Home > Blockchain >  How to test the new pattern using AbstractBundle from Symfony6.1?
How to test the new pattern using AbstractBundle from Symfony6.1?

Time:01-07

Since Symfony 6.1, instead of creating an extension class and another configuration class, our bundle class can now extend AbstractBundle to add this logic to the bundle class directly. This abstract class provides configuration hooks.

// src/AcmeSocialBundle.php
namespace Acme\SocialBundle;

use Symfony\Component\Config\Definition\Configurator\DefinitionConfigurator;
use Symfony\Component\HttpKernel\Bundle\AbstractBundle;

class AcmeSocialBundle extends AbstractBundle
{
    public function configure(DefinitionConfigurator $definition): void
    {
        $definition->rootNode()
            ->children()
                ->arrayNode('twitter')
                    ->children()
                        ->integerNode('client_id')->end()
                        ->scalarNode('client_secret')->end()
                    ->end()
                ->end() // twitter
            ->end()
        ;
    }

    public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
    {
        // Contrary to the Extension class, the "$config" variable is already merged
        // and processed. You can use it directly to configure the service container.
        $container->services()
            ->get('acme.social.twitter_client')
            ->arg(0, $config['twitter']['client_id'])
            ->arg(1, $config['twitter']['client_secret'])
        ;
    }
}

Symfony documentation explains how to test no more used configuration class.

class ConfigurationTest extends TestCase
{
    public function testEmptyConfiguration(): void
    {
        $config = Yaml::parse('');
        $processor = new Processor();

        $result = $processor->processConfiguration(
            new Configuration(),
            [$config]
        );
        
        self::assertSame($result, ['foo' => 'bar'],
        ]);
    }

But how to test my $definition in the configure method of this new pattern?

CodePudding user response:

In this case, we need to find a way to access the bundle configuration so that we can process and test it. There is usually a fixed configuration class behind the new structure (Symfony\Component\Config\Definition\Configuration), so the only thing you would need to do is retrieve it:

class ConfigurationTest extends TestCase
{
    public function testEmptyConfig(): void
    {
        $configuration = (new AcmeSocialBundle())
            ->getContainerExtension()
            ->getConfiguration([], new ContainerBuilder(new ParameterBag()))
        ;

        $configs = [Yaml::parse('...')];
        $result = (new Processor())->processConfiguration($configuration, $configs);

        self::assertSame(['foo' => 'bar'], $result);
    }
}

Note that the $configs variable should be an array of arrays (array of configs).

  • Related