1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace WebTheory\Collection\Driver; |
4
|
|
|
|
5
|
|
|
use WebTheory\Collection\Contracts\ArrayDriverInterface; |
6
|
|
|
use WebTheory\Collection\Contracts\CollectionQueryInterface; |
7
|
|
|
use WebTheory\Collection\Contracts\ObjectComparatorInterface; |
8
|
|
|
use WebTheory\Collection\Contracts\PropertyResolverInterface; |
9
|
|
|
use WebTheory\Collection\Driver\Abstracts\AbstractArrayDriver; |
10
|
|
|
use WebTheory\Collection\Query\BasicQuery; |
11
|
|
|
use WebTheory\Collection\Resolution\Abstracts\ResolvesPropertyValueTrait; |
12
|
|
|
|
13
|
|
|
class IdentifiableItemList extends AbstractArrayDriver implements ArrayDriverInterface |
14
|
|
|
{ |
15
|
|
|
use ResolvesPropertyValueTrait; |
16
|
|
|
|
17
|
219 |
|
public function __construct( |
18
|
|
|
string $property, |
19
|
|
|
PropertyResolverInterface $propertyResolver, |
20
|
|
|
ObjectComparatorInterface $objectComparator |
21
|
|
|
) { |
22
|
219 |
|
$this->property = $property; |
23
|
219 |
|
$this->propertyResolver = $propertyResolver; |
24
|
|
|
|
25
|
219 |
|
parent::__construct($objectComparator); |
26
|
|
|
} |
27
|
|
|
|
28
|
219 |
|
public function insert(array &$array, object $item, $locator = null): bool |
29
|
|
|
{ |
30
|
219 |
|
if ($this->arrayContainsObject($array, $item)) { |
31
|
3 |
|
return false; |
32
|
|
|
} |
33
|
|
|
|
34
|
219 |
|
$array[] = $item; |
35
|
|
|
|
36
|
219 |
|
return true; |
37
|
|
|
} |
38
|
|
|
|
39
|
3 |
|
public function remove(array &$array, $item): bool |
40
|
|
|
{ |
41
|
3 |
|
if (is_object($item)) { |
42
|
3 |
|
return $this->deleteObjectIfLocated($array, $item); |
43
|
|
|
} |
44
|
|
|
|
45
|
3 |
|
if ($item = $this->getFirstMatchingItem($array, $item)) { |
46
|
3 |
|
return $this->remove($array, $item); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return false; |
50
|
|
|
} |
51
|
|
|
|
52
|
6 |
|
public function contains(array $array, $item): bool |
53
|
|
|
{ |
54
|
6 |
|
if (is_object($item)) { |
55
|
|
|
return $this->arrayContainsObject($array, $item); |
56
|
|
|
} |
57
|
|
|
|
58
|
6 |
|
return !empty($this->getMatchingItems($array, $item)); |
59
|
|
|
} |
60
|
|
|
|
61
|
9 |
|
protected function getMatchingItems(array $array, $item): array |
62
|
|
|
{ |
63
|
9 |
|
return $this->getQuery($this->property, '=', $item)->query($array); |
64
|
|
|
} |
65
|
|
|
|
66
|
3 |
|
protected function getFirstMatchingItem(array $array, $item): ?object |
67
|
|
|
{ |
68
|
3 |
|
return $this->getMatchingItems($array, $item)[0] ?? null; |
69
|
|
|
} |
70
|
|
|
|
71
|
9 |
|
protected function getQuery(string $property, string $operator, $value): CollectionQueryInterface |
72
|
|
|
{ |
73
|
9 |
|
return new BasicQuery( |
74
|
9 |
|
$this->propertyResolver, |
75
|
|
|
$property, |
76
|
|
|
$operator, |
77
|
|
|
$value, |
78
|
|
|
); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|