Override extension configuration via compiler pass

624 views Asked by At

Hope you are doing well, I'm trying to override an existent api platform configuration api_platform.mapping.paths via a some kinda of custom Compiler Pass

The goal is to merge my new configuration with the existing one

Here is the configuration part that I would like to update it at the height of the complication of my container:

# api/config/packages/api_platform.yaml
api_platform:

    mapping:
        # The list of paths with files or directories where the bundle will look for additional resource files.
        paths: []

This is my custom compiler pass:

/**
 * Class MergeApiMappingPathsConfigurationPass.
 */
class MergeApiMappingPathsConfigurationPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {

        $configs = $container->getExtensionConfig('api_platform');
        $configs[0]['mapping']['paths'] = array_merge($configs[0]['mapping']['paths'], [__DIR__.'/../../Resources/resources/']);
        $container->prependExtensionConfig('api_platform', $configs[0]);

    }
}

And this is my root bundle where I registered my new custom compiler:

class DemoBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {

        parent::build($container);
        $container->addCompilerPass(new MergeApiMappingPathsConfigurationPass());
    }
}

The problem that my new configuration is not taken into account and it's not working properly.

1

There are 1 answers

1
craigh On BEST ANSWER

I do not think you want to use a CompilerPass for this. I think you want to use PrependExtensionInterface and the prepend method. (see https://symfony.com/doc/current/bundles/prepend_extension.html)

Something like

class DemoBundleExtension extends Extension implements PrependExtensionInterface
{
    public function prepend(ContainerBuilder $container)
    {
        if (!isset($container->getExtensions()['api_platform'])) {
            return;
        }
        $configs = $container->getExtensionConfig('api_platform');
        $configs[0]['mapping']['paths'] = array_merge($configs[0]['mapping']['paths'], [__DIR__.'/../../Resources/resources/']);
        $container->prependExtensionConfig('api_platform', ['mapping' => $configs]);
    }

    public function build(ContainerBuilder $container)
    {
        parent::build($container);
    }
}

I may have some of the details wrong, but this might give you a start on the right approach.