[Serializer] AbstractObjectNormalizer: Allow to disable type enforcement

This commit is contained in:
Maxime Steinhausser 2017-07-05 11:12:59 +02:00
parent ddc4b20934
commit 959ac2a6b2
3 changed files with 21 additions and 0 deletions

View File

@ -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
-----

View File

@ -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();
@ -289,6 +290,10 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
}
}
if (isset($context[self::DISABLE_TYPE_ENFORCEMENT]) && $context[self::DISABLE_TYPE_ENFORCEMENT]) {
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)));
}

View File

@ -628,6 +628,16 @@ class ObjectNormalizerTest extends TestCase
$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();