gpt4 book ai didi

php - 如何在 Symfony2 中正确启用 twig 的沙箱扩展?

转载 作者:行者123 更新时间:2023-12-03 23:22:19 25 4
gpt4 key购买 nike

在 Symfony2 中,默认禁用了一些 Twig 模块。其中之一是调试扩展,它添加了 {% debug %} 标签(在开发环境中很有用)。

要启用它,没什么特别困难的,您可以将此服务添加到您的配置中:

  debug.twig.extension:
class: Twig_Extensions_Extension_Debug
tags:
- { name: 'twig.extension' }

但是如何启用{% sandbox %}标签呢?

我的问题是扩展的构造函数采用了安全策略:

public function __construct(Twig_Sandbox_SecurityPolicyInterface $policy, $sandboxed = false)
{
$this->policy = $policy;
$this->sandboxedGlobally = $sandboxed;
}

通过阅读 twig documentation ,我看到了原生的方式(没有 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);

我可以在使用沙箱之前在服务内部做类似的事情,但这不像我们习惯的依赖注入(inject)那样清晰。

是否有更好/正确的方法在 Symfony2 中启用 twig 的沙箱扩展?

最佳答案

为什么不创建一个安全策略的私有(private)服务:

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

然后您可以将此服务注入(inject) twig.sandbox.extension 服务:

twig.sandbox.extension:
class: Twig_Extension_Sandbox
arguments:
- @twig.sandbox.policy
tags:
- { name: twig.extension }

完成。将 twig.sandbox.policy 标记为私有(private)可确保无法使用容器访问它(它仍然可以注入(inject)其他服务,但我认为这不是问题)。

免责声明:我没有对此进行测试,它可能需要一些调整才能真正起作用,所以不要复制粘贴!

关于php - 如何在 Symfony2 中正确启用 twig 的沙箱扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16070602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com