Passed
Pull Request — master (#68)
by Aleksei
18:23
created

SchemaManager::createPipeline()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 9.9
cc 4
nc 3
nop 2
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Schema;
6
7
use Psr\Container\ContainerInterface;
8
use SplDoublyLinkedList;
9
use Yiisoft\Yii\Cycle\Exception\CumulativeException;
10
use Yiisoft\Yii\Cycle\Schema\Provider\DeferredSchemaProviderDecorator;
11
12
/**
13
 * SchemaManager allows reading schema from providers available and clearing the schema in providers.
14
 */
15
final class SchemaManager
16
{
17
    /** @var SplDoublyLinkedList<int, SchemaProviderInterface> */
18
    private SplDoublyLinkedList $providers;
19
20
    public function __construct(ContainerInterface $container, array $providers)
21 19
    {
22
        $this->providers = $this->createPipeline($container, $providers);
23 19
    }
24 19
25 19
    public function read(): ?array
26
    {
27 13
        if ($this->providers->count() === 0) {
28
            return null;
29 13
        }
30 13
        $this->providers->rewind();
31
        return $this->providers->current()->read();
32 13
    }
33 11
34 11
    public function clear(): void
35 11
    {
36 10
        $exceptions = [];
37
        foreach ($this->providers as $provider) {
38
            try {
39 5
                $provider->clear();
40 4
            } catch (\Throwable $e) {
41
                $exceptions[] = $e;
42
            }
43
        }
44 12
        if (count($exceptions)) {
45 2
            throw new CumulativeException(...$exceptions);
46
        }
47
    }
48
49
    private function createPipeline(ContainerInterface $container, array $providers): SplDoublyLinkedList
50 10
    {
51 3
        $stack = new SplDoublyLinkedList();
52
        $nextProvider = null;
53
        foreach (array_reverse($providers) as $key => $definition) {
54 10
            $config = [];
55
            if (is_string($key) && is_array($definition)) {
56
                $config = $definition;
57 6
                $definition = $key;
58
            }
59 6
            $nextProvider = (new DeferredSchemaProviderDecorator($container, $definition, $nextProvider))
60 6
                ->withConfig($config);
61
            $stack->unshift($nextProvider);
62 6
        }
63 6
        return $stack;
64 4
    }
65
}
66