|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace ApiPlatform\Core\Problem\Serializer; |
| 13 | + |
| 14 | +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
| 15 | +use Symfony\Component\Validator\ConstraintViolationListInterface; |
| 16 | + |
| 17 | +/** |
| 18 | + * Converts {@see \Symfony\Component\Validator\ConstraintViolationListInterface} the API Problem spec (RFC 7807). |
| 19 | + * |
| 20 | + * @see https://tools.ietf.org/html/rfc7807 |
| 21 | +
|
| 22 | + * @author Kévin Dunglas <[email protected]> |
| 23 | + */ |
| 24 | +final class ConstraintViolationListNormalizer implements NormalizerInterface |
| 25 | +{ |
| 26 | + const FORMAT = 'jsonproblem'; |
| 27 | + |
| 28 | + /** |
| 29 | + * {@inheritdoc} |
| 30 | + */ |
| 31 | + public function normalize($object, $format = null, array $context = []) |
| 32 | + { |
| 33 | + $violations = []; |
| 34 | + $messages = []; |
| 35 | + |
| 36 | + foreach ($object as $violation) { |
| 37 | + $violations[] = [ |
| 38 | + 'propertyPath' => $violation->getPropertyPath(), |
| 39 | + 'message' => $violation->getMessage(), |
| 40 | + ]; |
| 41 | + |
| 42 | + $propertyPath = $violation->getPropertyPath(); |
| 43 | + $prefix = $propertyPath ? sprintf('%s: ', $propertyPath) : ''; |
| 44 | + |
| 45 | + $messages [] = $prefix.$violation->getMessage(); |
| 46 | + } |
| 47 | + |
| 48 | + return [ |
| 49 | + 'type' => $context['type'] ?? 'https://tools.ietf.org/html/rfc2616#section-10', |
| 50 | + 'title' => $context['title'] ?? 'An error occurred', |
| 51 | + 'detail' => $messages ? implode("\n", $messages) : (string) $object, |
| 52 | + 'violations' => $violations, |
| 53 | + ]; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * {@inheritdoc} |
| 58 | + */ |
| 59 | + public function supportsNormalization($data, $format = null) |
| 60 | + { |
| 61 | + return self::FORMAT === $format && $data instanceof ConstraintViolationListInterface; |
| 62 | + } |
| 63 | +} |
0 commit comments