Skip to content

Commit a5c2a5e

Browse files
committed
Add new feature to serializer: empty_data
You can now add empty_data to the context on deserialization of objects. This allow you to deserialize objects that have requirements in the constructor that can't be given. Basically, it helps you hydrate with value objects, so the validation component can invalid the object without the serializer send an error.
1 parent 1d73bbc commit a5c2a5e

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

src/Symfony/Component/Serializer/CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ CHANGELOG
66

77
* added `IncompleteInputDataException` new exception for deserialization failure
88
of objects that needs data insertion in constructor
9+
* added an optional `empty_data` option of context to specify a default data in
10+
case the object is not initializable by its constructor because of data missing
911

1012
4.0.0
1113
-----

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
3737
const GROUPS = 'groups';
3838
const ATTRIBUTES = 'attributes';
3939
const ALLOW_EXTRA_ATTRIBUTES = 'allow_extra_attributes';
40+
const EMPTY_DATA = 'empty_data';
4041

4142
/**
4243
* @var int
@@ -355,6 +356,8 @@ protected function instantiateObject(array &$data, $class, array &$context, \Ref
355356
// Don't run set for a parameter passed to the constructor
356357
$params[] = $parameterData;
357358
unset($data[$key]);
359+
} elseif ($allowed && !$ignored && isset($context[static::EMPTY_DATA][$class][$key])) {
360+
$params[] = $context[static::EMPTY_DATA][$class][$key];
358361
} elseif ($constructorParameter->isDefaultValueAvailable()) {
359362
$params[] = $constructorParameter->getDefaultValue();
360363
} else {

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,23 @@ public function testConstructorWithMissingData()
218218
$normalizer->denormalize($data, DummyValueObject::class);
219219
}
220220

221+
public function testFillWithEmptyDataWhenMissingData()
222+
{
223+
$data = array(
224+
'foo' => 10,
225+
);
226+
227+
$normalizer = new ObjectNormalizer();
228+
229+
$result = $normalizer->denormalize($data, DummyValueObject::class, 'json', array(
230+
'empty_data' => array(
231+
DummyValueObject::class => ['foo' => '', 'bar' => ''],
232+
),
233+
));
234+
235+
$this->assertEquals(new DummyValueObject(10, ''), $result);
236+
}
237+
221238
public function testGroupsNormalize()
222239
{
223240
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));

0 commit comments

Comments
 (0)