Skip to content

Commit

Permalink
Introduce PluginConfigurator
Browse files Browse the repository at this point in the history
This allows for configuring plugins via the normal config.

When you have a plugin that does not require config, the old behavior is the easiest.

But when you do want custom config per client, it will be cumbersome to create separate services
and reference them everywhere.

It would be easier to have the same type of configuration as the built-in clients.

That's now possible with the PluginConfigurator.

Define the plugins as follows:
```yaml
'plugins' => [
    [
        'reference' => [
            'id' => CustomPluginConfigurator::class,
            'config' => [
                'name' => 'foo',
            ]
        ],
    ],
],
```

The `CustomPluginConfigurator` looks like this:
```php
final class CustomPluginConfigurator implements PluginConfigurator
{
    public static function getConfigTreeBuilder() : TreeBuilder
    {
        $treeBuilder = new TreeBuilder('custom_plugin');
        $rootNode = $treeBuilder->getRootNode();

        $rootNode
            ->children()
                ->scalarNode('name')
                    ->isRequired()
                    ->cannotBeEmpty()
                ->end()
            ->end();

        return $treeBuilder;
    }

    public function create(array $config) : CustomPlugin
    {
        return new CustomPlugin($config['name']);
    }
}
```

On compile time, the config will be evaluated. It will create the service definition
by calling the `create` method with the given config.

On runtime you will have the CustomPlugin instantiated with the custom config.
  • Loading branch information
ruudk committed Nov 18, 2024
1 parent f64bbf0 commit e62fd49
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,11 @@ private function createClientPluginNode(): ArrayNodeDefinition
->isRequired()
->cannotBeEmpty()
->end()
->arrayNode('config')
->normalizeKeys(false)
->prototype('variable')
->end()
->end()
->end()
->end()
->arrayNode('add_host')
Expand Down
15 changes: 15 additions & 0 deletions src/DependencyInjection/HttplugExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,14 @@
use Http\Client\HttpAsyncClient;
use Http\Client\Plugin\Vcr\RecordPlugin;
use Http\Client\Plugin\Vcr\ReplayPlugin;
use Http\HttplugBundle\PluginConfigurator;
use Http\Message\Authentication\BasicAuth;
use Http\Message\Authentication\Bearer;
use Http\Message\Authentication\Header;
use Http\Message\Authentication\QueryParam;
use Http\Message\Authentication\Wsse;
use Http\Mock\Client as MockClient;
use LogicException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\UriInterface;
use Symfony\Component\Config\Definition\ConfigurationInterface;
Expand Down Expand Up @@ -427,6 +429,19 @@ private function configureClient(ContainerBuilder $container, string $clientName

switch ($pluginName) {
case 'reference':
if ($pluginConfig['config'] !== []) {
if (! is_a($pluginConfig['id'], PluginConfigurator::class, true)) {
throw new LogicException(sprintf('The plugin "%s" is not a valid PluginConfigurator.', $pluginConfig['id']));
}

$config = $pluginConfig['id']::getConfigTreeBuilder()->buildTree()->finalize($pluginConfig['config']);

$definition = new Definition(null, [$config]);
$definition->setFactory([new Reference($pluginConfig['id']), 'create']);

$plugins[] = $definition;
break;
}
$plugins[] = new Reference($pluginConfig['id']);
break;
case 'authentication':
Expand Down
20 changes: 20 additions & 0 deletions src/PluginConfigurator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

declare(strict_types=1);

namespace Http\HttplugBundle;

use Http\Client\Common\Plugin;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

interface PluginConfigurator
{
public static function getConfigTreeBuilder() : TreeBuilder;

/**
* Creates the plugin with the given config.
*
* @param array<mixed> $config
*/
public function create(array $config) : Plugin;
}
24 changes: 24 additions & 0 deletions tests/Resources/CustomPlugin.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types=1);

namespace Http\HttplugBundle\Tests\Resources;

use Http\Client\Common\Plugin;
use Http\Promise\Promise;
use Psr\Http\Message\RequestInterface;

final class CustomPlugin implements Plugin
{
private string $name;

public function __construct(string $name)
{
$this->name = $name;
}

public function handleRequest(RequestInterface $request, callable $next, callable $first) : Promise
{
return $next($request);
}
}
32 changes: 32 additions & 0 deletions tests/Resources/CustomPluginConfigurator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Http\HttplugBundle\Tests\Resources;

use Http\HttplugBundle\PluginConfigurator;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

final class CustomPluginConfigurator implements PluginConfigurator
{
public static function getConfigTreeBuilder() : TreeBuilder
{
$treeBuilder = new TreeBuilder('custom_plugin');
$rootNode = $treeBuilder->getRootNode();

$rootNode
->children()
->scalarNode('name')
->isRequired()
->cannotBeEmpty()
->end()
->end();

return $treeBuilder;
}

public function create(array $config) : CustomPlugin
{
return new CustomPlugin($config['name']);
}
}
11 changes: 11 additions & 0 deletions tests/Resources/Fixtures/config/full.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

declare(strict_types=1);

use Http\HttplugBundle\Tests\Resources\CustomPlugin;
use Http\HttplugBundle\Tests\Resources\CustomPluginConfigurator;

$container->loadFromExtension('httplug', [
'default_client_autowiring' => false,
'main_alias' => [
Expand All @@ -27,6 +30,14 @@
'http_methods_client' => true,
'plugins' => [
'httplug.plugin.redirect',
[
'reference' => [
'id' => CustomPluginConfigurator::class,
'config' => [
'name' => 'foo',
]
],
],
[
'add_host' => [
'host' => 'http://localhost',
Expand Down
7 changes: 7 additions & 0 deletions tests/Resources/Fixtures/config/full.xml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
</classes>
<client name="test" factory="httplug.factory.guzzle7" http-methods-client="true">
<plugin>httplug.plugin.redirect</plugin>
<plugin>
<reference id="Http\HttplugBundle\Tests\Resources\CustomPluginConfigurator">
<config>
<name>foo</name>
</config>
</reference>
</plugin>
<plugin>
<add-host host="http://localhost"/>
</plugin>
Expand Down
5 changes: 5 additions & 0 deletions tests/Resources/Fixtures/config/full.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ httplug:
http_methods_client: true
plugins:
- 'httplug.plugin.redirect'
-
reference:
id: Http\HttplugBundle\Tests\Resources\CustomPluginConfigurator
config:
name: foo
-
add_host:
host: http://localhost
Expand Down
12 changes: 12 additions & 0 deletions tests/Unit/DependencyInjection/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
use Http\Adapter\Guzzle7\Client;
use Http\HttplugBundle\DependencyInjection\Configuration;
use Http\HttplugBundle\DependencyInjection\HttplugExtension;
use Http\HttplugBundle\Tests\Resources\CustomPlugin;
use Http\HttplugBundle\Tests\Resources\CustomPluginConfigurator;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionConfigurationTestCase;
use Nyholm\Psr7\Factory\Psr17Factory;
use Symfony\Component\Config\Definition\ConfigurationInterface;
Expand Down Expand Up @@ -153,6 +155,16 @@ public function testSupportsAllConfigFormats(): void
'reference' => [
'enabled' => true,
'id' => 'httplug.plugin.redirect',
'config' => [],
],
],
[
'reference' => [
'enabled' => true,
'id' => CustomPluginConfigurator::class,
'config' => [
'name' => 'foo',
],
],
],
[
Expand Down
36 changes: 36 additions & 0 deletions tests/Unit/DependencyInjection/HttplugExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
use Http\Adapter\Guzzle7\Client;
use Http\Client\Plugin\Vcr\Recorder\InMemoryRecorder;
use Http\HttplugBundle\DependencyInjection\HttplugExtension;
use Http\HttplugBundle\Tests\Resources\CustomPluginConfigurator;
use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;
use Psr\Http\Client\ClientInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

/**
Expand Down Expand Up @@ -203,6 +205,40 @@ public function testClientPlugins(): void
$this->assertContainerBuilderHasService('httplug.client.mock');
}

public function testPluginConfiguratorConfig(): void
{
$config = [
'clients' => [
'acme' => [
'factory' => 'httplug.factory.curl',
'plugins' => [
[
'reference' => [
'id' => CustomPluginConfigurator::class,
'config' => [
'name' => 'foo',
]
],
],
],
],
],
];

$this->load($config);

$definition = new Definition(null, [
['name' => 'foo'],
]);
$definition->setFactory([CustomPluginConfigurator::class, 'create']);

$this->assertContainerBuilderHasService('httplug.client.acme');
$this->assertContainerBuilderHasServiceDefinitionWithArgument('httplug.client.acme', 1, [
$definition
]);
$this->assertContainerBuilderHasService('httplug.client.mock');
}

public function testNoProfilingWhenNotInDebugMode(): void
{
$this->setParameter('kernel.debug', false);
Expand Down

0 comments on commit e62fd49

Please sign in to comment.