1717use GraphQL \Error \Error ;
1818use GraphQL \Error \FormattedError ;
1919use Symfony \Component \HttpFoundation \Response ;
20+ use Symfony \Component \Serializer \NameConverter \NameConverterInterface ;
2021use Symfony \Component \Serializer \Normalizer \NormalizerInterface ;
2122use Symfony \Component \Validator \ConstraintViolation ;
2223
3031 */
3132final class ValidationExceptionNormalizer implements NormalizerInterface
3233{
34+ private $ nameConverter ;
35+
36+ public function __construct (NameConverterInterface $ nameConverter = null )
37+ {
38+ $ this ->nameConverter = $ nameConverter ;
39+ }
40+
3341 /**
3442 * {@inheritdoc}
3543 */
@@ -38,7 +46,7 @@ public function normalize($object, $format = null, array $context = []): array
3846 /** @var ValidationException */
3947 $ validationException = $ object ->getPrevious ();
4048 $ error = FormattedError::createFromException ($ object );
41- $ error ['message ' ] = $ validationException -> getMessage ( );
49+ $ error ['message ' ] = $ this -> normalizeValidationException ( $ validationException );
4250 $ error ['extensions ' ]['status ' ] = Response::HTTP_BAD_REQUEST ;
4351 $ error ['extensions ' ]['category ' ] = 'user ' ;
4452 $ error ['extensions ' ]['violations ' ] = [];
@@ -61,4 +69,24 @@ public function supportsNormalization($data, $format = null): bool
6169 {
6270 return $ data instanceof Error && $ data ->getPrevious () instanceof ValidationException;
6371 }
72+
73+ private function normalizeValidationException (ValidationException $ exception ): string
74+ {
75+ $ message = '' ;
76+ foreach ($ exception ->getConstraintViolationList () as $ violation ) {
77+ if ('' !== $ message ) {
78+ $ message .= "\n" ;
79+ }
80+
81+ $ class = \is_object ($ root = $ violation ->getRoot ()) ? \get_class ($ root ) : null ;
82+ $ propertyPath = $ this ->nameConverter ? $ this ->nameConverter ->normalize ($ violation ->getPropertyPath (), $ class ) : $ violation ->getPropertyPath ();
83+ if ($ propertyPath ) {
84+ $ message .= "$ propertyPath: " ;
85+ }
86+
87+ $ message .= $ violation ->getMessage ();
88+ }
89+
90+ return $ message ;
91+ }
6492}
0 commit comments