|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <dunglas@gmail.com> |
| 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 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace ApiPlatform\Laravel\State; |
| 15 | + |
| 16 | +use ApiPlatform\Laravel\ApiResource\ValidationError; |
| 17 | +use ApiPlatform\Metadata\Operation; |
| 18 | +use ApiPlatform\State\DenormalizationViolationFactoryInterface; |
| 19 | +use Illuminate\Contracts\Validation\Rule as LaravelRule; |
| 20 | +use Illuminate\Contracts\Validation\ValidationRule; |
| 21 | +use Illuminate\Foundation\Http\FormRequest; |
| 22 | +use Symfony\Component\Serializer\Exception\NotNormalizableValueException; |
| 23 | +use Symfony\Component\Serializer\Exception\PartialDenormalizationException; |
| 24 | + |
| 25 | +/** |
| 26 | + * Laravel-flavored denormalization violation factory — translates Symfony serializer |
| 27 | + * type errors into a 422 {@see ValidationError} when the Operation's Laravel rules |
| 28 | + * describe the property. |
| 29 | + * |
| 30 | + * Reads rules declared on the operation (string|array form, e.g. `'required|string'` |
| 31 | + * or `['required', 'string']`). FormRequest-class rules and pure-callable rule sets |
| 32 | + * are intentionally skipped in v1: a FormRequest-based contract typically runs in the |
| 33 | + * validation phase against the raw request, not the denormalized body. |
| 34 | + * |
| 35 | + * Mapping: |
| 36 | + * |
| 37 | + * | Exception "current type" | Matching Laravel rule | Emitted code | |
| 38 | + * |--------------------------|---------------------------------------------|----------------| |
| 39 | + * | null | required, filled | blank | |
| 40 | + * | null | present | null | |
| 41 | + * | any wrong type | string, integer, int, numeric, boolean, | invalid_type | |
| 42 | + * | | bool, array, date, json | | |
| 43 | + * | any wrong type | any other rule (no `nullable`) | invalid_type | |
| 44 | + * | null | nullable (no required/present/filled) | (no match) | |
| 45 | + * | any | (no rule) | (no match) | |
| 46 | + * |
| 47 | + * In collect mode, unconstrained errors still emit a generic `invalid_type` entry so |
| 48 | + * the response surface stays consistent with prior behavior. |
| 49 | + * |
| 50 | + * Codes are plain semantic strings — the Laravel package does not depend on Symfony |
| 51 | + * Validator. |
| 52 | + * |
| 53 | + * @author Antoine Bluchet <soyuka@gmail.com> |
| 54 | + */ |
| 55 | +final class DenormalizationViolationFactory implements DenormalizationViolationFactoryInterface |
| 56 | +{ |
| 57 | + public const CODE_BLANK = 'blank'; |
| 58 | + public const CODE_NULL = 'null'; |
| 59 | + public const CODE_INVALID_TYPE = 'invalid_type'; |
| 60 | + |
| 61 | + private const REQUIRED_RULES = ['required' => true, 'filled' => true]; |
| 62 | + private const PRESENT_RULES = ['present' => true]; |
| 63 | + |
| 64 | + public function handle(NotNormalizableValueException|PartialDenormalizationException $exception, Operation $operation): void |
| 65 | + { |
| 66 | + if ($exception instanceof NotNormalizableValueException) { |
| 67 | + $violation = $this->buildViolation($exception, $operation); |
| 68 | + if (null === $violation) { |
| 69 | + return; |
| 70 | + } |
| 71 | + |
| 72 | + throw new ValidationError($violation['message'], $this->makeId([$violation['propertyPath']]), $exception, [$violation]); |
| 73 | + } |
| 74 | + |
| 75 | + $violations = []; |
| 76 | + $errors = method_exists($exception, 'getNotNormalizableValueErrors') ? $exception->getNotNormalizableValueErrors() : $exception->getErrors(); |
| 77 | + foreach ($errors as $error) { |
| 78 | + if (!$error instanceof NotNormalizableValueException) { |
| 79 | + continue; |
| 80 | + } |
| 81 | + $violations[] = $this->buildViolation($error, $operation) ?? $this->buildGenericViolation($error); |
| 82 | + } |
| 83 | + |
| 84 | + if (!$violations) { |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + $paths = array_filter(array_map(static fn (array $v): string => $v['propertyPath'], $violations)); |
| 89 | + $message = implode('; ', array_map(static fn (array $v): string => $v['propertyPath'].': '.$v['message'], $violations)); |
| 90 | + |
| 91 | + throw new ValidationError($message, $this->makeId($paths), $exception, $violations); |
| 92 | + } |
| 93 | + |
| 94 | + /** |
| 95 | + * @return array{propertyPath: string, message: string, code: string}|null |
| 96 | + */ |
| 97 | + private function buildViolation(NotNormalizableValueException $exception, Operation $operation): ?array |
| 98 | + { |
| 99 | + $rules = $operation->getRules(); |
| 100 | + if (\is_callable($rules)) { |
| 101 | + $rules = $rules(); |
| 102 | + } |
| 103 | + |
| 104 | + if (\is_string($rules) && is_a($rules, FormRequest::class, true)) { |
| 105 | + return null; |
| 106 | + } |
| 107 | + |
| 108 | + if (!\is_array($rules)) { |
| 109 | + return null; |
| 110 | + } |
| 111 | + |
| 112 | + $path = $exception->getPath(); |
| 113 | + if (null === $path || '' === $path || !\array_key_exists($path, $rules)) { |
| 114 | + return null; |
| 115 | + } |
| 116 | + |
| 117 | + $propertyRules = $this->extractRuleTokens($rules[$path]); |
| 118 | + if (!$propertyRules) { |
| 119 | + return null; |
| 120 | + } |
| 121 | + |
| 122 | + $isNull = 'null' === strtolower((string) $exception->getCurrentType()); |
| 123 | + |
| 124 | + if ($isNull) { |
| 125 | + $hasRequired = (bool) array_intersect_key(self::REQUIRED_RULES, $propertyRules); |
| 126 | + $hasPresent = (bool) array_intersect_key(self::PRESENT_RULES, $propertyRules); |
| 127 | + |
| 128 | + // `nullable` explicitly permits null when no required/present/filled is set. |
| 129 | + if (isset($propertyRules['nullable']) && !$hasRequired && !$hasPresent) { |
| 130 | + return null; |
| 131 | + } |
| 132 | + |
| 133 | + if ($hasRequired) { |
| 134 | + return $this->violation($path, 'This value should not be blank.', self::CODE_BLANK); |
| 135 | + } |
| 136 | + if ($hasPresent) { |
| 137 | + return $this->violation($path, 'This value should not be null.', self::CODE_NULL); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + return $this->violation($path, $this->typeMessage($exception), self::CODE_INVALID_TYPE); |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * @return array<string, true> rule tokens as a keyed map for O(1) lookup |
| 146 | + */ |
| 147 | + private function extractRuleTokens(mixed $raw): array |
| 148 | + { |
| 149 | + if (\is_string($raw)) { |
| 150 | + $items = explode('|', $raw); |
| 151 | + } elseif (\is_array($raw)) { |
| 152 | + $items = $raw; |
| 153 | + } else { |
| 154 | + return []; |
| 155 | + } |
| 156 | + |
| 157 | + $tokens = []; |
| 158 | + foreach ($items as $item) { |
| 159 | + if ($item instanceof LaravelRule || $item instanceof ValidationRule || \is_object($item)) { |
| 160 | + continue; |
| 161 | + } |
| 162 | + if (!\is_string($item)) { |
| 163 | + continue; |
| 164 | + } |
| 165 | + $name = strtolower(strstr($item, ':', true) ?: $item); |
| 166 | + if ('' === $name) { |
| 167 | + continue; |
| 168 | + } |
| 169 | + $tokens[$name] = true; |
| 170 | + } |
| 171 | + |
| 172 | + return $tokens; |
| 173 | + } |
| 174 | + |
| 175 | + /** |
| 176 | + * @return array{propertyPath: string, message: string, code: string} |
| 177 | + */ |
| 178 | + private function violation(string $path, string $message, string $code): array |
| 179 | + { |
| 180 | + return [ |
| 181 | + 'propertyPath' => $path, |
| 182 | + 'message' => $message, |
| 183 | + 'code' => $code, |
| 184 | + ]; |
| 185 | + } |
| 186 | + |
| 187 | + /** |
| 188 | + * @return array{propertyPath: string, message: string, code: string} |
| 189 | + */ |
| 190 | + private function buildGenericViolation(NotNormalizableValueException $exception): array |
| 191 | + { |
| 192 | + return $this->violation( |
| 193 | + (string) $exception->getPath(), |
| 194 | + $exception->canUseMessageForUser() ? $exception->getMessage() : $this->typeMessage($exception), |
| 195 | + self::CODE_INVALID_TYPE, |
| 196 | + ); |
| 197 | + } |
| 198 | + |
| 199 | + private function typeMessage(NotNormalizableValueException $exception): string |
| 200 | + { |
| 201 | + $expectedTypes = $exception->getExpectedTypes() ?? []; |
| 202 | + if (!$expectedTypes) { |
| 203 | + return 'This value should be of the right type.'; |
| 204 | + } |
| 205 | + |
| 206 | + return \sprintf('This value should be of type %s.', implode('|', $expectedTypes)); |
| 207 | + } |
| 208 | + |
| 209 | + /** |
| 210 | + * @param string[] $paths |
| 211 | + */ |
| 212 | + private function makeId(array $paths): string |
| 213 | + { |
| 214 | + return hash('xxh3', implode(',', $paths) ?: 'denormalization'); |
| 215 | + } |
| 216 | +} |
0 commit comments