Skip to content

Commit

Permalink
[DependencyInjection] unable to make lazy service from readonly class s…
Browse files Browse the repository at this point in the history
  • Loading branch information
kor3k committed Feb 8, 2024
1 parent fa843ce commit e6068f7
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,9 @@ private function generateProxyClasses(): array
$proxyCode = substr(self::stripComments($proxyCode), 5);
}

$proxyClass = explode(' ', $this->inlineRequires ? substr($proxyCode, \strlen($code)) : $proxyCode, 3)[1];
$proxyClass = $this->inlineRequires ? substr($proxyCode, \strlen($code)) : $proxyCode;
$i = strpos($proxyClass, 'class');
$proxyClass = substr($proxyClass, 6 + $i, strpos($proxyClass, ' ', 7 + $i) - $i - 6);

if ($this->asFiles || $this->namespace) {
$proxyCode .= "\nif (!\\class_exists('$proxyClass', false)) {\n \\class_alias(__NAMESPACE__.'\\\\$proxyClass', '$proxyClass', false);\n}\n";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public function getProxyCode(Definition $definition, ?string $id = null): string

if ($asGhostObject) {
try {
return 'class '.$proxyClass.ProxyHelper::generateLazyGhost($class);
return (\PHP_VERSION_ID >= 80200 && $class?->isReadOnly() ? 'readonly ' : '').'class '.$proxyClass.ProxyHelper::generateLazyGhost($class);
} catch (LogicException $e) {
throw new InvalidArgumentException(sprintf('Cannot generate lazy ghost for service "%s".', $id ?? $definition->getClass()), 0, $e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ public function testInvalidClass()
$this->expectExceptionMessage('Invalid "proxy" tag for service "stdClass": class "stdClass" doesn\'t implement "Psr\Container\ContainerInterface".');
$dumper->getProxyCode($definition);
}

public function testReadonlyClass()
{
$dumper = new LazyServiceDumper();
$definition = (new Definition(ReadonlyTest::class))->setLazy(true);

$this->assertTrue($dumper->isProxyCandidate($definition));
$this->assertStringContainsString('readonly class ReadonlyTestGhost', $dumper->getProxyCode($definition));
}
}

final class TestContainer implements ContainerInterface
Expand All @@ -66,3 +75,11 @@ public function get(string $key): string
return $key;
}
}

readonly class ReadonlyTest
{
public function say(): string
{
return 'hello';
}
}

0 comments on commit e6068f7

Please sign in to comment.