Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a priority attribute on doctrine.middleware tag and #[AsMiddleware] attribute #1676

Merged
merged 2 commits into from
Jun 15, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Attribute/AsMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ class AsMiddleware
/** @param string[] $connections */
public function __construct(
public array $connections = [],
public ?int $priority = null,
) {
}
}
38 changes: 31 additions & 7 deletions DependencyInjection/Compiler/MiddlewaresPass.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

use function array_key_exists;
use function array_keys;
use function in_array;
use function array_map;
use function array_values;
use function is_subclass_of;
use function sprintf;
use function uasort;

final class MiddlewaresPass implements CompilerPassInterface
{
Expand All @@ -22,30 +25,39 @@ public function process(ContainerBuilder $container): void

$middlewareAbstractDefs = [];
$middlewareConnections = [];
$middlewarePriorities = [];
foreach ($container->findTaggedServiceIds('doctrine.middleware') as $id => $tags) {
$middlewareAbstractDefs[$id] = $container->getDefinition($id);
// When a def has doctrine.middleware tags with connection attributes equal to connection names
// registration of this middleware is limited to the connections with these names
foreach ($tags as $tag) {
if (! isset($tag['connection'])) {
if (isset($tag['priority']) && ! isset($middlewarePriorities[$id])) {
$middlewarePriorities[$id] = $tag['priority'];
}

continue;
}

$middlewareConnections[$id][] = $tag['connection'];
$middlewareConnections[$id][$tag['connection']] = $tag['priority'] ?? null;
}
}

foreach (array_keys($container->getParameter('doctrine.connections')) as $name) {
$middlewareDefs = [];
$i = 0;
foreach ($middlewareAbstractDefs as $id => $abstractDef) {
if (isset($middlewareConnections[$id]) && ! in_array($name, $middlewareConnections[$id], true)) {
if (isset($middlewareConnections[$id]) && ! array_key_exists($name, $middlewareConnections[$id])) {
continue;
}

$middlewareDefs[] = $childDef = $container->setDefinition(
sprintf('%s.%s', $id, $name),
new ChildDefinition($id)
);
$middlewareDefs[$id] = [
$childDef = $container->setDefinition(
sprintf('%s.%s', $id, $name),
new ChildDefinition($id)
),
++$i,
];

if (! is_subclass_of($abstractDef->getClass(), ConnectionNameAwareInterface::class)) {
continue;
Expand All @@ -54,6 +66,18 @@ public function process(ContainerBuilder $container): void
$childDef->addMethodCall('setConnectionName', [$name]);
}

$middlewareDefs = array_map(
static fn ($id, $def) => [
$middlewareConnections[$id][$name] ?? $middlewarePriorities[$id] ?? 0,
$def[1],
$def[0],
],
array_keys($middlewareDefs),
array_values($middlewareDefs),
);
uasort($middlewareDefs, static fn ($a, $b) => $b[0] <=> $a[0] ?: $a[1] <=> $b[1]);
dmaicher marked this conversation as resolved.
Show resolved Hide resolved
$middlewareDefs = array_map(static fn ($value) => $value[2], $middlewareDefs);

$container
->getDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name))
->addMethodCall('setMiddlewares', [$middlewareDefs]);
Expand Down
6 changes: 4 additions & 2 deletions DependencyInjection/DoctrineExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,14 +207,16 @@ protected function dbalLoad(array $config, ContainerBuilder $container)
$container->registerForAutoconfiguration(MiddlewareInterface::class)->addTag('doctrine.middleware');

$container->registerAttributeForAutoconfiguration(AsMiddleware::class, static function (ChildDefinition $definition, AsMiddleware $attribute) {
$priority = isset($attribute->priority) ? ['priority' => $attribute->priority] : [];

if ($attribute->connections === []) {
$definition->addTag('doctrine.middleware');
$definition->addTag('doctrine.middleware', $priority);

return;
}

foreach ($attribute->connections as $connName) {
$definition->addTag('doctrine.middleware', ['connection' => $connName]);
$definition->addTag('doctrine.middleware', array_merge($priority, ['connection' => $connName]));
}
});

Expand Down
218 changes: 216 additions & 2 deletions Tests/DependencyInjection/Compiler/MiddlewarePassTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

use function array_map;
use function implode;
use function sprintf;

use const PHP_VERSION_ID;
Expand Down Expand Up @@ -148,6 +150,194 @@ public function testDontAddMiddlewareWhenDbalIsNotUsed(string $middlewareClass,
self::assertCount(0, $middlewareDefinitions);
}

public function testAddMiddlewareOrderingWithDefaultPriority(): void
{
$container = $this->createContainer(static function (ContainerBuilder $container) {
$container
->register('middleware1', PHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware');

$container
->register('middleware2', ConnectionAwarePHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware');

$container
->setAlias('conf_conn1', 'doctrine.dbal.conn1_connection.configuration')
->setPublic(true); // Avoid removal and inlining
});

$this->assertMiddlewareInjected($container, 'conn1', PHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn1', ConnectionAwarePHP7Middleware::class, true);
$this->assertMiddlewareOrdering($container, 'conn1', [PHP7Middleware::class, ConnectionAwarePHP7Middleware::class]);
}

public function testAddMiddlewareOrderingWithExplicitPriority(): void
{
$container = $this->createContainer(static function (ContainerBuilder $container) {
$container
->register('middleware1', PHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware');

$container
->register('middleware2', ConnectionAwarePHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware', ['priority' => 2]);

$container
->setAlias('conf_conn1', 'doctrine.dbal.conn1_connection.configuration')
->setPublic(true); // Avoid removal and inlining
});

$this->assertMiddlewareInjected($container, 'conn1', PHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn1', ConnectionAwarePHP7Middleware::class, true);
$this->assertMiddlewareOrdering($container, 'conn1', [ConnectionAwarePHP7Middleware::class, PHP7Middleware::class]);
}

public function testAddMiddlewareOrderingWithExplicitPriorityAndConnection(): void
{
$container = $this->createContainer(static function (ContainerBuilder $container) {
$container
->register('middleware1', PHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware');

$container
->register('middleware2', ConnectionAwarePHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware', ['connection' => 'conn1', 'priority' => 2]);

$container
->setAlias('conf_conn1', 'doctrine.dbal.conn1_connection.configuration')
->setPublic(true); // Avoid removal and inlining

$container
->setAlias('conf_conn2', 'doctrine.dbal.conn2_connection.configuration')
->setPublic(true); // Avoid removal and inlining
});

$this->assertMiddlewareInjected($container, 'conn1', PHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn1', ConnectionAwarePHP7Middleware::class, true);
$this->assertMiddlewareInjected($container, 'conn2', PHP7Middleware::class);
$this->assertMiddlewareNotInjected($container, 'conn2', ConnectionAwarePHP7Middleware::class);
$this->assertMiddlewareOrdering($container, 'conn1', [ConnectionAwarePHP7Middleware::class, PHP7Middleware::class]);
}

public function testAddMiddlewareOrderingWithExplicitPriorityPerConnection(): void
{
$container = $this->createContainer(static function (ContainerBuilder $container) {
$container
->register('middleware1', PHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware');

$container
->register('middleware2', ConnectionAwarePHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware', ['connection' => 'conn1', 'priority' => 2])
->addTag('doctrine.middleware', ['connection' => 'conn2', 'priority' => -2]);

$container
->setAlias('conf_conn1', 'doctrine.dbal.conn1_connection.configuration')
->setPublic(true); // Avoid removal and inlining

$container
->setAlias('conf_conn2', 'doctrine.dbal.conn2_connection.configuration')
->setPublic(true); // Avoid removal and inlining
});

$this->assertMiddlewareInjected($container, 'conn1', PHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn1', ConnectionAwarePHP7Middleware::class, true);
$this->assertMiddlewareInjected($container, 'conn2', PHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn2', ConnectionAwarePHP7Middleware::class, true);
$this->assertMiddlewareOrdering($container, 'conn1', [ConnectionAwarePHP7Middleware::class, PHP7Middleware::class]);
$this->assertMiddlewareOrdering($container, 'conn2', [PHP7Middleware::class, ConnectionAwarePHP7Middleware::class]);
}

public function testAddMiddlewareOrderingWithInheritedPriorityPerConnection(): void
{
$container = $this->createContainer(static function (ContainerBuilder $container) {
$container
->register('middleware1', PHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware');

$container
->register('middleware2', ConnectionAwarePHP7Middleware::class)
->setAbstract(true)
->addTag('doctrine.middleware', ['priority' => 2])
->addTag('doctrine.middleware', ['connection' => 'conn1']);

$container
->register('middleware3', 'some_middleware_class')
->setAbstract(true)
->addTag('doctrine.middleware', ['priority' => 1])
->addTag('doctrine.middleware', ['connection' => 'conn1'])
->addTag('doctrine.middleware', ['connection' => 'conn2', 'priority' => -1]);

$container
->setAlias('conf_conn1', 'doctrine.dbal.conn1_connection.configuration')
->setPublic(true); // Avoid removal and inlining

$container
->setAlias('conf_conn2', 'doctrine.dbal.conn2_connection.configuration')
->setPublic(true); // Avoid removal and inlining
});

$this->assertMiddlewareInjected($container, 'conn1', PHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn1', ConnectionAwarePHP7Middleware::class, true);
$this->assertMiddlewareInjected($container, 'conn1', 'some_middleware_class');
$this->assertMiddlewareInjected($container, 'conn2', PHP7Middleware::class);
$this->assertMiddlewareNotInjected($container, 'conn2', ConnectionAwarePHP7Middleware::class);
$this->assertMiddlewareInjected($container, 'conn2', 'some_middleware_class');
$this->assertMiddlewareOrdering($container, 'conn1', [ConnectionAwarePHP7Middleware::class, 'some_middleware_class', PHP7Middleware::class]);
$this->assertMiddlewareOrdering($container, 'conn2', [PHP7Middleware::class, 'some_middleware_class']);
}

/** @requires PHP 8 */
public function testAddMiddlewareOrderingWithAttributeForAutoconfiguration(): void
{
$container = $this->createContainer(static function (ContainerBuilder $container) {
$container
->register('middleware1', AutoconfiguredMiddleware::class)
->setAutoconfigured(true);

$container
->register('middleware2', AutoconfiguredMiddlewareWithConnection::class)
->setAutoconfigured(true);

$container
->register('middleware3', AutoconfiguredMiddlewareWithPriority::class)
->setAutoconfigured(true);

$container
->setAlias('conf_conn1', 'doctrine.dbal.conn1_connection.configuration')
->setPublic(true); // Avoid removal and inlining

$container
->setAlias('conf_conn2', 'doctrine.dbal.conn2_connection.configuration')
->setPublic(true); // Avoid removal and inlining
});

$this->assertMiddlewareInjected($container, 'conn1', AutoconfiguredMiddleware::class);
$this->assertMiddlewareNotInjected($container, 'conn1', AutoconfiguredMiddlewareWithConnection::class);
$this->assertMiddlewareInjected($container, 'conn1', AutoconfiguredMiddlewareWithPriority::class);
$this->assertMiddlewareInjected($container, 'conn2', AutoconfiguredMiddleware::class);
$this->assertMiddlewareInjected($container, 'conn2', AutoconfiguredMiddlewareWithConnection::class);
$this->assertMiddlewareInjected($container, 'conn2', AutoconfiguredMiddlewareWithPriority::class);
$this->assertMiddlewareOrdering($container, 'conn1', [
AutoconfiguredMiddlewareWithPriority::class,
AutoconfiguredMiddleware::class,
]);
$this->assertMiddlewareOrdering($container, 'conn2', [
AutoconfiguredMiddlewareWithPriority::class,
AutoconfiguredMiddleware::class,
AutoconfiguredMiddlewareWithConnection::class,
]);
}

private function createContainer(callable $func, bool $addConnections = true): ContainerBuilder
{
$container = new ContainerBuilder(new ParameterBag(['kernel.debug' => false]));
Expand Down Expand Up @@ -223,8 +413,27 @@ private function assertMiddlewareNotInjected(
));
}

/** @param string[] $expectedOrder */
private function assertMiddlewareOrdering(
ContainerBuilder $container,
string $connName,
array $expectedOrder
): void {
$middlewareFound = $this->getMiddlewaresForConn($container, $connName);
$classes = array_map(
static fn (Definition $def): string => $def->getClass() ?? '',
$middlewareFound,
);

$this->assertSame($expectedOrder, $classes, sprintf(
'Middlewares ordered as %s in doctrine.dbal.%s_connection.configuration',
implode(', ', $classes),
$connName
));
}

/** @return Definition[] */
private function getMiddlewaresForConn(ContainerBuilder $container, string $connName, string $middlewareClass): array
private function getMiddlewaresForConn(ContainerBuilder $container, string $connName, ?string $middlewareClass = null): array
{
$calls = $container->getDefinition('conf_' . $connName)->getMethodCalls();
$middlewaresFound = [];
Expand All @@ -234,7 +443,7 @@ private function getMiddlewaresForConn(ContainerBuilder $container, string $conn
}

foreach ($call[1][0] as $middlewareDef) {
if ($middlewareDef->getClass() !== $middlewareClass) {
if (isset($middlewareClass) && $middlewareDef->getClass() !== $middlewareClass) {
continue;
}

Expand Down Expand Up @@ -275,4 +484,9 @@ class AutoconfiguredMiddleware
class AutoconfiguredMiddlewareWithConnection
{
}

#[AsMiddleware(priority: 2)]
class AutoconfiguredMiddlewareWithPriority
{
}
}