Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Serializer] add a context to allow invalid values in BackedEnumNormalizer #48821

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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
[Serializer] add a context to allow invalid values in BackedEnumNorma…
…lizer
  • Loading branch information
nikophil committed Mar 3, 2023
commit 526e0b210a072f083326b805be731f7843ebc010
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add `XmlEncoder::SAVE_OPTIONS` context option
* Add `BackedEnumNormalizer::ALLOW_INVALID_VALUES` context option
* Deprecate `MissingConstructorArgumentsException` in favor of `MissingConstructorArgumentException`

6.2
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Context\Normalizer;

use Symfony\Component\Serializer\Context\ContextBuilderInterface;
use Symfony\Component\Serializer\Context\ContextBuilderTrait;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;

/**
* A helper providing autocompletion for available BackedEnumNormalizer options.
*
* @author Nicolas PHILIPPE <nikophil@gmail.com>
*/
final class BackedEnumNormalizerContextBuilder implements ContextBuilderInterface
{
use ContextBuilderTrait;

/**
* Configures if invalid values are allowed in denormalization.
* They will be denormalized into `null` values.
*/
public function withAllowInvalidValues(bool $allowInvalidValues): static
{
return $this->with(BackedEnumNormalizer::ALLOW_INVALID_VALUES, $allowInvalidValues);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
*/
final class BackedEnumNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
/**
* If true, will denormalize any invalid value into null.
*/
public const ALLOW_INVALID_VALUES = 'allow_invalid_values';

public function normalize(mixed $object, string $format = null, array $context = []): int|string
{
if (!$object instanceof \BackedEnum) {
Expand All @@ -45,6 +50,18 @@ public function denormalize(mixed $data, string $type, string $format = null, ar
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;
}

try {
return $type::tryFrom($data);
} catch (\TypeError) {
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
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);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Tests\Context\Normalizer;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Context\Normalizer\BackedEnumNormalizerContextBuilder;
use Symfony\Component\Serializer\Normalizer\BackedEnumNormalizer;

class BackedEnumNormalizerContextBuilderTest extends TestCase
{
private BackedEnumNormalizerContextBuilder $contextBuilder;

protected function setUp(): void
{
$this->contextBuilder = new BackedEnumNormalizerContextBuilder();
}

public function testWithers()
{
$context = $this->contextBuilder->withAllowInvalidValues(true)->toArray();
self::assertSame([BackedEnumNormalizer::ALLOW_INVALID_VALUES => true], $context);

$context = $this->contextBuilder->withAllowInvalidValues(false)->toArray();
self::assertSame([BackedEnumNormalizer::ALLOW_INVALID_VALUES => false], $context);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,19 @@ public function testSupportsNormalizationShouldFailOnAnyPHPVersionForNonEnumObje
{
$this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
}

public function testItUsesTryFromIfContextIsPassed()
{
$this->assertNull($this->normalizer->denormalize(1, IntegerBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));
$this->assertNull($this->normalizer->denormalize('', IntegerBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));
$this->assertNull($this->normalizer->denormalize(null, IntegerBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));

$this->assertSame(IntegerBackedEnumDummy::SUCCESS, $this->normalizer->denormalize(200, IntegerBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));

$this->assertNull($this->normalizer->denormalize(1, StringBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));
$this->assertNull($this->normalizer->denormalize('foo', StringBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));
$this->assertNull($this->normalizer->denormalize(null, StringBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));

$this->assertSame(StringBackedEnumDummy::GET, $this->normalizer->denormalize('GET', StringBackedEnumDummy::class, null, [BackedEnumNormalizer::ALLOW_INVALID_VALUES => true]));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.