Skip to content

Commit

Permalink
Merge pull request #632 from W0rma/php84-explicit-nullable-types
Browse files Browse the repository at this point in the history
DisableConstructorPatch: make optional constructor parameters nullable explicitly
  • Loading branch information
stof authored Oct 11, 2024
2 parents c5d07b9 + 731031d commit f425512
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Prophecy\Doubler\Generator\Node\ArgumentNode;
use Prophecy\Doubler\Generator\Node\ArgumentTypeNode;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;

Expand All @@ -31,6 +32,9 @@ function it_makes_all_constructor_arguments_optional(
ArgumentNode $arg1,
ArgumentNode $arg2
) {
$arg1->getTypeNode()->willReturn(new ArgumentTypeNode('string', 'null'));
$arg2->getTypeNode()->willReturn(new ArgumentTypeNode('mixed'));

$class->isExtendable('__construct')->willReturn(true);
$class->hasMethod('__construct')->willReturn(true);
$class->getMethod('__construct')->willReturn($method);
Expand All @@ -39,6 +43,8 @@ function it_makes_all_constructor_arguments_optional(
$arg1->setDefault(null)->shouldBeCalled();
$arg2->setDefault(null)->shouldBeCalled();

$arg1->setTypeNode(new ArgumentTypeNode('null', 'string'))->shouldBeCalled();

$method->setCode(Argument::type('string'))->shouldBeCalled();

$this->apply($class);
Expand Down
8 changes: 8 additions & 0 deletions src/Prophecy/Doubler/ClassPatch/DisableConstructorPatch.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace Prophecy\Doubler\ClassPatch;

use Prophecy\Doubler\Generator\Node\ArgumentTypeNode;
use Prophecy\Doubler\Generator\Node\ClassNode;
use Prophecy\Doubler\Generator\Node\MethodNode;

Expand Down Expand Up @@ -55,6 +56,13 @@ public function apply(ClassNode $node)
\assert($constructor !== null);
foreach ($constructor->getArguments() as $argument) {
$argument->setDefault(null);

$types = $argument->getTypeNode()->getNonNullTypes();
if ([] === $types || ['mixed'] === $types || ['\mixed'] === $types) {
continue;
}

$argument->setTypeNode(new ArgumentTypeNode('null', ...$types));
}

$constructor->setCode(<<<PHP
Expand Down

0 comments on commit f425512

Please sign in to comment.