Passed
Push — master ( 9c8ace...d62147 )
by Alexander
13:22
created

SchemaConveyor::getGenerators()   B

Complexity

Conditions 9
Paths 9

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 16
c 0
b 0
f 0
nc 9
nop 0
dl 0
loc 22
rs 8.0555
1
<?php
2
3
namespace Yiisoft\Yii\Cycle\Conveyor;
4
5
use Cycle\Schema\Generator;
6
use Cycle\Schema\GeneratorInterface;
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Yii\Cycle\Exception\BadGeneratorDeclarationException;
9
10
class SchemaConveyor implements SchemaConveyorInterface
11
{
12
    protected array $conveyor = [
13
        self::STAGE_INDEX => [
14
            Generator\ResetTables::class,       // re-declared table schemas (remove columns)
15
        ],
16
        self::STAGE_RENDER => [
17
            Generator\GenerateRelations::class, // generate entity relations
18
            Generator\ValidateEntities::class,  // make sure all entity schemas are correct
19
            Generator\RenderTables::class,      // declare table schemas
20
            Generator\RenderRelations::class,   // declare relation keys and indexes
21
        ],
22
        self::STAGE_USERLAND => [],
23
        self::STAGE_POSTPROCESS => [
24
            Generator\GenerateTypecast::class   // typecast non string columns
25
        ],
26
    ];
27
28
    protected ContainerInterface $container;
29
30
    public function __construct(ContainerInterface $container)
31
    {
32
        $this->container = $container;
33
    }
34
35
    public function addGenerator(string $stage, $generator): void
36
    {
37
        $this->conveyor[$stage][] = $generator;
38
    }
39
40
    public function getGenerators(): array
41
    {
42
        $result = [];
43
        foreach ($this->conveyor as $group) {
44
            foreach ($group as $generatorDefinition) {
45
                $generator = null;
46
                if (is_string($generatorDefinition)) {
47
                    $generator = $this->container->get($generatorDefinition);
48
                } elseif (is_object($generatorDefinition) && $generatorDefinition instanceof GeneratorInterface) {
49
                    $result[] = $generatorDefinition;
50
                    continue;
51
                } elseif (is_object($generatorDefinition) && method_exists($generatorDefinition, '__invoke')) {
52
                    $generator = $generatorDefinition($this->container);
53
                }
54
                if ($generator instanceof GeneratorInterface) {
55
                    $result[] = $generator;
56
                    continue;
57
                }
58
                throw new BadGeneratorDeclarationException();
59
            }
60
        }
61
        return $result;
62
    }
63
}
64