From 6ec9057e88b2d80dcddba5492b6f04e31e5784cb Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 29 Sep 2022 08:48:54 +0200 Subject: [PATCH] Dont allow generating proxies for readonly classes --- src/Proxy/Exception/InvalidArgumentException.php | 11 +++++++++++ src/Proxy/ProxyGenerator.php | 4 ++++ tests/Common/Proxy/ProxyGeneratorTest.php | 12 ++++++++++++ tests/Common/Proxy/ReadOnlyClass.php | 7 +++++++ 4 files changed, 34 insertions(+) create mode 100644 tests/Common/Proxy/ReadOnlyClass.php diff --git a/src/Proxy/Exception/InvalidArgumentException.php b/src/Proxy/Exception/InvalidArgumentException.php index f6eeb85b1..998600e20 100644 --- a/src/Proxy/Exception/InvalidArgumentException.php +++ b/src/Proxy/Exception/InvalidArgumentException.php @@ -91,6 +91,17 @@ public static function classMustNotBeFinal($className) return new self(sprintf('Unable to create a proxy for a final class "%s".', $className)); } + /** + * @param string $className + * @psalm-param class-string $className + * + * @return self + */ + public static function classMustNotBeReadOnly($className) + { + return new self(sprintf('Unable to create a proxy for a readonly class "%s".', $className)); + } + /** @param mixed $value */ public static function invalidAutoGenerateMode($value): self { diff --git a/src/Proxy/ProxyGenerator.php b/src/Proxy/ProxyGenerator.php index 3219a794d..3ef767670 100644 --- a/src/Proxy/ProxyGenerator.php +++ b/src/Proxy/ProxyGenerator.php @@ -361,6 +361,10 @@ private function verifyClassCanBeProxied(ClassMetadata $class) if ($class->getReflectionClass()->isAbstract()) { throw InvalidArgumentException::classMustNotBeAbstract($class->getName()); } + + if (PHP_VERSION_ID >= 80200 && $class->getReflectionClass()->isReadOnly()) { + throw InvalidArgumentException::classMustNotBeReadOnly($class->getName()); + } } /** diff --git a/tests/Common/Proxy/ProxyGeneratorTest.php b/tests/Common/Proxy/ProxyGeneratorTest.php index 8fca420ce..59c1eb3ef 100644 --- a/tests/Common/Proxy/ProxyGeneratorTest.php +++ b/tests/Common/Proxy/ProxyGeneratorTest.php @@ -405,6 +405,18 @@ public function testFinalClassThrowsException() $proxyGenerator->generateProxyClass($this->createClassMetadata(FinalClass::class, [])); } + /** + * @requires PHP >= 8.2.0 + */ + public function testReadOnlyClassThrowsException() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Unable to create a proxy for a readonly class "' . ReadOnlyClass::class . '".'); + + $proxyGenerator = new ProxyGenerator(__DIR__ . '/generated', __NAMESPACE__ . 'Proxy'); + $proxyGenerator->generateProxyClass($this->createClassMetadata(ReadOnlyClass::class, [])); + } + /** * @requires PHP >= 8.0.0 */ diff --git a/tests/Common/Proxy/ReadOnlyClass.php b/tests/Common/Proxy/ReadOnlyClass.php new file mode 100644 index 000000000..3b05c9a49 --- /dev/null +++ b/tests/Common/Proxy/ReadOnlyClass.php @@ -0,0 +1,7 @@ +