Passed
Pull Request — master (#16)
by
unknown
02:49 queued 13s
created

SchemaFromConveyorFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 8
ccs 0
cts 8
cp 0
crap 2
rs 10
1
<?php
2
3
namespace Yiisoft\Yii\Cycle\Factory;
4
5
use Closure;
6
use Cycle\ORM\Schema;
7
use Cycle\Schema\Compiler;
8
use Cycle\Schema\GeneratorInterface;
9
use Cycle\Schema\Registry;
10
use Psr\Container\ContainerInterface;
11
use Psr\SimpleCache\CacheInterface;
12
use Spiral\Database\DatabaseManager;
13
use Yiisoft\Yii\Cycle\Conveyor\SchemaConveyorInterface;
14
15
final class SchemaFromConveyorFactory
16
{
17
    public string $cacheKey;
18
    public bool $cacheEnabled;
19
    /** @var GeneratorInterface[]|string[]|Closure[] */
20
    private array $generators;
21
22
    public function __construct(
23
        bool $cacheEnabled = true,
24
        string $cacheKey = 'Cycle-ORM-Schema',
25
        array $generators = []
26
    ) {
27
        $this->cacheEnabled = $cacheEnabled;
28
        $this->cacheKey = $cacheKey;
29
        $this->generators = $generators;
30
    }
31
32
    /**
33
     * @param ContainerInterface $container
34
     * @return Schema
35
     * @throws \Psr\SimpleCache\InvalidArgumentException
36
     * @throws \Yiisoft\Yii\Cycle\Exception\BadGeneratorDeclarationException
37
     */
38
    public function __invoke(ContainerInterface $container)
39
    {
40
        $schemaArray = null;
41
        if ($this->cacheEnabled) {
42
            $schemaArray = $container->get(CacheInterface::class)->get($this->cacheKey);
43
        }
44
        if (!is_array($schemaArray)) {
45
            $schemaArray = $this->generateSchemaArray(
46
                $container->get(SchemaConveyorInterface::class),
47
                $container->get(DatabaseManager::class)
48
            );
49
        }
50
        if ($this->cacheEnabled) {
51
            $container->get(CacheInterface::class)->set($this->cacheKey, $schemaArray);
52
        }
53
        return new Schema($schemaArray);
54
    }
55
56
    /**
57
     * @param SchemaConveyorInterface $conveyor
58
     * @param DatabaseManager $dbal
59
     * @return array
60
     * @throws \Yiisoft\Yii\Cycle\Exception\BadGeneratorDeclarationException
61
     */
62
    private function generateSchemaArray(SchemaConveyorInterface $conveyor, DatabaseManager $dbal): array
63
    {
64
        // add generators to userland stage
65
        foreach ($this->generators as $generator) {
66
            $conveyor->addGenerator(SchemaConveyorInterface::STAGE_USERLAND, $generator);
67
        }
68
        // compile schema array
69
        $generators = $conveyor->getGenerators();
70
        return (new Compiler())->compile(new Registry($dbal), $generators);
71
    }
72
}
73