1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of Graze DataStructure |
4
|
|
|
* |
5
|
|
|
* Copyright (c) 2017 Nature Delivered Ltd. <http://graze.com> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
* |
10
|
|
|
* @see http://github.com/graze/data-structure/blob/master/LICENSE |
11
|
|
|
* @link http://github.com/graze/data-structure |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Graze\DataStructure\Container; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* ImmutableFlatContainer can access data in child arrays and containers, any modification is immutable |
18
|
|
|
* (for the top level) but can modify child containers |
19
|
|
|
* |
20
|
|
|
* ```php |
21
|
|
|
* $container = new ImmutableFlatContainer(['a'=>'b']); |
22
|
|
|
* $new = $container->set('c', 'd'); |
23
|
|
|
* $container->getAll(); |
24
|
|
|
* // ['a' => 'b'] |
25
|
|
|
* $new->getAll() |
26
|
|
|
* // ['a' => 'b', 'c' => 'd'] |
27
|
|
|
* |
28
|
|
|
* $child = new Container(['a' => 'b']); |
29
|
|
|
* $container = new ImmutableFlatContainer([ |
30
|
|
|
* ``` |
31
|
|
|
*/ |
32
|
|
|
class ImmutableFlatContainer extends FlatContainer |
33
|
|
|
{ |
34
|
|
|
/** |
35
|
|
|
* @param array $params |
36
|
|
|
*/ |
37
|
20 |
|
public function __construct(array $params = []) |
38
|
|
|
{ |
39
|
20 |
|
parent::__construct([]); |
40
|
|
|
|
41
|
20 |
|
foreach ($params as $key => $value) { |
42
|
17 |
|
$this->doSet($key, $this->recursiveClone($value)); |
43
|
|
|
} |
44
|
20 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param string $key |
48
|
|
|
* @param mixed $value |
49
|
|
|
* |
50
|
|
|
* @return ContainerInterface |
51
|
|
|
*/ |
52
|
5 |
|
public function set($key, $value) |
53
|
|
|
{ |
54
|
5 |
|
$cont = clone $this; |
55
|
5 |
|
$cont->doSet($key, $this->recursiveClone($value)); |
56
|
|
|
|
57
|
5 |
|
return $cont; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Clone children to ensure any modifications can not change this objects contents |
62
|
|
|
* |
63
|
|
|
* @param string $key |
64
|
|
|
* |
65
|
|
|
* @return mixed |
66
|
|
|
*/ |
67
|
8 |
|
public function get($key) |
68
|
|
|
{ |
69
|
8 |
|
return $this->recursiveClone(parent::get($key)); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param string $key |
74
|
|
|
* |
75
|
|
|
* @return ContainerInterface |
76
|
|
|
*/ |
77
|
3 |
|
public function remove($key) |
78
|
|
|
{ |
79
|
3 |
|
if ($this->has($key)) { |
80
|
2 |
|
$cont = clone $this; |
81
|
2 |
|
$cont->doRemove($key); |
82
|
|
|
|
83
|
2 |
|
return $cont; |
84
|
|
|
} |
85
|
|
|
|
86
|
1 |
|
return $this; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|