postoffice-1.0.x-dev/src/DependencyInjection/Compiler/StackedMailerPass.php
src/DependencyInjection/Compiler/StackedMailerPass.php
<?php
namespace Drupal\postoffice\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Provides a compiler pass for stacked mailer.
*
* Build a mailer by collecting all services tagged
* 'postoffice.mailer_middleware' and assembles them into a stack. The
* middleware with the highest priority ends up as the outermost while the
* lowest priority middleware wraps the actual mailer defined by the
* postoffice.mailer.basic service.
*/
class StackedMailerPass implements CompilerPassInterface {
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container): void {
if (!$container->hasDefinition('postoffice.mailer')) {
return;
}
$stacked_mailer = $container->getDefinition('postoffice.mailer');
$middlewares = [];
$priorities = [];
foreach ($container->findTaggedServiceIds('postoffice.mailer_middleware') as $id => $attributes) {
$priorities[$id] = $attributes[0]['priority'] ?? 0;
$middlewares[$id] = $container->getDefinition($id);
}
array_multisort($priorities, SORT_ASC, $middlewares);
$decorated_id = 'postoffice.mailer.basic';
$middlewares_param = [new Reference($decorated_id)];
foreach ($middlewares as $id => $decorator) {
// Prepend a reference to the middlewares container parameter.
array_unshift($middlewares_param, new Reference($id));
// Prepend the inner body renderer as first constructor argument.
$arguments = $decorator->getArguments();
array_unshift($arguments, new Reference($decorated_id));
$decorator->setArguments($arguments);
$decorated_id = $id;
}
$arguments = [$middlewares_param[0]];
$stacked_mailer->setArguments($arguments);
}
}
