Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 parameters 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?

like image 946
Robin Hermans Avatar asked Nov 07 '13 08:11

Robin Hermans


1 Answers

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) {
            // ...
        }
    }
}
like image 119
Touki Avatar answered Sep 22 '22 06:09

Touki