Skip to content

Commit

Permalink
ReflectionSourceStubber - fix enum as default function parameter value
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejmirtes committed Oct 2, 2023
1 parent e1511f1 commit 135a394
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/SourceLocator/SourceStubber/ReflectionSourceStubber.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Roave\BetterReflection\SourceLocator\SourceStubber;

use BackedEnum;
use LogicException;
use PhpParser\Builder\Class_;
use PhpParser\Builder\ClassConst;
Expand Down Expand Up @@ -46,10 +47,12 @@
use function assert;
use function explode;
use function function_exists;
use function get_class;
use function get_defined_constants;
use function implode;
use function in_array;
use function is_file;
use function is_object;
use function is_resource;
use function method_exists;
use function preg_replace;
Expand Down Expand Up @@ -579,7 +582,20 @@ private function setParameterDefaultValue(ReflectionParameter $parameterReflecti
return;
}

$parameterNode->setDefault($parameterReflection->getDefaultValue());
$defaultValue = $parameterReflection->getDefaultValue();
if (is_object($defaultValue)) {
$className = get_class($defaultValue);
$isEnum = function_exists('enum_exists') && \enum_exists($className, false);
if ($isEnum && $defaultValue instanceof BackedEnum) {
$parameterNode->setDefault(new Node\Expr\ClassConstFetch(
new FullyQualified($className),
new Node\Identifier($defaultValue->name)
));
return;
}
}

$parameterNode->setDefault($defaultValue);
}

private function formatType(CoreReflectionType $type): Name|NullableType|UnionType|IntersectionType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use Roave\BetterReflection\SourceLocator\SourceStubber\ReflectionSourceStubber;
use Roave\BetterReflection\SourceLocator\Type\PhpInternalSourceLocator;
use Roave\BetterReflectionTest\BetterReflectionSingleton;
use Roave\BetterReflectionTest\Fixture\SomeEnum;
use Traversable;

use function array_filter;
Expand Down Expand Up @@ -414,4 +415,14 @@ public function testUnknownConstant(): void
{
self::assertNull($this->stubber->generateConstantStub('SOME_CONSTANT'));
}

public function testClosureWithEnumParameterDefaultValue(): void
{
require_once __DIR__ . '/../../Fixture/Attributes.php';
$closure = function ($test = SomeEnum::ONE): void {

};
$stub = $this->stubber->generateFunctionStubFromReflection(new CoreReflectionFunction($closure));
self::assertStringContainsString('$test = \Roave\BetterReflectionTest\Fixture\SomeEnum::ONE', $stub->getStub());
}
}

0 comments on commit 135a394

Please sign in to comment.