Passed
Pull Request — 2.x (#59)
by butschster
16:42
created

DatabaseConfig::getIterator()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 0
cp 0
crap 2
rs 10
c 1
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cycle ORM package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\Database\Config;
13
14
use Cycle\Database\Driver\DriverInterface;
15
use Cycle\Database\Exception\ConfigException;
16
use Cycle\Database\NamedInterface;
17
use Spiral\Core\ConfigsInterface;
18
use Spiral\Core\Container\InjectableInterface;
19
use Spiral\Core\Traits\Config\AliasTrait;
20
21
final class DatabaseConfig implements InjectableInterface, \IteratorAggregate, \ArrayAccess
22
{
23
    use AliasTrait;
0 ignored issues
show
Deprecated Code introduced by
The trait Spiral\Core\Traits\Config\AliasTrait has been deprecated: to be removed in future releases. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

23
    use /** @scrutinizer ignore-deprecated */ AliasTrait;

This trait has been deprecated. The supplier of the trait has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the trait will be removed and what other trait to use instead.

Loading history...
24
25
    public const INJECTOR = ConfigsInterface::class;
26
    public const CONFIG = 'database';
27
    public const DEFAULT_DATABASE = 'default';
28
29
    /**
30
     * @internal
31
     *
32
     * @var array
33
     */
34
    protected array $config = [
35
        'default' => self::DEFAULT_DATABASE,
36
        'aliases' => [],
37
        'databases' => [],
38
        'connections' => [],
39
    ];
40
41
    /**
42 2
     * At this moment on array based configs can be supported.
43
     *
44 2
     * @param array $config
45
     */
46
    public function __construct(array $config = [])
47
    {
48
        $this->config = $config;
49
    }
50
51
    /**
52 6
     * @return string
53
     */
54 6
    public function getDefaultDatabase(): string
55 6
    {
56 6
        return $this->config['default'] ?? 'default';
57
    }
58
59 6
    /**
60
     * Get named list of all databases.
61
     *
62
     * @return DatabasePartial[]
63
     */
64
    public function getDatabases(): array
65
    {
66
        $result = [];
67 6
        foreach (array_keys($this->config['databases'] ?? []) as $database) {
68
            $result[$database] = $this->getDatabase($database);
69 6
        }
70 6
71 4
        return $result;
72
    }
73
74 6
    /**
75
     * Get names list of all driver connections.
76
     *
77
     * @return DriverInterface[]
78
     */
79
    public function getDrivers(): array
80
    {
81
        $result = [];
82 26
        foreach (array_keys($this->config['connections'] ?? $this->config['drivers'] ?? []) as $driver) {
83
            $result[$driver] = $this->getDriver($driver);
84 26
        }
85
86
        return $result;
87
    }
88
89
    /**
90
     * @param string $database
91
     *
92
     * @return bool
93
     */
94 20
    public function hasDatabase(string $database): bool
95
    {
96 20
        return isset($this->config['databases'][$database]);
97 2
    }
98
99
    /**
100 18
     * @param string $database
101
     *
102 18
     * @throws ConfigException
103
     *
104 18
     * @return DatabasePartial
105 18
     */
106 18
    public function getDatabase(string $database): DatabasePartial
107
    {
108
        if (!$this->hasDatabase($database)) {
109
            throw new ConfigException("Undefined database `{$database}`");
110
        }
111
112
        $config = $this->config['databases'][$database];
113
114
        return new DatabasePartial(
115 28
            $database,
116
            $config['tablePrefix'] ?? $config['prefix'] ?? '',
117 28
            $config['connection'] ?? $config['write'] ?? $config['driver'],
118
            $config['readConnection'] ?? $config['read'] ?? $config['readDriver'] ?? null
119
        );
120
    }
121
122
    /**
123
     * @param string $driver
124
     *
125
     * @return bool
126
     */
127 26
    public function hasDriver(string $driver): bool
128
    {
129 26
        return isset($this->config['connections'][$driver]) || isset($this->config['drivers'][$driver]);
130 6
    }
131
132
    /**
133 20
     * @param string $driver
134
     *
135 20
     * @throws ConfigException
136 18
     *
137
     * @return DriverInterface
138 18
     */
139 18
    public function getDriver(string $driver): DriverInterface
140
    {
141
        if (!$this->hasDriver($driver)) {
142
            throw new ConfigException("Undefined driver `{$driver}`");
143
        }
144
145 2
        $config = $this->config['connections'][$driver] ?? $this->config['drivers'][$driver];
146 2
147 2
        if ($config instanceof DriverConfig) {
148 2
            $driverObject = $config->driver::create($config);
149
150
            if ($driverObject instanceof NamedInterface) {
151
                return $driverObject->withName($driver);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $driverObject->withName($driver) returns the type Cycle\Database\NamedInterface which is incompatible with the type-hinted return Cycle\Database\Driver\DriverInterface.
Loading history...
152
            }
153
154
            return $driverObject;
155
        }
156
157
        throw new \InvalidArgumentException(
158
            \vsprintf('Driver config must be an instance of %s, but %s passed', [
159
                DriverConfig::class,
160
                \get_debug_type($config),
161
            ])
162
        );
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function toArray(): array
169
    {
170
        return $this->config;
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176
    public function offsetExists($offset)
177
    {
178
        return array_key_exists($offset, $this->config);
179
    }
180
181
    /**
182
     * {@inheritdoc}
183
     */
184
    public function offsetGet($offset)
185
    {
186
        if (!$this->offsetExists($offset)) {
187
            throw new \Spiral\Core\Exception\ConfigException("Undefined configuration key '{$offset}'");
188
        }
189
190
        return $this->config[$offset];
191
    }
192
193
    /**
194
     *{@inheritdoc}
195
     *
196
     * @throws ConfigException
197
     */
198
    public function offsetSet($offset, $value): void
199
    {
200
        throw new ConfigException(
201
            'Unable to change configuration data, configs are treated as immutable by default'
202
        );
203
    }
204
205
    /**
206
     *{@inheritdoc}
207
     *
208
     * @throws ConfigException
209
     */
210
    public function offsetUnset($offset): void
211
    {
212
        throw new ConfigException(
213
            'Unable to change configuration data, configs are treated as immutable by default'
214
        );
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function getIterator()
221
    {
222
        return new \ArrayIterator($this->config);
223
    }
224
}
225