Symfony2 get to the access_control parameters located in the security.yml

前端 未结 2 1272
北海茫月
北海茫月 2021-01-06 00:32

I\'m trying to get the access_control parameters which are located in my security.yml as an array in my custom service.

Just like with getting the role_hierarchy para

2条回答
  •  [愿得一人]
    2021-01-06 01:18

    There's no way to get the access_control parameter from the container.
    This is because this parameter is only used to create request matchers which will be registered as AccessMap later given in the AccessListener, and then are left over without registering it into the container.

    You can try something hacky to get these matchers back by getting them like

    $context  = $this->get("security.firewall.map.context.main")->getContext();
    $listener = $context[0][5];
    // Do reflection on "map" private member
    

    But this is kind of an ugly solution.

    Another way I can see on how to get them is to parse again the security file

    use Symfony\Component\Yaml\Yaml;
    
    $file   = sprintf("%s/config/security.yml", $this->container->getParameter('kernel.root_dir'));
    $parsed = Yaml::parse(file_get_contents($file));
    
    $access = $parsed['security']['access_control'];
    

    If you want to register this configuration into a service, you can do something like

    services.yml

    services:
        acme.config_provider:
            class: Acme\FooBundle\ConfigProvider
            arguments:
                - "%kernel.root_dir%"
        acme.my_service:
            class: Acme\FooBundle\MyService
            arguments:
                - "@acme.config_provider"
    

    Acme\FooBundle\ConfigProvider

    use Symfony\Component\Yaml\Yaml;
    
    class ConfigProvider
    {
        protected $rootDir;
    
        public function __construct($rootDir)
        {
            $this->rootDir = $rootDir;
        }
    
        public function getConfiguration()
        {
            $file = sprintf(
                "%s/config/security.yml",
                $this->rootDir
            );
            $parsed = Yaml::parse(file_get_contents($file));
    
            return $parsed['security']['access_control'];
        }
    }
    

    Acme\FooBundle\MyService

    class MyService
    {
        protected $provider;
    
        public function __construct(ConfigProvider $provider)
        {
            $this->provider = $provider;
        }
    
        public function doAction()
        {
            $access = $this->provider->getConfiguration();
    
            foreach ($access as $line) {
                // ...
            }
        }
    }
    

提交回复
热议问题