Passed
Pull Request — master (#59)
by Sergei
13:57
created

FromFilesSchemaProvider::read()   A

Complexity

Conditions 6
Paths 9

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 14
rs 9.2222
cc 6
nc 9
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Schema\Provider;
6
7
use InvalidArgumentException;
8
use LogicException;
9
use Yiisoft\Aliases\Aliases;
10
use Yiisoft\Yii\Cycle\Schema\SchemaProviderInterface;
11
12
/**
13
 * Be careful, using this class may be insecure.
14
 */
15
final class FromFilesSchemaProvider implements SchemaProviderInterface
16
{
17
    private array $files = [];
18
    private Aliases $aliases;
19
20
    public function __construct(Aliases $aliases)
21
    {
22
        $this->aliases = $aliases;
23
    }
24
25
    /**
26
     * @param array $config
27
     * @return self
28
     * @throws InvalidArgumentException
29
     */
30
    public function withConfig(array $config): self
31
    {
32
        if (empty($config['files'])) {
33
            throw new InvalidArgumentException('Files not set.');
34
        }
35
36
        if (!is_array($config['files'])) {
37
            throw new InvalidArgumentException('The "files" parameter must be array.');
38
        }
39
40
        $files = $config['files'];
41
42
        $files = array_map(
43
            fn ($file) => $this->aliases->get($file),
44
            $files
45
        );
46
47
        $new = clone $this;
48
        $new->files = $files;
49
        return $new;
50
    }
51
52
    /**
53
     * @return array|null
54
     * @throws LogicException
55
     */
56
    public function read(): ?array
57
    {
58
        $schema = [];
59
        foreach ($this->files as $file) {
60
            if (is_file($file)) {
61
                foreach (require $file as $role => $definition) {
62
                    if (array_key_exists($role, $schema)) {
63
                        throw new LogicException('Role "' . $role . '" already has in schema.');
64
                    }
65
                    $schema[$role] = $definition;
66
                }
67
            }
68
        }
69
        return empty($schema) ? null : $schema;
70
    }
71
72
    public function write(array $schema): bool
73
    {
74
        return false;
75
    }
76
77
    public function clear(): bool
78
    {
79
        return false;
80
    }
81
82
    public function isWritable(): bool
83
    {
84
        return false;
85
    }
86
87
    public function isReadable(): bool
88
    {
89
        return true;
90
    }
91
}
92