Passed
Pull Request — master (#33)
by Rustam
02:23
created

Gii   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 85.71%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 9
eloc 19
c 4
b 1
f 0
dl 0
loc 47
ccs 18
cts 21
cp 0.8571
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B getGenerator() 0 20 7
A addGenerator() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Gii;
6
7
use Psr\Container\ContainerInterface;
8
use RuntimeException;
9
use Yiisoft\Yii\Gii\Exception\GeneratorNotFoundException;
10
11
final class Gii implements GiiInterface
12
{
13
    private ContainerInterface $container;
14
15
    /**
16
     * @var array<string, mixed>
17
     */
18
    private array $generators;
19
20 3
    public function __construct(array $generators, ContainerInterface $container)
21
    {
22 3
        $this->generators = $generators;
23 3
        $this->container = $container;
24 3
    }
25
26 1
    public function addGenerator(string $name, $generator): void
27
    {
28 1
        $this->generators[$name] = $generator;
29 1
    }
30
31
    /**
32
     * @param string $name
33
     *
34
     * @throws GeneratorNotFoundException
35
     *
36
     * @return GeneratorInterface
37
     */
38 3
    public function getGenerator(string $name): GeneratorInterface
39
    {
40 3
        if (!isset($this->generators[$name])) {
41 1
            throw new GeneratorNotFoundException('Generator "' . $name . '" not found');
42
        }
43 2
        $generator = $this->generators[$name];
44 2
        if (is_string($generator)) {
45
            $generator = $this->container->get($generator);
46 2
        } elseif ($generator instanceof GeneratorInterface) {
47 1
            return $generator;
48 1
        } elseif (is_object($generator) && method_exists($generator, '__invoke')) {
49
            /** @psalm-suppress InvalidFunctionCall */
50
            $generator = $generator($this->container);
51
        }
52 1
        if (!($generator instanceof GeneratorInterface)) {
53 1
            throw new RuntimeException(
54 1
                'Generator should be GeneratorInterface instance. "' . get_class($generator) . '" given.'
55
            );
56
        }
57
        return $generator;
58
    }
59
}
60