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

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

I'm trying to get the access_control parameters wich are located in my security.yml as an array in my custom service.
Just like with getting the role_hierarchy parametes I thought it would work with the following code:

$accessParameters = $this->container->getParameter('security.access_control');

Unfortunately this was not the case.
Can someone tell how to get the parameters?

回答1:

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) {             // ...         }     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!