-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigContainer.php
More file actions
67 lines (56 loc) · 1.71 KB
/
ConfigContainer.php
File metadata and controls
67 lines (56 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php declare(strict_types=1);
/*
* This file is part of Polymorphine/Container package.
*
* (c) Shudd3r <q3.shudder@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Polymorphine\Container;
use Psr\Container\ContainerInterface;
/**
* Container with multidimensional array values accessed using path notation identifiers.
*
* @example $container = new ConfigContainer($config);
* $container->get('key.sub-key.id') === $config['key']['sub-key']['id']; //true
*/
class ConfigContainer implements ContainerInterface
{
public const SEPARATOR = '.';
private array $config;
/**
* $config keys MUST NOT contain path separator (`.` character) on any level.
* Values stored under these keys will not be accessible.
*
* @param array $config Associative (multidimensional) array of config values
*/
public function __construct(array $config)
{
$this->config = $config;
}
public function get($id)
{
$data = &$this->config;
$keys = explode(self::SEPARATOR, $id);
foreach ($keys as $key) {
if (!is_array($data) || !array_key_exists($key, $data)) {
throw Exception\RecordNotFoundException::undefined($id);
}
$data = &$data[$key];
}
return $data;
}
public function has($id): bool
{
$data = &$this->config;
$keys = explode(self::SEPARATOR, $id);
foreach ($keys as $key) {
if (!is_array($data) || !array_key_exists($key, $data)) {
return false;
}
$data = &$data[$key];
}
return true;
}
}