Passed
Pull Request — master (#68)
by Aleksei
04:14
created

SchemaManager::createPipeline()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 11
c 0
b 0
f 0
dl 0
loc 15
ccs 12
cts 12
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 14
    public function __construct(ContainerInterface $container, array $providers)
21
    {
22 14
        $this->providers = $this->createPipeline($container, $providers);
23 14
    }
24
25 10
    public function read(): ?array
26
    {
27 10
        if ($this->providers->count() === 0) {
28 1
            return null;
29
        }
30 9
        $this->providers->rewind();
31 9
        return $this->providers->current()->read();
32
    }
33
34 4
    public function clear(): void
35
    {
36 4
        $exceptions = [];
37 4
        foreach ($this->providers as $provider) {
38
            try {
39 3
                $provider->clear();
40 1
            } catch (\Throwable $e) {
41 1
                $exceptions[] = $e;
42
            }
43
        }
44 4
        if (count($exceptions)) {
45 1
            throw new CumulativeException(...$exceptions);
46
        }
47 3
    }
48
49 14
    private function createPipeline(ContainerInterface $container, array $providers): SplDoublyLinkedList
50
    {
51 14
        $stack = new SplDoublyLinkedList();
52 14
        $nextProvider = null;
53 14
        foreach (array_reverse($providers) as $key => $definition) {
54 12
            $config = [];
55 12
            if (is_string($key) && is_array($definition)) {
56 1
                $config = $definition;
57 1
                $definition = $key;
58
            }
59 12
            $nextProvider = (new DeferredSchemaProviderDecorator($container, $definition, $nextProvider))
60 12
                ->withConfig($config);
61 12
            $stack->unshift($nextProvider);
62
        }
63 14
        return $stack;
64
    }
65
}
66