Skip to content

Commit 6535548

Browse files
Merge pull request #30 from KNonen/master
fix bug: "Argument of type NULL should have been an array" when argument is optional
2 parents e150ef5 + 76e6c1e commit 6535548

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

ArgumentValidator.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ public function __construct(
3131
public function validate(\ReflectionParameter $parameter, $argument)
3232
{
3333
if ($parameter->isArray()) {
34+
if ($parameter->allowsNull() && is_null($argument)) {
35+
return;
36+
}
3437
$this->validateArrayArgument($argument);
3538
} elseif ($parameter->getClass()) {
3639
$this->validateObjectArgument($parameter->getClass()->getName(), $argument, $parameter->allowsNull());

Tests/ArgumentValidatorTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,22 @@ public function testFailsWhenParameterHasArrayTypeHintButArgumentIsNotArray()
8484
$validator->validate($parameter, $argument);
8585
}
8686

87+
public function testFailsWhenOptionalParameterHasArrayTypeHintAndResultOfExpressionIsNullButNullIsNotAllowed()
88+
{
89+
$class = 'Matthias\SymfonyServiceDefinitionValidator\Tests\Fixtures\ClassWithOptionalArrayConstructorArgument';
90+
91+
$parameter = new \ReflectionParameter(array($class, '__construct'), 'options');
92+
$argument = null;
93+
94+
$validator = new ArgumentValidator(new ContainerBuilder(), $this->createMockResultingClassResolver());
95+
96+
try {
97+
$validator->validate($parameter, $argument);
98+
} catch (TypeHintMismatchException $exception) {
99+
$this->fail('null argument should be allowed');
100+
}
101+
}
102+
87103
public function testFailsWhenResultOfExpressionIsNotAnObjectOfTheExpectedClass()
88104
{
89105
$this->skipTestIfExpressionsAreNotAvailable();
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
namespace Matthias\SymfonyServiceDefinitionValidator\Tests\Fixtures;
4+
5+
class ClassWithOptionalArrayConstructorArgument
6+
{
7+
public function __construct(array $options = null)
8+
{
9+
}
10+
}

0 commit comments

Comments
 (0)