Skip to content

[Serializer] AbstractObjectNormalizer: Allow to disable type enforcement #23404

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 1 commit into from
Jul 12, 2017
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
6 changes: 6 additions & 0 deletions src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
CHANGELOG
=========

3.4.0
-----

* added `AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT` context option
to disable throwing an `UnexpectedValueException` on a type mismatch

3.3.0
-----

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
const ENABLE_MAX_DEPTH = 'enable_max_depth';
const DEPTH_KEY_PATTERN = 'depth_%s::%s';
const ALLOW_EXTRA_ATTRIBUTES = 'allow_extra_attributes';
const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement';

private $propertyTypeExtractor;
private $attributesCache = array();
Expand Down Expand Up @@ -289,6 +290,10 @@ private function validateAndDenormalize($currentClass, $attribute, $data, $forma
}
}

if (isset($context[self::DISABLE_TYPE_ENFORCEMENT]) && $context[self::DISABLE_TYPE_ENFORCEMENT]) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

!empty(...)

return $data;
}

throw new UnexpectedValueException(sprintf('The type of the "%s" attribute for class "%s" must be one of "%s" ("%s" given).', $attribute, $currentClass, implode('", "', array_keys($expectedTypes)), gettype($data)));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,16 @@ public function testRejectInvalidKey()
$serializer->denormalize(array('inners' => array('a' => array('foo' => 1))), ObjectOuter::class);
}

public function testDoNotRejectInvalidTypeOnDisableTypeEnforcementContextOption()
{
$extractor = new PropertyInfoExtractor(array(), array(new PhpDocExtractor()));
$normalizer = new ObjectNormalizer(null, null, null, $extractor);
$serializer = new Serializer(array($normalizer));
$context = array(ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true);

$this->assertSame('foo', $serializer->denormalize(array('number' => 'foo'), JsonNumber::class, null, $context)->number);
}

public function testExtractAttributesRespectsFormat()
{
$normalizer = new FormatAndContextAwareNormalizer();
Expand Down