Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -57,30 +57,28 @@ public function denormalize(mixed $data, string $type, ?string $format = null, a
throw new InvalidArgumentException('The data must belong to a backed enumeration.');
}

if ($context[self::ALLOW_INVALID_VALUES] ?? false) {
if (null === $data || (!\is_int($data) && !\is_string($data))) {
return null;
}
$allowInvalidValues = $context[self::ALLOW_INVALID_VALUES] ?? false;

try {
return $type::tryFrom($data);
} catch (\TypeError) {
if (null === $data || (!\is_int($data) && !\is_string($data))) {
if ($allowInvalidValues && !isset($context['not_normalizable_value_exceptions'])) {
return null;
}
}

if (!\is_int($data) && !\is_string($data)) {
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, [Type::BUILTIN_TYPE_INT, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true);
}

try {
return $type::from($data);
} catch (\ValueError $e) {
} catch (\ValueError|\TypeError $e) {
if (isset($context['has_constructor'])) {
throw new InvalidArgumentException('The data must belong to a backed enumeration of type '.$type, 0, $e);
}

throw NotNormalizableValueException::createForUnexpectedDataType('The data must belong to a backed enumeration of type '.$type, $data, [$type], $context['deserialization_path'] ?? null, true, 0, $e);
if ($allowInvalidValues && !isset($context['not_normalizable_value_exceptions'])) {
return null;
}

throw NotNormalizableValueException::createForUnexpectedDataType('The data must belong to a backed enumeration of type '.$type, $data, [Type::BUILTIN_TYPE_INT, Type::BUILTIN_TYPE_STRING], $context['deserialization_path'] ?? null, true, 0, $e);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,30 @@ public function testItUsesTryFromIfContextIsPassed()

$this->assertSame(StringBackedEnumDummy::GET, $this->normalizer->denormalize('GET', StringBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));
}

public function testDenormalizeNullWithAllowInvalidAndCollectErrorsThrows()
{
$this->expectException(NotNormalizableValueException::class);
$this->expectExceptionMessage('The data is neither an integer nor a string');

$context = [
BackedEnumNormalizer::ALLOW_INVALID_VALUES => true,
'not_normalizable_value_exceptions' => [], // Indicate that we want to collect errors
];

$this->normalizer->denormalize(null, StringBackedEnumDummy::class, null, $context);
}

public function testDenormalizeInvalidValueWithAllowInvalidAndCollectErrorsThrows()
{
$this->expectException(NotNormalizableValueException::class);
$this->expectExceptionMessage('The data must belong to a backed enumeration of type');

$context = [
BackedEnumNormalizer::ALLOW_INVALID_VALUES => true,
'not_normalizable_value_exceptions' => [],
];

$this->normalizer->denormalize('invalid-value', StringBackedEnumDummy::class, null, $context);
}
}
48 changes: 48 additions & 0 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor;
use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\PropertyInfo\Extractor\SerializerExtractor;
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
Expand Down Expand Up @@ -1794,6 +1795,38 @@ public function testDeserializeObjectWithAsymmetricPropertyVisibility()
$this->assertSame('one', $object->item);
$this->assertSame('final', $object->type); // Value set in the constructor; must not be changed during deserialization
}

public function testPartialDenormalizationWithInvalidEnumAndAllowInvalid()
{
$factory = new ClassMetadataFactory(new AttributeLoader());
$extractor = new PropertyInfoExtractor(
[new SerializerExtractor($factory)],
[new ReflectionExtractor()]
);
$serializer = new Serializer(
[
new ArrayDenormalizer(),
new BackedEnumNormalizer(),
new ObjectNormalizer($factory, null, null, $extractor),
],
);

$context = [
'collect_denormalization_errors' => true,
'allow_invalid_values' => true,
];

try {
$serializer->denormalize(['id' => 123, 'status' => null], SerializerTestRequestDto::class, null, $context);
$this->fail('PartialDenormalizationException was not thrown.');
} catch (PartialDenormalizationException $exception) {
$this->assertCount(1, $exception->getErrors());
$error = $exception->getErrors()[0];

$this->assertSame('status', $error->getPath());
$this->assertSame(['int', 'string'], $error->getExpectedTypes());
}
}
}

class Model
Expand Down Expand Up @@ -1969,3 +2002,18 @@ interface NormalizerAwareNormalizer extends NormalizerInterface, NormalizerAware
interface DenormalizerAwareDenormalizer extends DenormalizerInterface, DenormalizerAwareInterface
{
}

enum SerializerTestBackedEnum: string
{
case PENDING = 'pending';
case ACTIVE = 'active';
}

class SerializerTestRequestDto
{
public function __construct(
public int $id,
public SerializerTestBackedEnum $status,
) {
}
}