Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use class constants in @Security annotation using the Symfony Expression Language?

I am using Symfony 3 and I've created a custom Voter class.

I want to access it using the SensioFrameworkExtraBundle @Security tag.

It kind of works.

If I do the following it works perfectly:

 /**
 * @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 don't like the idea of using magic strings in the application and I would much rather use a class constant for the check.

Something like this:

/**
 * @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 that I get the following error message:

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

Which when unescaped, is the following:

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

So I'm stumped on this.

Can it be done?

Any suggestions on a better way to do this?

like image 984
Jayd Avatar asked Jun 16 '17 13:06

Jayd


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)")
like image 52
gp_sflover Avatar answered Nov 16 '22 10:11

gp_sflover


Doctrine annotation reader has 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 just as expected for @Security / @IsGranted.

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

like image 13
Alister Bulman Avatar answered Nov 16 '22 10:11

Alister Bulman