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

Adding support for decorating messenger handlers #2

Merged
merged 1 commit into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ class MyController
}
```

## Supported Features for Using Decorators

The following features currently support the use of decorators in your application:

* Controllers
* Messenger Handlers (when `symfony/messenger` is installed)

## License

This software is published under the [MIT License](LICENSE)
11 changes: 6 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@
"minimum-stability": "stable",
"require": {
"php": ">=8.2",
"yceruto/decorator": "^1.1",
"yceruto/decorator": "1.2.*",
"symfony/framework-bundle": "^6.4|^7.0"
},
"require-dev": {
"doctrine/doctrine-bundle": "^2.13",
"doctrine/orm": "^3.2",
"friendsofphp/php-cs-fixer": "^3.64",
"phpunit/phpunit": "^11.3",
"symfony/browser-kit": "^7.1",
"symfony/mime": "^7.1",
"symfony/serializer": "^7.1",
"symfony/yaml": "^7.1"
"symfony/browser-kit": "^7.2",
"symfony/messenger": "^7.2",
"symfony/mime": "^7.2",
"symfony/serializer": "^7.2",
"symfony/yaml": "^7.2"
},
"config": {
"sort-packages": true
Expand Down
2 changes: 2 additions & 0 deletions src/DecoratorBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@
use Symfony\Component\Serializer\SerializerInterface;
use Yceruto\Decorator\DecoratorInterface;
use Yceruto\DecoratorBundle\DependencyInjection\DecoratorsPass;
use Yceruto\DecoratorBundle\DependencyInjection\MessengerPass;

class DecoratorBundle extends AbstractBundle
{
public function build(ContainerBuilder $container): void
{
$container->addCompilerPass(new DecoratorsPass());
$container->addCompilerPass(new MessengerPass());
}

public function loadExtension(array $config, ContainerConfigurator $container, ContainerBuilder $builder): void
Expand Down
32 changes: 32 additions & 0 deletions src/DependencyInjection/MessengerPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Yceruto\DecoratorBundle\Messenger\Middleware\HandleMessageMiddleware;

class MessengerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition('messenger.middleware.handle_message')) {
return;
}

$middlewareDef = $container->getDefinition('messenger.middleware.handle_message');
$middlewareDef->setClass(HandleMessageMiddleware::class);
$middlewareDef->setAutowired(true);
}
}
164 changes: 164 additions & 0 deletions src/Messenger/Middleware/HandleMessageMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Messenger\Middleware;

use Psr\Log\LoggerAwareTrait;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Exception\HandlerFailedException;
use Symfony\Component\Messenger\Exception\LogicException;
use Symfony\Component\Messenger\Exception\NoHandlerForMessageException;
use Symfony\Component\Messenger\Handler\Acknowledger;
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
use Symfony\Component\Messenger\Handler\HandlersLocatorInterface;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
use Symfony\Component\Messenger\Stamp\AckStamp;
use Symfony\Component\Messenger\Stamp\FlushBatchHandlersStamp;
use Symfony\Component\Messenger\Stamp\HandledStamp;
use Symfony\Component\Messenger\Stamp\HandlerArgumentsStamp;
use Symfony\Component\Messenger\Stamp\NoAutoAckStamp;
use Yceruto\Decorator\DecoratorInterface;

/**
* @author Samuel Roze <[email protected]>
*/
class HandleMessageMiddleware implements MiddlewareInterface
{
use LoggerAwareTrait;

public function __construct(
private HandlersLocatorInterface $handlersLocator,
private bool $allowNoHandlers = false,
private ?DecoratorInterface $decorator = null,
) {
}

/**
* @throws NoHandlerForMessageException When no handler is found and $allowNoHandlers is false
*/
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$handler = null;
$message = $envelope->getMessage();

$context = [
'class' => $message::class,
];

$exceptions = [];
$alreadyHandled = false;
foreach ($this->handlersLocator->getHandlers($envelope) as $handlerDescriptor) {
if ($this->messageHasAlreadyBeenHandled($envelope, $handlerDescriptor)) {
$alreadyHandled = true;
continue;
}

try {
$handler = $handlerDescriptor->getHandler();
$batchHandler = $handlerDescriptor->getBatchHandler();

/** @var AckStamp $ackStamp */
if ($batchHandler && $ackStamp = $envelope->last(AckStamp::class)) {
$ack = new Acknowledger(get_debug_type($batchHandler), static function (?\Throwable $e = null, $result = null) use ($envelope, $ackStamp, $handlerDescriptor) {
if (null !== $e) {
$e = new HandlerFailedException($envelope, [$handlerDescriptor->getName() => $e]);
} else {
$envelope = $envelope->with(HandledStamp::fromDescriptor($handlerDescriptor, $result));
}

$ackStamp->ack($envelope, $e);
});

$result = $this->callHandler($handler, $message, $ack, $envelope->last(HandlerArgumentsStamp::class));

if (!\is_int($result) || 0 > $result) {
throw new LogicException(\sprintf('A handler implementing BatchHandlerInterface must return the size of the current batch as a positive integer, "%s" returned from "%s".', \is_int($result) ? $result : get_debug_type($result), get_debug_type($batchHandler)));
}

if (!$ack->isAcknowledged()) {
$envelope = $envelope->with(new NoAutoAckStamp($handlerDescriptor));
} elseif ($ack->getError()) {
throw $ack->getError();
} else {
$result = $ack->getResult();
}
} else {
$result = $this->callHandler($handler, $message, null, $envelope->last(HandlerArgumentsStamp::class));
}

$handledStamp = HandledStamp::fromDescriptor($handlerDescriptor, $result);
$envelope = $envelope->with($handledStamp);
$this->logger?->info('Message {class} handled by {handler}', $context + ['handler' => $handledStamp->getHandlerName()]);
} catch (\Throwable $e) {
$exceptions[$handlerDescriptor->getName()] = $e;
}
}

/** @var FlushBatchHandlersStamp $flushStamp */
if ($flushStamp = $envelope->last(FlushBatchHandlersStamp::class)) {
/** @var NoAutoAckStamp $stamp */
foreach ($envelope->all(NoAutoAckStamp::class) as $stamp) {
try {
$handler = $stamp->getHandlerDescriptor()->getBatchHandler();
$handler->flush($flushStamp->force());
} catch (\Throwable $e) {
$exceptions[$stamp->getHandlerDescriptor()->getName()] = $e;
}
}
}

if (null === $handler && !$alreadyHandled) {
if (!$this->allowNoHandlers) {
throw new NoHandlerForMessageException(\sprintf('No handler for message "%s".', $context['class']));
}

$this->logger?->info('No handler for message {class}', $context);
}

if (\count($exceptions)) {
throw new HandlerFailedException($envelope, $exceptions);
}

return $stack->next()->handle($envelope, $stack);
}

private function messageHasAlreadyBeenHandled(Envelope $envelope, HandlerDescriptor $handlerDescriptor): bool
{
/** @var HandledStamp $stamp */
foreach ($envelope->all(HandledStamp::class) as $stamp) {
if ($stamp->getHandlerName() === $handlerDescriptor->getName()) {
return true;
}
}

return false;
}

private function callHandler(callable $handler, object $message, ?Acknowledger $ack, ?HandlerArgumentsStamp $handlerArgumentsStamp): mixed
{
$arguments = [$message];
if (null !== $ack) {
$arguments[] = $ack;
}
if (null !== $handlerArgumentsStamp) {
$arguments = [...$arguments, ...$handlerArgumentsStamp->getAdditionalArguments()];
}

if ($this->decorator) {
$handler = $this->decorator->decorate($handler(...));
}

return $handler(...$arguments);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Tests\Integration\App\DecorateController\Controller;

use Symfony\Component\Routing\Attribute\Route;
use Yceruto\DecoratorBundle\Tests\Integration\Fixtures\Decorator\SecuredSerialize;
use Yceruto\DecoratorBundle\Tests\Integration\Fixtures\Decorator\HttpSecuredApi;

#[Route('/compound-decorators/default-options')]
class ControllerWithCompoundDecorator
{
#[SecuredSerialize]
#[HttpSecuredApi]
public function __invoke(): array
{
return ['success' => true];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Tests\Integration\App\DecorateController\Controller;

use Symfony\Component\Routing\Attribute\Route;
use Yceruto\DecoratorBundle\Decorator\Serializer\Serialize;
use Yceruto\DecoratorBundle\Tests\Integration\Fixtures\Decorator\Secured;
use Yceruto\DecoratorBundle\Tests\Integration\Fixtures\Decorator\HttpSecured;

#[Route('/security-serialize-decorators/default-options')]
class ControllerWithSecurityAndSerializeDecorator
{
#[Secured]
#[HttpSecured]
#[Serialize]
public function __invoke(): array
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Tests\Integration\App\DecorateController\Controller;

use Symfony\Component\Routing\Attribute\Route;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Tests\Integration\App\DecorateController\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Yceruto\DecoratorBundle\Decorator\Serializer\Serialize;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Tests\Integration\App\DecorateController\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
<?php

declare(strict_types=1);

/*
* This file is part of Decorator Bundle package.
*
* (c) Yonel Ceruto <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Yceruto\DecoratorBundle\Tests\Integration\App\DecorateController\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Yceruto\DecoratorBundle\Decorator\Serializer\Serialize;

Expand Down
Loading
Loading