Debian Codegraph @

vendor/ramsey/collection/src/AbstractCollection.php

raw
1 <?php
2
3 /**
4 * This file is part of the ramsey/collection library
5 *
6 * For the full copyright and license information, please view the LICENSE
7 * file that was distributed with this source code.
8 *
9 * @copyright Copyright (c) Ben Ramsey <[email protected]>
10 * @license http://opensource.org/licenses/MIT MIT
11 */
12
13 declare(strict_types=1);
14
15 namespace Ramsey\Collection;
16
17 use Closure;
18 use Ramsey\Collection\Exception\CollectionMismatchException;
19 use Ramsey\Collection\Exception\InvalidArgumentException;
20 use Ramsey\Collection\Exception\InvalidPropertyOrMethod;
21 use Ramsey\Collection\Exception\NoSuchElementException;
22 use Ramsey\Collection\Exception\UnsupportedOperationException;
23 use Ramsey\Collection\Tool\TypeTrait;
24 use Ramsey\Collection\Tool\ValueExtractorTrait;
25 use Ramsey\Collection\Tool\ValueToStringTrait;
26
27 use function array_filter;
28 use function array_key_first;
29 use function array_key_last;
30 use function array_map;
31 use function array_merge;
32 use function array_reduce;
33 use function array_search;
34 use function array_udiff;
35 use function array_uintersect;
36 use function in_array;
37 use function is_int;
38 use function is_object;
39 use function spl_object_id;
40 use function sprintf;
41 use function usort;
42
43 /**
44 * This class provides a basic implementation of `CollectionInterface`, to
45 * minimize the effort required to implement this interface
46 *
47 * @template T
48 * @extends AbstractArray<T>
49 * @implements CollectionInterface<T>
50 */
51 abstract class AbstractCollection extends AbstractArray implements CollectionInterface
52 {
53 use TypeTrait;
54 use ValueToStringTrait;
55 use ValueExtractorTrait;
56
57 /**
58 * @throws InvalidArgumentException if $element is of the wrong type.
59 */
60 public function add(mixed $element): bool
61 {
62 $this[] = $element;
63
64 return true;
65 }
66
67 public function contains(mixed $element, bool $strict = true): bool
68 {
69 return in_array($element, $this->data, $strict);
70 }
71
72 /**
73 * @throws InvalidArgumentException if $element is of the wrong type.
74 */
75 public function offsetSet(mixed $offset, mixed $value): void
76 {
77 if ($this->checkType($this->getType(), $value) === false) {
78 throw new InvalidArgumentException(
79 'Value must be of type ' . $this->getType() . '; value is '
80 . $this->toolValueToString($value),
81 );
82 }
83
84 if ($offset === null) {
85 $this->data[] = $value;
86 } else {
87 $this->data[$offset] = $value;
88 }
89 }
90
91 public function remove(mixed $element): bool
92 {
93 if (($position = array_search($element, $this->data, true)) !== false) {
94 unset($this[$position]);
95
96 return true;
97 }
98
99 return false;
100 }
101
102 /**
103 * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist
104 * on the elements in this collection.
105 * @throws UnsupportedOperationException if unable to call column() on this
106 * collection.
107 *
108 * @inheritDoc
109 */
110 public function column(string $propertyOrMethod): array
111 {
112 $temp = [];
113
114 foreach ($this->data as $item) {
115 $temp[] = $this->extractValue($item, $propertyOrMethod);
116 }
117
118 return $temp;
119 }
120
121 /**
122 * @return T
123 *
124 * @throws NoSuchElementException if this collection is empty.
125 */
126 public function first(): mixed
127 {
128 $firstIndex = array_key_first($this->data);
129
130 if ($firstIndex === null) {
131 throw new NoSuchElementException('Can\'t determine first item. Collection is empty');
132 }
133
134 return $this->data[$firstIndex];
135 }
136
137 /**
138 * @return T
139 *
140 * @throws NoSuchElementException if this collection is empty.
141 */
142 public function last(): mixed
143 {
144 $lastIndex = array_key_last($this->data);
145
146 if ($lastIndex === null) {
147 throw new NoSuchElementException('Can\'t determine last item. Collection is empty');
148 }
149
150 return $this->data[$lastIndex];
151 }
152
153 /**
154 * @return CollectionInterface<T>
155 *
156 * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist
157 * on the elements in this collection.
158 * @throws UnsupportedOperationException if unable to call sort() on this
159 * collection.
160 */
161 public function sort(?string $propertyOrMethod = null, Sort $order = Sort::Ascending): CollectionInterface
162 {
163 $collection = clone $this;
164
165 usort(
166 $collection->data,
167 function (mixed $a, mixed $b) use ($propertyOrMethod, $order): int {
168 $aValue = $this->extractValue($a, $propertyOrMethod);
169 $bValue = $this->extractValue($b, $propertyOrMethod);
170
171 return ($aValue <=> $bValue) * ($order === Sort::Descending ? -1 : 1);
172 },
173 );
174
175 return $collection;
176 }
177
178 /**
179 * @param callable(T): bool $callback A callable to use for filtering elements.
180 *
181 * @return CollectionInterface<T>
182 */
183 public function filter(callable $callback): CollectionInterface
184 {
185 $collection = clone $this;
186 $collection->data = array_merge([], array_filter($collection->data, $callback));
187
188 return $collection;
189 }
190
191 /**
192 * @return CollectionInterface<T>
193 *
194 * @throws InvalidPropertyOrMethod if the $propertyOrMethod does not exist
195 * on the elements in this collection.
196 * @throws UnsupportedOperationException if unable to call where() on this
197 * collection.
198 */
199 public function where(?string $propertyOrMethod, mixed $value): CollectionInterface
200 {
201 return $this->filter(
202 fn (mixed $item): bool => $this->extractValue($item, $propertyOrMethod) === $value,
203 );
204 }
205
206 /**
207 * @param callable(T): TCallbackReturn $callback A callable to apply to each
208 * item of the collection.
209 *
210 * @return CollectionInterface<TCallbackReturn>
211 *
212 * @template TCallbackReturn
213 */
214 public function map(callable $callback): CollectionInterface
215 {
216 return new Collection('mixed', array_map($callback, $this->data));
217 }
218
219 /**
220 * @param callable(TCarry, T): TCarry $callback A callable to apply to each
221 * item of the collection to reduce it to a single value.
222 * @param TCarry $initial This is the initial value provided to the callback.
223 *
224 * @return TCarry
225 *
226 * @template TCarry
227 */
228 public function reduce(callable $callback, mixed $initial): mixed
229 {
230 return array_reduce($this->data, $callback, $initial);
231 }
232
233 /**
234 * @param CollectionInterface<T> $other The collection to check for divergent
235 * items.
236 *
237 * @return CollectionInterface<T>
238 *
239 * @throws CollectionMismatchException if the compared collections are of
240 * differing types.
241 */
242 public function diff(CollectionInterface $other): CollectionInterface
243 {
244 $this->compareCollectionTypes($other);
245
246 $diffAtoB = array_udiff($this->data, $other->toArray(), $this->getComparator());
247 $diffBtoA = array_udiff($other->toArray(), $this->data, $this->getComparator());
248
249 $collection = clone $this;
250 $collection->data = array_merge($diffAtoB, $diffBtoA);
251
252 return $collection;
253 }
254
255 /**
256 * @param CollectionInterface<T> $other The collection to check for
257 * intersecting items.
258 *
259 * @return CollectionInterface<T>
260 *
261 * @throws CollectionMismatchException if the compared collections are of
262 * differing types.
263 */
264 public function intersect(CollectionInterface $other): CollectionInterface
265 {
266 $this->compareCollectionTypes($other);
267
268 $collection = clone $this;
269 $collection->data = array_uintersect($this->data, $other->toArray(), $this->getComparator());
270
271 return $collection;
272 }
273
274 /**
275 * @param CollectionInterface<T> ...$collections The collections to merge.
276 *
277 * @return CollectionInterface<T>
278 *
279 * @throws CollectionMismatchException if unable to merge any of the given
280 * collections or items within the given collections due to type
281 * mismatch errors.
282 */
283 public function merge(CollectionInterface ...$collections): CollectionInterface
284 {
285 $mergedCollection = clone $this;
286
287 foreach ($collections as $index => $collection) {
288 if (!$collection instanceof static) {
289 throw new CollectionMismatchException(
290 sprintf('Collection with index %d must be of type %s', $index, static::class),
291 );
292 }
293
294 // When using generics (Collection.php, Set.php, etc),
295 // we also need to make sure that the internal types match each other
296 if ($this->getUniformType($collection) !== $this->getUniformType($this)) {
297 throw new CollectionMismatchException(
298 sprintf(
299 'Collection items in collection with index %d must be of type %s',
300 $index,
301 $this->getType(),
302 ),
303 );
304 }
305
306 foreach ($collection as $key => $value) {
307 if (is_int($key)) {
308 $mergedCollection[] = $value;
309 } else {
310 $mergedCollection[$key] = $value;
311 }
312 }
313 }
314
315 return $mergedCollection;
316 }
317
318 /**
319 * @param CollectionInterface<T> $other
320 *
321 * @throws CollectionMismatchException
322 */
323 private function compareCollectionTypes(CollectionInterface $other): void
324 {
325 if (!$other instanceof static) {
326 throw new CollectionMismatchException('Collection must be of type ' . static::class);
327 }
328
329 // When using generics (Collection.php, Set.php, etc),
330 // we also need to make sure that the internal types match each other
331 if ($this->getUniformType($other) !== $this->getUniformType($this)) {
332 throw new CollectionMismatchException('Collection items must be of type ' . $this->getType());
333 }
334 }
335
336 private function getComparator(): Closure
337 {
338 return function (mixed $a, mixed $b): int {
339 // If the two values are object, we convert them to unique scalars.
340 // If the collection contains mixed values (unlikely) where some are objects
341 // and some are not, we leave them as they are.
342 // The comparator should still work and the result of $a < $b should
343 // be consistent but unpredictable since not documented.
344 if (is_object($a) && is_object($b)) {
345 $a = spl_object_id($a);
346 $b = spl_object_id($b);
347 }
348
349 return $a === $b ? 0 : ($a < $b ? 1 : -1);
350 };
351 }
352
353 /**
354 * @param CollectionInterface<mixed> $collection
355 */
356 private function getUniformType(CollectionInterface $collection): string
357 {
358 return match ($collection->getType()) {
359 'integer' => 'int',
360 'boolean' => 'bool',
361 'double' => 'float',
362 default => $collection->getType(),
363 };
364 }
365 }