Skip to content

Commit

Permalink
Fix crash on a union type including null
Browse files Browse the repository at this point in the history
This change prevents the generation of type hints with 2 "null".
For example, "string|array|null" should generate the code
"string|array|null" instead of "string|array|null|null" to avoid
a PHP fatal error "Duplicate type null is redundant".

Closes #1105.
  • Loading branch information
LeSuisse committed Dec 7, 2020
1 parent 60fa2f6 commit f3757c0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
8 changes: 5 additions & 3 deletions library/Mockery/Reflector.php
Expand Up @@ -192,9 +192,11 @@ private static function typeToString(\ReflectionType $type, \ReflectionClass $de
{
// PHP 8 union types can be recursively processed
if ($type instanceof \ReflectionUnionType) {
return \implode('|', \array_map(function (\ReflectionType $type) use ($declaringClass) {
return self::typeToString($type, $declaringClass);
}, $type->getTypes()));
return \implode('|', \array_filter(\array_map(function (\ReflectionType $type) use ($declaringClass) {
$typeHint = self::typeToString($type, $declaringClass);

return $typeHint === 'null' ? null : $typeHint;
}, $type->getTypes())));
}

// PHP 7.0 doesn't have named types, but 7.1+ does
Expand Down
16 changes: 16 additions & 0 deletions tests/PHP80/Php80LanguageFeaturesTest.php
Expand Up @@ -29,6 +29,15 @@ public function it_can_mock_a_class_with_a_union_argument_type_hint()
$mock->foo($object);
}

/** @test */
public function it_can_mock_a_class_with_a_union_argument_type_hint_including_null()
{
$mock = mock(ArgumentUnionTypeHintWithNull::class);
$mock->allows()->foo(null);

$mock->foo(null);
}

/** @test */
public function it_can_mock_a_class_with_a_parent_argument_type_hint()
{
Expand Down Expand Up @@ -78,6 +87,13 @@ public function foo(string|array|self $foo)
}
}

class ArgumentUnionTypeHintWithNull
{
public function foo(string|array|null $foo)
{
}
}

class ArgumentParentTypeHint extends \stdClass
{
public function foo(parent $foo)
Expand Down

0 comments on commit f3757c0

Please sign in to comment.