Skip to content

Commit 959ac2a

Browse files
committed
[Serializer] AbstractObjectNormalizer: Allow to disable type enforcement
1 parent ddc4b20 commit 959ac2a

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

src/Symfony/Component/Serializer/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
CHANGELOG
22
=========
33

4+
3.4.0
5+
-----
6+
7+
* added `AbstractObjectNormalizer::DISABLE_TYPE_ENFORCEMENT` context option
8+
to disable throwing an `UnexpectedValueException` on a type mismatch
9+
410
3.3.0
511
-----
612

src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
3333
const ENABLE_MAX_DEPTH = 'enable_max_depth';
3434
const DEPTH_KEY_PATTERN = 'depth_%s::%s';
3535
const ALLOW_EXTRA_ATTRIBUTES = 'allow_extra_attributes';
36+
const DISABLE_TYPE_ENFORCEMENT = 'disable_type_enforcement';
3637

3738
private $propertyTypeExtractor;
3839
private $attributesCache = array();
@@ -289,6 +290,10 @@ private function validateAndDenormalize($currentClass, $attribute, $data, $forma
289290
}
290291
}
291292

293+
if (isset($context[self::DISABLE_TYPE_ENFORCEMENT]) && $context[self::DISABLE_TYPE_ENFORCEMENT]) {
294+
return $data;
295+
}
296+
292297
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)));
293298
}
294299

src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,16 @@ public function testRejectInvalidKey()
628628
$serializer->denormalize(array('inners' => array('a' => array('foo' => 1))), ObjectOuter::class);
629629
}
630630

631+
public function testDoNotRejectInvalidTypeOnDisableTypeEnforcementContextOption()
632+
{
633+
$extractor = new PropertyInfoExtractor(array(), array(new PhpDocExtractor()));
634+
$normalizer = new ObjectNormalizer(null, null, null, $extractor);
635+
$serializer = new Serializer(array($normalizer));
636+
$context = array(ObjectNormalizer::DISABLE_TYPE_ENFORCEMENT => true);
637+
638+
$this->assertSame('foo', $serializer->denormalize(array('number' => 'foo'), JsonNumber::class, null, $context)->number);
639+
}
640+
631641
public function testExtractAttributesRespectsFormat()
632642
{
633643
$normalizer = new FormatAndContextAwareNormalizer();

0 commit comments

Comments
 (0)