无法解析Symfony配置文件中布尔节点中的参数

时间:2019-07-11 15:49:34

标签: php symfony symfony4

我有一个(专用)捆绑包,需要使用布尔参数:

$rootNode
    ->addDefaultsIfNotSet()
    ->children()
        ->booleanNode('property_cache_enabled')->defaultTrue()->end()
    ->end()

当我希望它解析为kernel.debug时,会引发异常:

  

路径“ rvlt_digital_symfony_api.property_cache_enabled”的类型无效。预期为布尔值,但有字符串。

这是配置的相关部分:

rvlt_digital_symfony_api:
  property_cache_enabled: '%kernel.debug%'

如何解决?当我搜索此问题时,我仅发现与环境变量转换有关的内容;这没有帮助,因为这不是环境变量。

2 个答案:

答案 0 :(得分:0)

是的,您可能会喜欢这里的文档using_parameters_in_dic

答案 1 :(得分:0)

您可以使用值%kernel.debug%直接配置模块,而不必为此值设置显式配置。

更改配置类即可:

class ApplicationConfiguration implements ConfigurationInterface
{
    private $debug;

    public function  __construct($debug)
    {
        $this->debug = (bool) $debug;
    }

    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('rvlt_digital_symfony_api');

        $treeBuilder->getRootNode()
            ->addDefaultsIfNotSet()
            ->children()
                ->booleanNode('property_cache_enabled')->defaultValue($this->debug)->end()
            ->end();

        return $treeBuilder;
    }
}

还有您的扩展类,以便在实例化配置时,从容器中读取%kernel.debug%的值并将其注入配置实例中:

class ApplicationExtension extends Extension
{
     public function getConfiguration(array $config, ContainerBuilder $container)
    {
        return new Configuration($container->getParameter('kernel.debug'));
    }
}

这样,如果您没有为rvlt_digital_symfony_api.property_cache_enabled设置配置,则只需匹配应用程序的%kernel.debug%设置,这就是您首先要的设置。 (不过,您仍然可以配置该值并覆盖默认值。)

此用例已在此处的文档中明确讨论:Using Parameters within a Dependency Injection Class

相关问题