13
13
14
14
namespace Sylius \Resource \Symfony \Validator \EventListener ;
15
15
16
+ use Psr \Container \ContainerInterface ;
16
17
use Sylius \Resource \Symfony \Validator \Exception \ConstraintViolationListAwareExceptionInterface ;
17
18
use Symfony \Component \HttpFoundation \Response ;
18
19
use Symfony \Component \HttpKernel \Event \ExceptionEvent ;
19
20
use Symfony \Component \Serializer \SerializerInterface ;
21
+ use Symfony \Contracts \Service \ServiceSubscriberInterface ;
20
22
21
23
/**
22
24
* Handles validation errors.
23
25
*
24
26
* @experimental
25
27
*/
26
- final class ValidationExceptionListener
28
+ final class ValidationExceptionListener implements ServiceSubscriberInterface
27
29
{
28
- public function __construct (private ? SerializerInterface $ serializer = null )
30
+ public function __construct (private ContainerInterface $ container )
29
31
{
30
32
}
31
33
@@ -40,7 +42,9 @@ public function onKernelException(ExceptionEvent $event): void
40
42
return ;
41
43
}
42
44
43
- if (null === $ this ->serializer ) {
45
+ /** @var SerializerInterface|null $serializer */
46
+ $ serializer = $ this ->container ->get ('serializer ' );
47
+ if (null === $ serializer ) {
44
48
throw new \LogicException ('The Symfony Serializer is not available. Try running "composer require symfony/serializer". ' );
45
49
}
46
50
@@ -53,7 +57,7 @@ public function onKernelException(ExceptionEvent $event): void
53
57
$ mimeType = $ request ->getMimeType ($ format );
54
58
55
59
$ event ->setResponse (new Response (
56
- $ this -> serializer ->serialize ($ exception ->getConstraintViolationList (), $ format ),
60
+ $ serializer ->serialize ($ exception ->getConstraintViolationList (), $ format ),
57
61
Response::HTTP_UNPROCESSABLE_ENTITY ,
58
62
[
59
63
'Content-Type ' => sprintf ('%s; charset=utf-8 ' , $ mimeType ),
@@ -62,4 +66,11 @@ public function onKernelException(ExceptionEvent $event): void
62
66
],
63
67
));
64
68
}
69
+
70
+ public static function getSubscribedServices (): array
71
+ {
72
+ return [
73
+ 'serializer ' => '? ' . SerializerInterface::class,
74
+ ];
75
+ }
65
76
}
0 commit comments