【问题标题】:How to use class constants in @Security annotation using the Symfony Expression Language?如何使用 Symfony 表达式语言在 @Security 注释中使用类常量?
【发布时间】:2017-11-19 08:04:11
【问题描述】:

我正在使用 Symfony 3,并且我创建了一个自定义 Voter 类。

我想使用 SensioFrameworkExtraBundle @Security 标签访问它。

有点用。

如果我执行以下操作,它会完美运行:

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

但我不喜欢在应用程序中使用魔术字符串的想法,我更愿意使用类常量进行检查。

类似这样的:

/**
 * @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)
{

但是当我尝试时,我收到以下错误消息:

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

未转义时,如下:

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

所以我被难住了。

可以吗?

有什么更好的方法可以做到这一点吗?

【问题讨论】:

    标签: php symfony namespaces expression


    【解决方案1】:

    您可以使用Expression Language Component中提供的constant()函数:

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

    【讨论】:

      【解决方案2】:

      Doctrine 注释阅读器让 PHP 代码中的常量更容易做到这一点:

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

      这对于@Security / @IsGranted 也可以正常工作。

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

      【讨论】:

      • 这应该添加到接受的答案中!感谢您的信息
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      相关资源
      最近更新 更多