Passed
Pull Request — master (#47)
by Alexander
01:24
created

ArrayAccessTrait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
eloc 7
dl 0
loc 60
ccs 0
cts 12
cp 0
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getIterator() 0 3 1
A offsetUnset() 0 3 1
A count() 0 3 1
A offsetGet() 0 3 1
A offsetExists() 0 3 1
A offsetSet() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Arrays;
6
7
/**
8
 * ArrayAccessTrait provides the implementation for {@see \IteratorAggregate}, {@see \ArrayAccess} and {@see \Countable}.
9
 *
10
 * Note that ArrayAccessTrait requires the class using it contain a property named `data` which should be an array.
11
 * The data will be exposed by ArrayAccessTrait to support accessing the class object like an array.
12
 *
13
 * @property array $data
14
 */
15
trait ArrayAccessTrait
16
{
17
    /**
18
     * Returns an iterator for traversing the data.
19
     * This method is required by the SPL interface {@see \IteratorAggregate}.
20
     * It will be implicitly called when you use `foreach` to traverse the collection.
21
     * @return \ArrayIterator an iterator for traversing the cookies in the collection.
22
     */
23
    public function getIterator(): \ArrayIterator
24
    {
25
        return new \ArrayIterator($this->data);
26
    }
27
28
    /**
29
     * Returns the number of data items.
30
     * This method is required by Countable interface.
31
     * @return int number of data elements.
32
     */
33
    public function count(): int
34
    {
35
        return count($this->data);
36
    }
37
38
    /**
39
     * This method is required by the interface {@see \ArrayAccess}.
40
     * @param mixed $offset the offset to check on
41
     * @return bool
42
     */
43
    public function offsetExists($offset): bool
44
    {
45
        return isset($this->data[$offset]);
46
    }
47
48
    /**
49
     * This method is required by the interface {@see \ArrayAccess}.
50
     * @param mixed $offset the offset to retrieve element.
51
     * @return mixed the element at the offset, null if no element is found at the offset
52
     */
53
    public function offsetGet($offset)
54
    {
55
        return $this->data[$offset] ?? null;
56
    }
57
58
    /**
59
     * This method is required by the interface {@see \ArrayAccess}.
60
     * @param mixed $offset the offset to set element
61
     * @param mixed $value the element value
62
     */
63
    public function offsetSet($offset, $value): void
64
    {
65
        $this->data[$offset] = $value;
66
    }
67
68
    /**
69
     * This method is required by the interface {@see \ArrayAccess}.
70
     * @param mixed $offset the offset to unset element
71
     */
72
    public function offsetUnset($offset): void
73
    {
74
        unset($this->data[$offset]);
75
    }
76
}
77