Passed
Pull Request — master (#34)
by Anton
02:40
created

Gii::getGenerator()   B

Complexity

Conditions 8
Paths 11

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 21
ccs 15
cts 15
cp 1
rs 8.4444
cc 8
nc 11
nop 1
crap 8
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 4
    public function __construct(array $generators, ContainerInterface $container)
21
    {
22 4
        $this->generators = $generators;
23 4
        $this->container = $container;
24 4
    }
25
26 3
    public function addGenerator(string $name, $generator): void
27
    {
28 3
        $this->generators[$name] = $generator;
29 3
    }
30
31
    /**
32
     * @param string $name
33
     *
34
     * @throws GeneratorNotFoundException
35
     *
36
     * @return GeneratorInterface
37
     */
38 4
    public function getGenerator(string $name): GeneratorInterface
39
    {
40 4
        if (!isset($this->generators[$name])) {
41 1
            throw new GeneratorNotFoundException('Generator "' . $name . '" not found');
42
        }
43 3
        $generator = $this->generators[$name];
44 3
        if (is_string($generator)) {
45 1
            $generator = $this->container->get($generator);
46 3
        } elseif ($generator instanceof GeneratorInterface) {
47 1
            return $generator;
48 3
        } elseif (is_object($generator) && method_exists($generator, '__invoke')) {
49
            /** @psalm-suppress InvalidFunctionCall */
50 1
            $generator = $generator($this->container);
51
        }
52 3
        if (!($generator instanceof GeneratorInterface)) {
53 2
            $type = is_object($generator) ? get_class($generator) : gettype($generator);
54 2
            throw new RuntimeException(
55 2
                'Generator should be GeneratorInterface instance. "' . $type . '" given.'
56
            );
57
        }
58 1
        return $generator;
59
    }
60
}
61