diff --git a/lib/Doctrine/Common/Proxy/ProxyGenerator.php b/lib/Doctrine/Common/Proxy/ProxyGenerator.php index 1401bcbf7..0714d3884 100644 --- a/lib/Doctrine/Common/Proxy/ProxyGenerator.php +++ b/lib/Doctrine/Common/Proxy/ProxyGenerator.php @@ -1091,10 +1091,7 @@ private function buildParametersString(array $parameters, array $renameParameter } $parameterDefinition .= '$' . ($renameParameters ? $renameParameters[$i] : $param->getName()); - - if ($param->isDefaultValueAvailable()) { - $parameterDefinition .= ' = ' . var_export($param->getDefaultValue(), true); - } + $parameterDefinition .= $this->getParameterDefaultValue($param); $parameterDefinitions[] = $parameterDefinition; } @@ -1118,6 +1115,24 @@ private function getParameterType(ReflectionParameter $parameter) return $this->formatType($parameter->getType(), $declaringFunction, $parameter); } + /** + * @return string + */ + private function getParameterDefaultValue(ReflectionParameter $parameter) + { + if (! $parameter->isDefaultValueAvailable()) { + return ''; + } + + if (PHP_VERSION_ID < 80100) { + return ' = ' . var_export($parameter->getDefaultValue(), true); + } + + $value = rtrim(substr(explode('$' . $parameter->getName() . ' = ', (string) $parameter, 2)[1], 0, -2)); + + return ' = ' . $value; + } + /** * @param ReflectionParameter[] $parameters * diff --git a/tests/Doctrine/Tests/Common/Proxy/PHP81NewInInitializers.php b/tests/Doctrine/Tests/Common/Proxy/PHP81NewInInitializers.php new file mode 100644 index 000000000..d9c40da87 --- /dev/null +++ b/tests/Doctrine/Tests/Common/Proxy/PHP81NewInInitializers.php @@ -0,0 +1,23 @@ +assertSame($object->isEnum, \Doctrine\Tests\Common\Proxy\YesOrNo::YES); } + /** + * @requires PHP >= 8.1.0 + */ + public function testPhp81NewInInitializers() + { + $className = PHP81NewInInitializers::class; + + if (!class_exists('Doctrine\Tests\Common\ProxyProxy\__CG__\PHP81NewInInitializers', false)) { + $metadata = $this->createClassMetadata($className, ['id']); + + $proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy'); + $this->generateAndRequire($proxyGenerator, $metadata); + } + + self::assertStringContainsString( + 'onlyInitializer($foo = new \stdClass()): void', + file_get_contents(__DIR__ . '/generated/__CG__DoctrineTestsCommonProxyPHP81NewInInitializers.php') + ); + + self::assertStringContainsString( + 'typed(\DateTimeInterface $foo = new \DateTimeImmutable(\'now\')): void', + file_get_contents(__DIR__ . '/generated/__CG__DoctrineTestsCommonProxyPHP81NewInInitializers.php') + ); + + self::assertStringContainsString( + 'arrayInDefault(array $foo = [new \DateTimeImmutable(\'2022-08-22 16:20\', new \DateTimeZone(\'Europe/Warsaw\'))]): void', + file_get_contents(__DIR__ . '/generated/__CG__DoctrineTestsCommonProxyPHP81NewInInitializers.php') + ); + } + /** * @param string $className * @param mixed[] $ids