How to use class constants in @Security annotation using symfony expression language?

I use Symfony 3 and I created my own Voter class.

I want to access it with @Security tag.

It kind of works.

If I do the following, this works fine:

  /** * @Rest\Get("organisation/{id}") * @Security("is_granted('OrgAdmin', id)") * @param int $id * @param Request $request * * @return View */ public function getOrganisationAction($id, Request $request) { 

But I do not like the idea of ​​using magic strings in the application, and I would prefer to use the class constant for checking.

Something like that:

 /** * @Rest\Get("organisation/{id}") * @Security("is_granted(AppBundle\OrgRoles::ROLE_ADMIN, id)") * @param int $id * @param Request $request * * @return View */ public function getOrganisationAction($id, Request $request) { 

But when I try to do this, I get the following error message:

 Unexpected character \"\\\" around position 20 for expression 'is_granted(AppBundle\\OrgRoles::ROLE_ADMIN, id)'. 

Which, when not abandoned, is as follows:

 Unexpected character "\" around position 20 for expression 'is_granted(AppBundle\OrgRoles::ROLE_ADMIN, id)'. 

So I'm confused.

It can be done?

Any suggestions on a better way to do this?

+10
source share
2 answers

You can use the constant() function available in the expression language component :

 @Security("is_granted(constant('\\Full\\Namespace\\To\\OrgRoles::ROLE_ADMIN'), id)") 
+10
source

Doctrine annotation reader made this even easier for constants in PHP code:

 use MyCompany\Annotations\Bar; use MyCompany\Entity\SomeClass; /** * @Foo(PHP_EOL) * @Bar(Bar::FOO) */ 

This also works as expected for @ Security / @ IsGranted.

https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/custom.html#constants

+3
source

Source: https://habr.com/ru/post/1268906/


All Articles