8000 [Messenger] Added a middleware that validates messages by Nyholm · Pull Request #26648 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Messenger] Added a middleware that validates messages #26648

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

Merged
merged 1 commit into from
Apr 3, 2018
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
8000
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1005,10 +1005,14 @@ function ($a) {
->arrayNode('middlewares')
->addDefaultsIfNotSet()
->children()
->arrayNode('doctrine_transaction')
->canBeEnabled()
->children()
->scalarNode('entity_manager_name')->info('The name of the entity manager to use')->defaultNull()->end()
->arrayNode('doctrine_transaction')
->canBeEnabled()
->children()
->scalarNode('entity_manager_name')->info('The name of the entity manager to use')->defaultNull()->end()
->end()
->end()
->arrayNode('validation')
->{!class_exists(FullStack::class) && class_exists(Validation::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1459,6 +1459,14 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder
} else {
$container->removeDefinition('messenger.middleware.doctrine_transaction');
}

if ($config['middlewares']['validation']['enabled']) {
if (!$container->has('validator')) {
throw new LogicException('The Validation middleware is only available when the Validator component is installed and enabled. Try running "composer require symfony/validator".');
}
} else {
$container->removeDefinition('messenger.middleware.validator');
}
}

private function registerCacheConfiguration(array $config, ContainerBuilder $container)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@
<tag name="message_bus_middleware" priority="-10" />
</service>

<service id="messenger.middleware.validator" class="Symfony\Component\Messenger\Middleware\ValidationMiddleware">
<argument type="service" id="validator" />

<tag name="message_bus_middleware" priority="100" />
</service>

<service id="messenger.middleware.doctrine_transaction" class="Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware">
<argument type="service" id="doctrine" />
<argument /> <!-- Entity manager name -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,16 @@
<xsd:complexType name="messenger_middleware">
<xsd:sequence>
<xsd:element name="doctrine-transaction" type="messenger_doctrine_transaction" minOccurs="0" maxOccurs="1" />
<xsd:element name="validation" type="messenger_validation" minOccurs="0" maxOccurs="1" />
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="messenger_doctrine_transaction">
<xsd:attribute name="entity-manager-name" type="xsd:string" />
<xsd:attribute name="enabled" type="xsd:boolean" />
</xsd:complexType>

<xsd:complexType name="messenger_validation">
<xsd:attribute name="enabled" type="xsd:boolean" />
</xsd:complexType>
</xsd:schema>
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,9 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor
'enabled' => false,
'entity_manager_name' => null,
),
'validation' => array(
'enabled' => false,
),
),
),
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

$container->loadFromExtension('framework', array(
'messenger' => array(
'middlewares' => array(
'validation' => array(
'enabled' => false,
),
),
),
));
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/d 6293 ic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="http://symfony.com/schema/dic/symfony"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
http://symfony.com/schema/dic/symfony http://symfony.com/schema/dic/symfony/symfony-1.0.xsd">

<framework:config>
<framework:messenger>
<framework:middlewares>
<framework:validation enabled="false"/>
</framework:middlewares>
</framework:messenger>
</framework:config>
</container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
framework:
messenger:
middlewares:
validation:
enabled: false
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
use Symfony\Component\Serializer\Normalizer\JsonSerializableNormalizer;
use Symfony\Component\Translation\DependencyInjection\TranslatorPass;
use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass;
use Symfony\Component\Validator\Validation;
use Symfony\Component\Workflow;

abstract class FrameworkExtensionTest extends TestCase
Expand Down Expand Up @@ -532,6 +533,16 @@ public function testMessengerDoctrine()
$this->assertEquals('foobar', $def->getArgument(1));
}

public function testMessengerValidationDisabled()
{
if (!class_exists(Validation::class)) {
self::markTestSkipped('Skipping tests since Validator component is not installed');
}

$container = $this->createContainerFromFile('messenger_validation');
$this->assertFalse($container->hasDefinition('messenger.middleware.validator'));
}

public function testTranslator()
{
$container = $this->createContainerFromFile('full');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Messenger\Exception;

use Symfony\Component\Validator\ConstraintViolationListInterface;

/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ValidationFailedException extends \RuntimeException implements ExceptionInterface
{
private $violations;
private $violatingMessage;

/**
* @param object $violatingMessage
*/
public function __construct($violatingMessage, ConstraintViolationListInterface $violations)
{
$this->violatingMessage = $violatingMessage;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it really needed? I'm used to handle one command at a time so I always have the message at hand, am I missing a use case? The existing NoHandlerForMessageException doesn't expose it

Copy link
Contributor
@ogizanagi ogizanagi Mar 29, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difference is that the NoHandlerForMessageException is a logic exception (or at least, should be to me), it is meant to fail badly. No need to access the exception programmatically and retrieve the issuing message.

ValidationFailedException is a runtime exception, meant to be caught and handled/transformed to a better representation (e.g: an API problem response). It can also be used in a profiler panel or whatever :)

Anyway, even if we often handle one message at the time, use-cases with multiple messages do exist. We should cover them. 👍

$this->violations = $violations;

parent::__construct(sprintf('Message of type "%s" failed validation.', get_class($this->violatingMessage)));
}

public function getViolatingMessage()
{
return $this->violatingMessage;
}

public function getViolations(): ConstraintViolationListInterface
{
return $this->violations;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Messenger\Middleware;

use Symfony\Component\Messenger\Exception\ValidationFailedException;
use Symfony\Component\Messenger\MiddlewareInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ValidationMiddleware implements MiddlewareInterface
{
private $validator;

public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}

public function handle($message, callable $next)
{
$violations = $this->validator->validate($message);
if (count($violations)) {
throw new ValidationFailedException($message, $violations);
}

return $next($message);
}
}
0