-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.php
More file actions
53 lines (42 loc) · 1.68 KB
/
Sort.php
File metadata and controls
53 lines (42 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
declare(strict_types=1);
namespace TinyBlocks\Collection\Internal\Operations\Order;
use Closure;
use Generator;
use TinyBlocks\Collection\Internal\Operations\LazyOperation;
use TinyBlocks\Collection\Order;
final readonly class Sort implements LazyOperation
{
private function __construct(private Order $order, private ?Closure $predicate)
{
}
public static function from(Order $order, ?Closure $predicate = null): Sort
{
return new Sort(order: $order, predicate: $predicate);
}
public function apply(iterable $elements): Generator
{
$temporaryElements = is_array($elements) ? $elements : [];
if (!is_array($elements)) {
foreach ($elements as $key => $value) {
$temporaryElements[$key] = $value;
}
}
$predicate = is_null($this->predicate)
? static fn(mixed $first, mixed $second): int => $first <=> $second
: $this->predicate;
$ascendingPredicate = static fn(mixed $first, mixed $second): int => $predicate($first, $second);
$descendingPredicate = is_null($this->predicate)
? static fn(mixed $first, mixed $second): int => $predicate($second, $first)
: $predicate;
match ($this->order) {
Order::ASCENDING_KEY => ksort($temporaryElements),
Order::DESCENDING_KEY => krsort($temporaryElements),
Order::ASCENDING_VALUE => uasort($temporaryElements, $ascendingPredicate),
Order::DESCENDING_VALUE => uasort($temporaryElements, $descendingPredicate)
};
foreach ($temporaryElements as $key => $value) {
yield $key => $value;
}
}
}