Passed
Pull Request — master (#4)
by
unknown
01:43
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\BadDeclarationException;
9
use Yiisoft\Yii\Cycle\SchemaConveyorInterface;
10
11
class SchemaConveyor implements SchemaConveyorInterface
12
{
13
    /** @var array */
14
    protected $conveyor = [];
15
    /** @var ContainerInterface */
16
    protected $container;
17
18
    public function __construct(ContainerInterface $container)
19
    {
20
        $this->container = $container;
21
        $this->conveyor = [
22
            self::STAGE_INDEX => [],
23
            self::STAGE_RENDER => [
24
                // render tables and relations
25
                Generator\ResetTables::class,       // re-declared table schemas (remove columns)
26
                Generator\GenerateRelations::class, // generate entity relations
27
                Generator\ValidateEntities::class,  // make sure all entity schemas are correct
28
                Generator\RenderTables::class,      // declare table schemas
29
                Generator\RenderRelations::class,   // declare relation keys and indexes
30
            ],
31
            self::STAGE_USERLAND => [],
32
            self::STAGE_POSTPROCESS => [
33
                // post processing
34
                Generator\GenerateTypecast::class   // typecast non string columns
35
            ],
36
        ];
37
    }
38
39
    /**
40
     * @inheritDoc
41
     */
42
    public function addGenerator(string $stage, $generator): void
43
    {
44
        $this->conveyor[$stage][] = $generator;
45
    }
46
47
    /**
48
     * @inheritDoc
49
     */
50
    public function getGenerators(): array
51
    {
52
        $result = [];
53
        foreach ($this->conveyor as $group) {
54
            foreach ($group as $generator) {
55
                $g = null;
56
                if (is_string($generator)) {
57
                    $g = $this->container->get($generator);
58
                } elseif (is_object($generator) && $generator instanceof GeneratorInterface) {
59
                    $result[] = $generator;
60
                    continue;
61
                } elseif (is_object($generator) && method_exists($generator, '__invoke')) {
62
                    $g = $generator($this->container);
63
                }
64
                if ($g instanceof GeneratorInterface) {
65
                    $result[] = $g;
66
                    continue;
67
                }
68
                throw new BadDeclarationException();
69
            }
70
        }
71
        return $result;
72
    }
73
}
74