1

我在一个 symfony 2.8 项目中。另一位开发人员编写了一个 Voter 来检查用户是否具有特定任务的权限。我已经在控制器中使用此功能没有问题,但现在我正在编写一个服务来获取动态菜单,但我不知道如何访问该方法isGranted

错误:试图调用类的名为“isGranted”的未定义方法。

namespace NameSpaceQuestion\Question\Service;

use Doctrine\ORM\EntityManager;

class MenuBuilder
{

    private $areasTools;
    public $menuItems = array();
    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function createMenuCourse($course,$mode,$user)
    {
        $repository = $this->em->getRepository('eBundle:AreasTools');
        $areas = $repository->findAll();
        //Retrieve every area from the db
        $itemsMenu = array();

        foreach ($areas as $area) {

            //If the user has permissions the area is included in the menu and proceed to check the tools that belong to the current area
            if($this->isGranted( $mode,$area,$user ) ){
                $itemsMenu[$area->getName()] = array();
                $toolsPerCourse = $this->em->getRepository('eBundle:CourseTool')->findByAreaToolAndCourse($area, $course);
                foreach ($toolsPerCourse as $toolCourse) {
                    //If the user has permissions the tool is included in the menu under the respective Area
                    if( ($this->isGranted( $mode,$toolCourse,$user ) )){
                        array_push($itemsMenu[$area->getName()], $toolCourse->getName());
                    }
                }

            }
        }

        return $itemsMenu;
    }
}
4

2 回答 2

4

您必须使用依赖注入在 MenuBuilder 类中获取 AuthorizationChecker。你可以在这里阅读: http: //symfony.com/doc/current/cookbook/security/securing_services.html

因为看起来您已经在注入 EntityManager,所以只需将 AuthorizationChecker 添加到您的代码中:

use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

class MenuBuilder
{

    protected $authorizationChecker;

    public function __construct(EntityManager $em, AuthorizationCheckerInterface $authorizationChecker)
    {
        $this->authorizationChecker = $authorizationChecker;
        $this->em = $em;
    }

    function createMenuCourse()
    {
         if ( $this->authorizationChecker->isGranted('EDIT',$user) ) {
               //build menu
         }
    }
}
于 2016-05-18T15:26:37.787 回答
1

首先要了解的是 Symfony 基本控制器有许多辅助函数,例如实现了 isGranted。但是,当然,如果您不在控制器内部,那么您将无权访问它们。另一方面,查看基类并复制所需的功能是有益的。

isGranted 功能依赖于授权检查器服务,您需要将其注入到菜单构建器中,结果如下:

class MenuBuilder
{
    private $em;
    private $authorizationChecker;

    public function __construct(
        EntityManager $em, 
        $authorizationChecker // security.authorization_checker
    ) {
        $this->em = $em;
        $this->authorizationChecker = $authorizationChecker;
    }    
    protected function isGranted($attributes, $object = null)
    {
        return $this->authorizationChecker->isGranted($attributes, $object);
    }

该死。斯蒂芬比我领先一分钟。必须学会更快地打字。

于 2016-05-18T15:27:59.033 回答