Passed
Push — master ( 0672c9...d1a262 )
by
unknown
05:07
created

AbstractStorage::setEventManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Minerva\Collections\Basis\Abstractions;
4
5
use Minerva\Collections\Basis\Exceptions\InvalidCapacityException;
6
use Minerva\Collections\Basis\Exceptions\InvalidOffsetException;
7
use Minerva\Collections\Basis\Exceptions\MaxCapacityReachedException;
8
use Minerva\Collections\Basis\Interfaces\StorageInterface;
9
use Minerva\Collections\Basis\Exceptions\ReadOnlyStorageException;
10
use Zend\EventManager\EventManager;
11
use Zend\EventManager\EventManagerInterface;
12
13
/**
14
 * Implementação abstrata do storage
15
 *
16
 * @author  Lucas A. de Araújo <[email protected]>
17
 * @package Minerva\Collections\Basis\Abstractions
18
 */
19
abstract class AbstractStorage implements StorageInterface
20
{
21
22
    /**
23
     * Array onde os dados serão armazenados
24
     *
25
     * @var array
26
     */
27
    protected $storage = array();
28
29
    /**
30
     * Eventos
31
     *
32
     * @var EventManagerInterface
33
     */
34
    protected $events;
35
36
    /**
37
     * Elemento atual em operação
38
     *
39
     * @var int
40
     */
41
    protected $current = 0;
42
43
    /**
44
     * Define se o storage é apenas para leitura
45
     *
46
     * @var bool
47
     */
48
    private $readOnly = false;
49
50
    /**
51
     * Define a capacidade máxima do storage
52
     *
53
     * @var int|null
54
     */
55
    private $capacity = null;
56
57
    /**
58
     * Define o manager de eventos
59
     *
60
     * @param EventManagerInterface $events
61
     * @return void
62
     */
63 10
    public function setEventManager(EventManagerInterface $events)
64 1
    {
65 10
        $events->setIdentifiers([__CLASS__, get_called_class()]);
66 10
        $this->events = $events;
67 10
    }
68
69
    /**
70
     * Retorna o event manager
71
     *
72
     * @return EventManagerInterface
73
     */
74 10
    public function getEventManager()
75
    {
76 10
        if (null === $this->events) {
77 10
            $this->setEventManager(new EventManager());
78 10
        }
79
80 10
        return $this->events;
81
    }
82
83
    /**
84
     * @return boolean
85
     */
86 10
    public function isReadOnly()
87
    {
88 10
        return $this->readOnly;
89
    }
90
91
    /**
92
     * Fecha a coleção para apenas leitura
93
     */
94 2
    public function lock()
95
    {
96 2
        $this->readOnly = true;
97 2
    }
98
99
    /**
100
     * @return int|null
101
     */
102 10
    public function getCapacity()
103
    {
104 10
        return $this->capacity;
105
    }
106
107
    /**
108
     * @param int|null $capacity
109
     * @throws InvalidCapacityException
110
     */
111 1
    public function setCapacity($capacity)
112
    {
113 1
        if(!is_int($capacity))
114 1
            throw new InvalidCapacityException();
115
116 1
        if($this->count() > $capacity)
117 1
            throw new InvalidCapacityException();
118
119 1
        $this->capacity = $capacity;
120 1
    }
121
122
    /**
123
     * Executa callback para cada elemento armazenado
124
     *
125
     * @param callable $callback
126
     * @return void
127
     */
128 3
    public function each(callable $callback)
129
    {
130 3
        foreach ($this->storage as $key => $item)
131 3
            $callback($item, $key);
132 3
    }
133
134
    /**
135
     * Filtra elementos armazenados de acordo com callback
136
     *
137
     * @param callable $callback
138
     * @return StorageInterface
139
     */
140 2
    public function filter(callable $callback)
141
    {
142 2
        $storage = clone $this;
143 2
        $storage->clear();
144
145
        $this->each(function($item, $key) use(&$storage, $callback){
146 2
            if($callback($item, $key) === true)
147 2
                $storage[$key] = $item;
148 2
        });
149
150 2
        return $storage;
151
    }
152
153
    /**
154
     * Copia o conteúdo do storage para dentro de outra array ou storage
155
     *
156
     * @param $array
157
     * @param bool $override
158
     */
159
    public function copyTo(&$array, $override = true)
160
    {
161 1
        $this->each(function($item, $key) use(&$array, $override){
162 1
            if(!$override && isset($array[$key]))
163 1
                return ;
164
165 1
           $array[$key] = $item;
166 1
        });
167 1
    }
168
169
    /**
170
     * Limpa o storage completamente
171
     *
172
     * @throws ReadOnlyStorageException
173
     */
174 3
    public function clear()
175
    {
176 3
        $this->getEventManager()->trigger('beforeClear', $this);
177
178 3
        if($this->isReadOnly())
179 3
            throw new ReadOnlyStorageException();
180
181 3
        $this->storage = array();
182 3
        $this->getEventManager()->trigger('afterClear', $this);
183 3
    }
184
185
    /**
186
     * Retorna o número de elementos armazenados
187
     *
188
     * @return int
189
     */
190 10
    public function count()
191
    {
192 10
        return count($this->storage);
193
    }
194
195
    /**
196
     * Return the current element
197
     *
198
     * @link http://php.net/manual/en/iterator.current.php
199
     * @return mixed Can return any type.
200
     * @since 5.0.0
201
     */
202 1
    public function current()
203
    {
204 1
        return $this->storage[$this->current];
205
    }
206
207
    /**
208
     * Move forward to next element
209
     *
210
     * @link http://php.net/manual/en/iterator.next.php
211
     * @return void Any returned value is ignored.
212
     * @since 5.0.0
213
     */
214 6
    public function next()
215
    {
216 6
        ++$this->current;
217 6
    }
218
219
    /**
220
     * Return the key of the current element
221
     *
222
     * @link http://php.net/manual/en/iterator.key.php
223
     * @return mixed scalar on success, or null on failure.
224
     * @since 5.0.0
225
     */
226 4
    public function key()
227
    {
228 4
        return $this->current;
229
    }
230
231
    /**
232
     * Checks if current position is valid
233
     *
234
     * @link http://php.net/manual/en/iterator.valid.php
235
     * @return boolean The return value will be casted to boolean and then evaluated.
236
     * Returns true on success or false on failure.
237
     * @since 5.0.0
238
     */
239 4
    public function valid()
240
    {
241 4
        return isset($this->storage[$this->current]);
242
    }
243
244
    /**
245
     * Rewind the Iterator to the first element
246
     *
247
     * @link http://php.net/manual/en/iterator.rewind.php
248
     * @return void Any returned value is ignored.
249
     * @since 5.0.0
250
     */
251 6
    public function rewind()
252
    {
253 6
        $this->current = 0;
254 6
    }
255
256
    /**
257
     * Whether a offset exists
258
     *
259
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
260
     * @param mixed $offset <p>
261
     * An offset to check for.
262
     * </p>
263
     * @return boolean true on success or false on failure.
264
     * </p>
265
     * <p>
266
     * The return value will be casted to boolean if non-boolean was returned.
267
     * @since 5.0.0
268
     */
269 6
    public function offsetExists($offset)
270
    {
271 6
        return isset($this->storage[$offset]);
272
    }
273
274
    /**
275
     * Offset to retrieve
276
     *
277
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
278
     * @param mixed $offset <p>
279
     * The offset to retrieve.
280
     * </p>
281
     * @return mixed Can return all value types.
282
     * @throws InvalidOffsetException
283
     * @since 5.0.0
284
     */
285 4
    public function offsetGet($offset)
286
    {
287 4
        if(!$this->offsetExists($offset))
288 4
            throw new InvalidOffsetException();
289
290 3
        return $this->storage[$offset];
291
    }
292
293
    /**
294
     * Offset to set
295
     *
296
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
297
     * @param mixed $offset <p>
298
     * The offset to assign the value to.
299
     * </p>
300
     * @param mixed $value <p>
301
     * The value to set.
302
     * </p>
303
     * @throws InvalidOffsetTypeException
304
     * @throws MaxCapacityReachedException
305
     * @throws ReadOnlyStorageException
306
     * @since 5.0.0
307
     */
308 10
    public function offsetSet($offset, $value)
309
    {
310 10
        if($this->isReadOnly())
311 10
            throw new ReadOnlyStorageException();
312
313 10
        if($this->count() === $this->getCapacity())
314 10
            throw new MaxCapacityReachedException();
315
316 10
        $this->getEventManager()->trigger('beforeAdd', $this);
317 10
        $this->storage[$offset] = $value;
318 10
        $this->getEventManager()->trigger('afterAdd', $this);
319 10
    }
320
321
    /**
322
     * Offset to unset
323
     *
324
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
325
     * @param mixed $offset <p>
326
     * The offset to unset.
327
     * </p>
328
     * @throws InvalidOffsetException
329
     * @throws ReadOnlyStorageException
330
     * @since 5.0.0
331
     */
332 3
    public function offsetUnset($offset)
333
    {
334 3
        if(!$this->offsetExists($offset))
335 3
            throw new InvalidOffsetException();
336
337 2
        if($this->isReadOnly())
338 2
            throw new ReadOnlyStorageException();
339
340 1
        unset($this->storage[$offset]);
341 1
    }
342
343
    /**
344
     * Converte o objeto para array
345
     *
346
     * @return array
347
     */
348 1
    public function toArray()
349
    {
350 1
        return $this->storage;
351
    }
352
}