我的最终目标是检查某个路由名称是否属于应用程序的安全区域。
我想,为了实现这一点,我应该解析security.yml,获得"防火墙"部分,并遍历每个防火墙,试图将我的路由名称的路径与"secured_area"防火墙的模式相匹配。
作为Symfony2的新手,我尝试挖掘它的源代码,以了解它是如何解析security.yml本身的,但这个过程中涉及的类的数量让我有点不知所措。
所以,我在寻求建议:
-
这是解决问题的正确方法吗?还是有更直接的解决方案?
-
有关于如何写这篇文章的提示吗?
好吧,我最终做了一些类似的事情:
$route = $this->router->getRouteCollection()->get($routeName);
$yamlParser = new Yaml'Parser();
$securityConfig = $yamlParser->parse(file_get_contents($this->securityFilePath));
foreach ($securityConfig['security']['firewalls'] as $firewallName => $definition) {
if (isset($definition['pattern']) && preg_match('{'.$definition['pattern'].'}', $route->getPath())) {
return $firewallName;
}
}
可能不是最干净的解决方案,但能起到作用。
使用Symfony 3还有另一种方法可以做到这一点https://symfony.com/blog/new-in-symfony-3-2-firewall-config-class-and-profiler
通过将防火墙映射注入控制器或服务,您可以使用getFirewallConfig(Request$Request)和与路由的url版本关联的伪请求。
类似这样的东西:
// Your controller or service
public function __construct(
UrlGeneratorInterface $router,
FirewallMapInterface $firewallMap,
) {
$this->router = $router;
$this->firewallMap = $firewallMap;
}
public function getFirewallId($routeName)
{
$fwConfig = $this->firewallMap->getFirewallConfig(
Request::create($this->router->generate($routeName),'GET'));
return $fwConfig->getName();
}