1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebTheory\Collection\Driver\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
|
129 |
|
public function __construct(ObjectComparatorInterface $objectComparator) |
13
|
|
|
{ |
14
|
129 |
|
$this->objectComparator = $objectComparator; |
15
|
|
|
} |
16
|
|
|
|
17
|
306 |
|
public function insert(array &$array, object $item, $offset = null): bool |
18
|
|
|
{ |
19
|
306 |
|
if ($this->arrayContainsObject($array, $item)) { |
20
|
12 |
|
return false; |
21
|
|
|
} |
22
|
|
|
|
23
|
306 |
|
$this->insertItem($array, $item, $offset); |
24
|
|
|
|
25
|
306 |
|
return true; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function fetch(array $array, $item) |
29
|
|
|
{ |
30
|
|
|
return $array[$item]; |
31
|
|
|
} |
32
|
|
|
|
33
|
9 |
|
public function remove(array &$array, $item): bool |
34
|
|
|
{ |
35
|
9 |
|
return is_object($item) |
36
|
6 |
|
? $this->deleteObjectIfLocated($array, $item) |
37
|
9 |
|
: $this->maybeRemoveItem($array, $item); |
38
|
|
|
} |
39
|
|
|
|
40
|
24 |
|
public function contains(array $array, $item): bool |
41
|
|
|
{ |
42
|
24 |
|
return is_object($item) |
43
|
6 |
|
? $this->arrayContainsObject($array, $item) |
44
|
24 |
|
: $this->arrayContains($array, $item); |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
protected function maybeRemoveItem(array &$array, $item): bool |
48
|
|
|
{ |
49
|
3 |
|
if (isset($array[$item])) { |
50
|
3 |
|
unset($array[$item]); |
51
|
|
|
|
52
|
3 |
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return false; |
56
|
|
|
} |
57
|
|
|
|
58
|
12 |
|
protected function arrayContains(array $array, $item): bool |
59
|
|
|
{ |
60
|
12 |
|
return isset($array[$item]); |
61
|
|
|
} |
62
|
|
|
|
63
|
306 |
|
protected function arrayContainsObject(array $array, object $object): bool |
64
|
|
|
{ |
65
|
306 |
|
foreach ($array as $item) { |
66
|
306 |
|
if ($this->objectComparator->matches($item, $object)) { |
67
|
15 |
|
return true; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
306 |
|
return false; |
72
|
|
|
} |
73
|
|
|
|
74
|
6 |
|
protected function deleteObjectIfLocated(array &$array, object $object): bool |
75
|
|
|
{ |
76
|
6 |
|
$position = array_search($object, $array, true); |
77
|
|
|
|
78
|
6 |
|
if ($position === false) { |
79
|
|
|
return false; |
80
|
|
|
} |
81
|
|
|
|
82
|
6 |
|
unset($array[$position]); |
83
|
|
|
|
84
|
6 |
|
return true; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
abstract protected function insertItem(array &$array, object $item, $offset = null): void; |
88
|
|
|
} |
89
|
|
|
|