Skip to content

Commit

Permalink
creating lazy services in PHP 8.4 WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Nov 25, 2024
1 parent 9b9bfb4 commit d9d7d4c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/DI/Definitions/ServiceDefinition.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

use Nette;
use Nette\DI\ServiceCreationException;
use Nette\Utils\Strings;


/**
Expand All @@ -29,6 +30,8 @@ final class ServiceDefinition extends Definition
/** @var Statement[] */
private array $setup = [];

private bool $lazy = true;


public function __construct()
{
Expand Down Expand Up @@ -181,6 +184,24 @@ private function prependSelf(Statement $setup): Statement

public function generateMethod(Nette\PhpGenerator\Method $method, Nette\DI\PhpGenerator $generator): void
{
if ($this->canLazy()) {
$rc = new \ReflectionClass($this->creator->getEntity());
$code = $rc->hasMethod('__construct')
? $generator->formatPhp("\$service->__construct(...?:);\n", [$this->creator->arguments])
: '';
foreach ($this->setup as $setup) {
$code .= $generator->formatStatement($setup) . ";\n";
}
$method->setBody(
"return new ReflectionClass({$rc->getName()}::class)->newLazyGhost(function (\$service) {\n"
. Strings::indent($code)
. '});',
);
if (!preg_match('#(?:func_get_arg|func_num_args)#i', $code)) { // latteFactory workaround
return;
}
}

$code = $generator->formatStatement($this->creator) . ";\n";
if (!$this->setup) {
$method->setBody('return ' . $code);
Expand All @@ -197,6 +218,22 @@ public function generateMethod(Nette\PhpGenerator\Method $method, Nette\DI\PhpGe
}


private function canLazy(): bool
{
if (!$this->lazy || !is_string($this->creator->getEntity()) || PHP_VERSION_ID < 80400) {
return false;
}

$rc = new \ReflectionClass($this->creator->getEntity());
do {
if ($rc->isInternal()) {
return false;
}
} while ($rc = $rc->getParentClass());
return true;
}


public function __clone()
{
parent::__clone();
Expand Down
2 changes: 2 additions & 0 deletions src/DI/Extensions/DIExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ public function __construct(bool $debugMode = false)
public array $excluded = [];
public ?string $parentClass = null;
public object $export;
public bool $lazy = false;
};
$this->config->export = new class {
public bool $parameters = true;
Expand All @@ -62,6 +63,7 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class): void
$class->setExtends($this->config->parentClass);
}

$this->initializeLazy($class);
$this->restrictParameters($class);
$this->restrictTags($class);
$this->restrictTypes($class);
Expand Down

0 comments on commit d9d7d4c

Please sign in to comment.