diff --git a/src/Definition/Repository/Cache/Compiler/ParameterDefinitionCompiler.php b/src/Definition/Repository/Cache/Compiler/ParameterDefinitionCompiler.php index d73806c..4afb4e2 100644 --- a/src/Definition/Repository/Cache/Compiler/ParameterDefinitionCompiler.php +++ b/src/Definition/Repository/Cache/Compiler/ParameterDefinitionCompiler.php @@ -6,6 +6,8 @@ namespace CuyZ\Valinor\Definition\Repository\Cache\Compiler; use CuyZ\Valinor\Definition\ParameterDefinition; +use function is_scalar; + /** @internal */ final class ParameterDefinitionCompiler { @@ -23,7 +25,7 @@ final class ParameterDefinitionCompiler { $isOptional = var_export($parameter->isOptional(), true); $isVariadic = var_export($parameter->isVariadic(), true); - $defaultValue = var_export($parameter->defaultValue(), true); + $defaultValue = $this->defaultValue($parameter); $type = $this->typeCompiler->compile($parameter->type()); $attributes = $this->attributesCompiler->compile($parameter->attributes()); @@ -39,4 +41,13 @@ final class ParameterDefinitionCompiler ) PHP; } + + private function defaultValue(ParameterDefinition $parameter): string + { + $defaultValue = $parameter->defaultValue(); + + return is_scalar($defaultValue) + ? var_export($parameter->defaultValue(), true) + : 'unserialize(' . var_export(serialize($defaultValue), true) . ')'; + } } diff --git a/tests/Fake/Type/FakeType.php b/tests/Fake/Type/FakeType.php index 476dfd3..bd0c867 100644 --- a/tests/Fake/Type/FakeType.php +++ b/tests/Fake/Type/FakeType.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace CuyZ\Valinor\Tests\Fake\Type; +use CuyZ\Valinor\Tests\Fixture\Object\StringableObject; use CuyZ\Valinor\Type\Type; use CuyZ\Valinor\Type\Types\ArrayKeyType; use CuyZ\Valinor\Type\Types\BooleanType; @@ -50,6 +51,10 @@ final class FakeType implements Type return new ClassType(stdClass::class); } + if ($raw === StringableObject::class) { + return new ClassType(StringableObject::class); + } + return new self(); } diff --git a/tests/Fixture/Object/ObjectWithParameterDefaultObjectValue.php b/tests/Fixture/Object/ObjectWithParameterDefaultObjectValue.php new file mode 100644 index 0000000..aed34bb --- /dev/null +++ b/tests/Fixture/Object/ObjectWithParameterDefaultObjectValue.php @@ -0,0 +1,13 @@ +isVariadic()); } + /** + * @PHP8.1 move to test above + * + * @requires PHP >= 8.1 + */ + public function test_parameter_with_object_default_value_is_compiled_correctly(): void + { + $class = FakeClassDefinition::fromReflection(new ReflectionClass(ObjectWithParameterDefaultObjectValue::class)); + + $class = $this->eval($this->compiler->compile($class)); + + self::assertInstanceOf(ClassDefinition::class, $class); + self::assertSame(ObjectWithParameterDefaultObjectValue::class, $class->name()); + } + public function test_modifying_class_definition_file_invalids_compiled_class_definition(): void { /** @var class-string $className */