-
Notifications
You must be signed in to change notification settings - Fork 3
/
HierarchyContainer.php
89 lines (78 loc) · 2.2 KB
/
HierarchyContainer.php
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
declare(strict_types=1);
namespace Dhii\Container;
use Dhii\Collection\ContainerInterface;
use Dhii\Container\Exception\NotFoundException;
use stdClass;
/**
* A container implementation that provides access to hierarchical data in the form a container tree.
*
* This implementation dynamically transforms hierarchical data into a tree of containers, on-demand. The transformation
* is performed "in-place", converting internal array and object values into containers without producing a copy or
* internal cache, making this implementation very memory-friendly.
*
* **Example usage:**
*
* ```php
* $data = [
* 'config' => [
* 'db' => [
* 'host' => 'localhost',
* 'port' => 3306,
* ],
* ]
* ];
*
* $container = new HierarchicalContainer($data);
* $container->get('config')->get('db')->get('host'); // "localhost"
* ```
*
* @since [*next-version*]
* @see PathContainer For an implementation that compliments this one by allowing container trees to be accessed using
* path-like keys.
* @see SegmentingContainer For an implementation that achieves a similar effect but for flat hierarchies.
*/
class HierarchyContainer implements ContainerInterface
{
/**
* @since [*next-version*]
*
* @var mixed[]
*/
protected $data;
/**
* Constructor.
*
* @since [*next-version*]
*
* @param mixed[] $data The hierarchical data for which to create the container tree.
*/
public function __construct(array $data)
{
$this->data = $data;
}
/**
* @inheritDoc
*/
public function get(string $key)
{
if (!array_key_exists($key, $this->data)) {
throw new NotFoundException("Key '{$key}' does not exist", 0, null);
}
$value = $this->data[$key];
if ($value instanceof stdClass) {
$value = get_object_vars($value);
}
if (is_array($value)) {
$value = $this->data[$key] = new self($value);
}
return $value;
}
/**
* @inheritDoc
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
}
}