Dictionary.php
3.14 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
<?php
// Copyright (c) Lellys Informática. All rights reserved. See License.txt in the project root for license information.
namespace Easy\Collections;
use InvalidArgumentException;
use OutOfBoundsException;
use Traversable;
/**
* Represents a collection of keys and values.
*/
class Dictionary extends CollectionArray implements MapInterface, MapConvertableInterface
{
public function __construct($array = null)
{
if ($array !== null) {
$this->addAll($array);
}
}
public function hashCode($object)
{
return spl_object_hash($object);
}
/**
* {@inheritdoc}
*/
public function add($key, $value)
{
if ($this->containsKey($key)) {
throw new InvalidArgumentException('The key ' . $key . ' already exists!');
}
$this->set($key, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function addAll($items)
{
if (!is_array($items) && !$items instanceof Traversable) {
throw new \InvalidArgumentException('The items must be an array or Traversable');
}
foreach ($items as $key => $value) {
if (is_array($value)) {
$value = Dictionary::fromArray($value);
}
$this->add($key, $value);
}
}
public function set($key, $value)
{
if ($key === null) {
throw new InvalidArgumentException("Can't use 'null' as key!");
}
$this->offsetSet($key, $value);
return $this;
}
/**
* {@inheritdoc}
*/
public function offsetExists($offset)
{
if (is_object($offset)) {
$offset = $this->hashCode($offset);
}
return isset($this->array[$offset]) || array_key_exists($offset, $this->array);
}
/**
* {@inheritdoc}
*/
public function offsetGet($offset)
{
if ($this->containsKey($offset) === false) {
throw new OutOfBoundsException('No element at position ' . $offset);
}
if (is_object($offset)) {
$offset = $this->hashCode($offset);
}
return $this->array[$offset];
}
/**
* {@inheritdoc}
*/
public function offsetSet($offset, $value)
{
if (is_object($offset)) {
$offset = $this->hashCode($offset);
}
$this->array[$offset] = $value;
}
/**
* {@inheritdoc}
*/
public function offsetUnset($offset)
{
if ($this->containsKey($offset) === false) {
throw new InvalidArgumentException('The key ' . $offset . ' is not present in the dictionary');
}
unset($this->array[$offset]);
}
/**
* {@inheritdoc}
*/
public function toList()
{
return new ArrayList($this->array);
}
/**
* {@inheritdoc}
*/
public static function fromArray(array $arr)
{
$map = new Dictionary();
foreach ($arr as $k => $v) {
if (is_array($v)) {
$map->add($k, new Dictionary($v));
} else {
$map->add($k, $v);
}
}
return $map;
}
}