ValidationMiddleware.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Messenger\Middleware;
  11. use Symfony\Component\Messenger\Envelope;
  12. use Symfony\Component\Messenger\Exception\ValidationFailedException;
  13. use Symfony\Component\Messenger\Stamp\ValidationStamp;
  14. use Symfony\Component\Validator\Validator\ValidatorInterface;
  15. /**
  16. * @author Tobias Nyholm <tobias.nyholm@gmail.com>
  17. */
  18. class ValidationMiddleware implements MiddlewareInterface
  19. {
  20. private $validator;
  21. public function __construct(ValidatorInterface $validator)
  22. {
  23. $this->validator = $validator;
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function handle(Envelope $envelope, StackInterface $stack): Envelope
  29. {
  30. $message = $envelope->getMessage();
  31. $groups = null;
  32. /** @var ValidationStamp|null $validationStamp */
  33. if ($validationStamp = $envelope->last(ValidationStamp::class)) {
  34. $groups = $validationStamp->getGroups();
  35. }
  36. $violations = $this->validator->validate($message, null, $groups);
  37. if (\count($violations)) {
  38. throw new ValidationFailedException($message, $violations);
  39. }
  40. return $stack->next()->handle($envelope, $stack);
  41. }
  42. }