Ala*_*blo 2 php sandbox symfony twig
在Symfony2中,默认情况下禁用了一些Twig模块.其中一个是调试扩展,它添加了{% debug %}标记(在开发环境中很有用).
要启用它,没有什么困难,您可以将此服务添加到您的配置中:
debug.twig.extension:
class: Twig_Extensions_Extension_Debug
tags:
- { name: 'twig.extension' }
Run Code Online (Sandbox Code Playgroud)
但是如何启用{% sandbox %}标签?
我的问题是扩展的构造函数采用安全策略:
public function __construct(Twig_Sandbox_SecurityPolicyInterface $policy, $sandboxed = false)
{
$this->policy = $policy;
$this->sandboxedGlobally = $sandboxed;
}
Run Code Online (Sandbox Code Playgroud)
通过阅读twig文档,我看到了本机的方式(没有Symfony2):
$tags = array('if');
$filters = array('upper');
$methods = array(
'Article' => array('getTitle', 'getBody'),
);
$properties = array(
'Article' => array('title', 'body'),
);
$functions = array('range');
$policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
$sandbox = new Twig_Extension_Sandbox($policy);
$twig->addExtension($sandbox);
Run Code Online (Sandbox Code Playgroud)
在使用沙盒之前,我可以在服务中做类似的事情,但这并不像我们习惯的依赖注入那么清晰.
是否有更好/正确的方法在Symfony2中启用twig的沙箱扩展?
为什么不创建安全策略的私有服务:
parameters:
twig.sandbox.tags:
- if
twig.sandbox.filters:
- upper
twig.sandbox.methods:
Article: [getTitle, getBody]
twig.sandbox.properties:
Article: [title, body]
twig.sandbox.functions:
- range
twig.sandbox.policy:
class: Twig_Sandbox_SecurityPolicy
arguments:
- %twig.sandbox.tags%
- %twig.sandbox.filters%
- %twig.sandbox.methods%
- %twig.sandbox.properties%
- %twig.sandbox.functions%
public: false
Run Code Online (Sandbox Code Playgroud)
然后,您可以将此服务注入twig.sandbox.extension服务:
twig.sandbox.extension:
class: Twig_Extension_Sandbox
arguments:
- @twig.sandbox.policy
tags:
- { name: twig.extension }
Run Code Online (Sandbox Code Playgroud)
完成.标记twig.sandbox.policy私有确保使用容器无法访问它(它仍然可以注入其他服务,但我认为这不是问题).
免责声明:我没有测试过这个,它可能需要一些调整才能实际工作,所以不要复制粘贴!
| 归档时间: |
|
| 查看次数: |
1940 次 |
| 最近记录: |