Debian Codegraph @

lib/3rdParty/composer/symfony/serializer/Normalizer/BackedEnumNormalizer.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[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 Symfony\Component\Serializer\Normalizer;
13
14 use Symfony\Component\Serializer\Exception\InvalidArgumentException;
15 use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
16
17 /**
18 * Normalizes a {@see \BackedEnum} enumeration to a string or an integer.
19 *
20 * @author Alexandre Daubois <[email protected]>
21 */
22 final class BackedEnumNormalizer implements NormalizerInterface, DenormalizerInterface
23 {
24 /**
25 * If true, will denormalize any invalid value into null.
26 */
27 public const ALLOW_INVALID_VALUES = 'allow_invalid_values';
28
29 public function getSupportedTypes(?string $format): array
30 {
31 return [
32 \BackedEnum::class => true,
33 ];
34 }
35
36 public function normalize(mixed $data, ?string $format = null, array $context = []): int|string
37 {
38 if (!$data instanceof \BackedEnum) {
39 throw new InvalidArgumentException('The data must belong to a backed enumeration.');
40 }
41
42 return $data->value;
43 }
44
45 public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
46 {
47 return $data instanceof \BackedEnum;
48 }
49
50 /**
51 * @throws NotNormalizableValueException
52 */
53 public function denormalize(mixed $data, string $type, ?string $format = null, array $context = []): mixed
54 {
55 if (!is_subclass_of($type, \BackedEnum::class)) {
56 throw new InvalidArgumentException('The data must belong to a backed enumeration.');
57 }
58
59 $allowInvalidValues = $context[self::ALLOW_INVALID_VALUES] ?? false;
60
61 if (!\is_int($data) && !\is_string($data)) {
62 if ($allowInvalidValues) {
63 return null;
64 }
65
66 throw NotNormalizableValueException::createForUnexpectedDataType('The data is neither an integer nor a string, you should pass an integer or a string that can be parsed as an enumeration case of type '.$type.'.', $data, ['int', 'string'], $context['deserialization_path'] ?? null, true);
67 }
68
69 try {
70 return $type::from($data);
71 } catch (\ValueError|\TypeError $e) {
72 if ($allowInvalidValues) {
73 return null;
74 }
75
76 throw NotNormalizableValueException::createForUnexpectedDataType('The data must belong to a backed enumeration of type '.$type, $data, ['int', 'string'], $context['deserialization_path'] ?? null, true, 0, $e);
77 }
78 }
79
80 public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
81 {
82 return is_subclass_of($type, \BackedEnum::class);
83 }
84 }