Search code examples
phpmergeconfigurationyii2

Yii2 override nested config parameters


I merge my configs in this way:

$config = \yii\helpers\ArrayHelper::merge(
    (require (__DIR__ . '/../config/web.php')),
    (require __DIR__ . '/../config/overrides/web.php')
);

Here is the config/web.php

$config = [
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
                [
                    'class' => 'yii\log\EmailTarget',
                    'levels' => ['info'],
                    'categories' => ['parsingFailure'],
                    'logVars' => [],
                    'message' => [
                        'from' => ['system@host.com'],
                        'to' => ['support@host.com'],
                        'subject' => 'Message parsing failure',
                    ],
                ],
            ],
        ],
        //....some more components
    ]
];

Here is the override that I try to apply config/overrides/web.php

$config = [
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [],
        ],
    ]
];

So, my goal is to disable logging in local configuration. Of course it does not work, since the behavior of array_merge is different and nothing gets overridden.


Solution

  • From the docs:

    Recursive merging will be conducted if both arrays have an element of array type and are having the same key. [...] You can use yii\helpers\UnsetArrayValue object to unset value from previous array or yii\helpers\ReplaceArrayValue to force replace former value instead of recursive merging.

    So your second array should be

    'targets' =>  new \yii\helpers\ReplaceArrayValue([]),