Passed
Pull Request — master (#32)
by Anton
08:45 queued 06:16
created

Gii::getGenerator()   B

Complexity

Conditions 7
Paths 8

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 7.4822

Importance

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