Passed
Branch master (69397d)
by Chris
07:22
created

AbstractArrayDriver::collect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace WebTheory\Collection\Access\Abstracts;
4
5
use WebTheory\Collection\Contracts\ArrayDriverInterface;
6
use WebTheory\Collection\Contracts\ObjectComparatorInterface;
7
8
abstract class AbstractArrayDriver implements ArrayDriverInterface
9
{
10
    protected ObjectComparatorInterface $objectComparator;
11
12 309
    public function __construct(ObjectComparatorInterface $objectComparator)
13
    {
14 309
        $this->objectComparator = $objectComparator;
15
    }
16
17 69
    public function fetch(array $array, $item)
18
    {
19 69
        return $array[$item];
20
    }
21
22 309
    public function collect(array &$array, array $items): void
23
    {
24 309
        foreach ($items as $offset => $item) {
25 309
            $this->insert($array, $item, $offset);
26
        }
27
    }
28
29 9
    public function remove(array &$array, $item): bool
30
    {
31 9
        return is_object($item)
32 6
            ? $this->deleteObjectIfLocated($array, $item)
33 9
            : $this->maybeRemoveItem($array, $item);
34
    }
35
36 24
    public function contains(array $array, $item): bool
37
    {
38 24
        return is_object($item)
39 6
            ? $this->arrayContainsObject($array, $item)
40 24
            : $this->arrayContains($array, $item);
41
    }
42
43 3
    protected function maybeRemoveItem(array &$array, $item): bool
44
    {
45 3
        if (isset($array[$item])) {
46 3
            unset($array[$item]);
47
48 3
            return true;
49
        }
50
51
        return false;
52
    }
53
54 12
    protected function arrayContains(array $array, $item): bool
55
    {
56 12
        return isset($array[$item]);
57
    }
58
59 309
    protected function arrayContainsObject(array $array, object $object): bool
60
    {
61 309
        foreach ($array as $item) {
62 309
            if ($this->objectComparator->matches($item, $object)) {
63 10
                return true;
64
            }
65
        }
66
67 309
        return false;
68
    }
69
70 6
    protected function deleteObjectIfLocated(array &$array, object $object): bool
71
    {
72 6
        $position = array_search($object, $array, true);
73
74 6
        if ($position === false) {
75
            return false;
76
        }
77
78 6
        unset($array[$position]);
79
80 6
        return true;
81
    }
82
}
83