Skip to content

Commit

Permalink
Make optional constructor parameters nullable explicitly
Browse files Browse the repository at this point in the history
Implicitly nullable types are deprecated in PHP 8.4
  • Loading branch information
W0rma committed Oct 4, 2024
1 parent e3810e5 commit 1442852
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) {
continue;
}

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

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

0 comments on commit 1442852

Please sign in to comment.