Passed
Push — master ( f4d5f9...dfd0e0 )
by Alexander
01:26
created

ArrayAccessTrait::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 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 1
    public function getIterator(): \ArrayIterator
24
    {
25 1
        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 1
    public function count(): int
34
    {
35 1
        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 1
    public function offsetExists($offset): bool
44
    {
45 1
        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 1
    public function offsetGet($offset)
54
    {
55 1
        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 1
    public function offsetSet($offset, $value): void
64
    {
65 1
        $this->data[$offset] = $value;
66 1
    }
67
68
    /**
69
     * This method is required by the interface {@see \ArrayAccess}.
70
     * @param mixed $offset the offset to unset element
71
     */
72 1
    public function offsetUnset($offset): void
73
    {
74 1
        unset($this->data[$offset]);
75 1
    }
76
}
77