Passed
Pull Request — master (#4)
by
unknown
01:33
created

SchemaConveyor::addGenerator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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