Skip to content

Commit 9d5372a

Browse files
committed
[Components][Serializer] optional constructor arguments can be omitted during the denormalization process
1 parent 3bbc004 commit 9d5372a

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

Normalizer/GetSetMethodNormalizer.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,9 @@ public function denormalize($data, $class, $format = null, array $context = arra
128128
$params[] = $data[$paramName];
129129
// don't run set for a parameter passed to the constructor
130130
unset($data[$paramName]);
131-
} elseif (!$constructorParameter->isOptional()) {
131+
} elseif ($constructorParameter->isOptional()) {
132+
$params[] = $constructorParameter->getDefaultValue();
133+
} else {
132134
throw new RuntimeException(
133135
'Cannot create an instance of '.$class.
134136
' from serialized data because its constructor requires '.

Tests/Normalizer/GetSetMethodNormalizerTest.php

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,16 @@ public function testConstructorDenormalize()
8686
$this->assertEquals('bar', $obj->getBar());
8787
}
8888

89+
public function testConstructorDenormalizeWithMissingOptionalArgument()
90+
{
91+
$obj = $this->normalizer->denormalize(
92+
array('foo' => 'test', 'baz' => array(1, 2, 3)),
93+
__NAMESPACE__.'\GetConstructorOptionalArgsDummy', 'any');
94+
$this->assertEquals('test', $obj->getFoo());
95+
$this->assertEquals(array(), $obj->getBar());
96+
$this->assertEquals(array(1, 2, 3), $obj->getBaz());
97+
}
98+
8999
/**
90100
* @dataProvider provideCallbacks
91101
*/
@@ -263,3 +273,37 @@ public function otherMethod()
263273
throw new \RuntimeException("Dummy::otherMethod() should not be called");
264274
}
265275
}
276+
277+
class GetConstructorOptionalArgsDummy
278+
{
279+
protected $foo;
280+
private $bar;
281+
private $baz;
282+
283+
public function __construct($foo, $bar = array(), $baz = array())
284+
{
285+
$this->foo = $foo;
286+
$this->bar = $bar;
287+
$this->baz = $baz;
288+
}
289+
290+
public function getFoo()
291+
{
292+
return $this->foo;
293+
}
294+
295+
public function getBar()
296+
{
297+
return $this->bar;
298+
}
299+
300+
public function getBaz()
301+
{
302+
return $this->baz;
303+
}
304+
305+
public function otherMethod()
306+
{
307+
throw new \RuntimeException("Dummy::otherMethod() should not be called");
308+
}
309+
}

0 commit comments

Comments
 (0)