Skip to content

Commit

Permalink
Make generators lazy
Browse files Browse the repository at this point in the history
  • Loading branch information
xepozz committed Oct 8, 2023
1 parent 83d964f commit 780a5f4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 11 deletions.
6 changes: 3 additions & 3 deletions config/di.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@
foreach ($generators as $generator) {
$class = $generator['class'];
/**
* @var $generator GeneratorInterface
* @var $loader Closure(): GeneratorInterface
*/
$generator = $injector->make($class, $generator['parameters'] ?? []);
$generatorsInstances[] = $generator;
$loader = fn() => $injector->make($class, $generator['parameters'] ?? []);
$generatorsInstances[$class] = $loader;
}
return new Gii($generatorsInstances);
},
Expand Down
17 changes: 10 additions & 7 deletions src/Gii.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@

namespace Yiisoft\Yii\Gii;

use Closure;
use Yiisoft\Yii\Gii\Exception\GeneratorNotFoundException;

/**
* @psalm-import-type LazyGenerator from GiiInterface
*/
final class Gii implements GiiInterface
{
/**
* @param array<string, GeneratorInterface> $generators
* @param array<string, LazyGenerator|GeneratorInterface> $generators
*/
public function __construct(private array $generators)
{
$this->generators = array_combine(
array_map(fn (GeneratorInterface $generator) => $generator::getId(), $generators),
array_values($this->generators)
);
}

public function addGenerator(GeneratorInterface $generator): void
Expand All @@ -30,11 +30,14 @@ public function getGenerator(string $id): GeneratorInterface
throw new GeneratorNotFoundException('Generator "' . $id . '" not found');
}

return $this->generators[$id];
return $this->generators[$id] instanceof Closure ? $this->generators[$id]() : $this->generators[$id];

Check warning on line 33 in src/Gii.php

View check run for this annotation

Codecov / codecov/patch

src/Gii.php#L33

Added line #L33 was not covered by tests
}

public function getGenerators(): array
{
return $this->generators;
return array_map(
fn (Closure|GeneratorInterface $generator) => $generator instanceof Closure ? $generator() : $generator,
$this->generators
);
}
}
6 changes: 5 additions & 1 deletion src/GiiInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@

namespace Yiisoft\Yii\Gii;

use Closure;
use Yiisoft\Yii\Gii\Exception\GeneratorNotFoundException;

/**
* @psalm-type LazyGenerator = Closure(): GeneratorInterface
*/
interface GiiInterface
{
/**
* @param GeneratorInterface $generator
* @psalm-param GeneratorInterface $generator
*/
public function addGenerator(GeneratorInterface $generator): void;

Expand Down

0 comments on commit 780a5f4

Please sign in to comment.