-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathSort.php
More file actions
90 lines (79 loc) · 3.23 KB
/
Copy pathSort.php
File metadata and controls
90 lines (79 loc) · 3.23 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
namespace loophp\collection\Operation;
use Closure;
use Exception;
use Generator;
use loophp\collection\Contract\Operation;
use loophp\iterators\SortIterableAggregate;
/**
* @immutable
*
* @template TKey
* @template T
*/
final class Sort extends AbstractOperation
{
/**
* @return Closure(int): Closure(null|(Closure(T, T, TKey, TKey): int)): Closure(iterable<TKey, T>): Generator<TKey, T>
*/
public function __invoke(): Closure
{
return
/**
* @return Closure(null|Closure(T, T, TKey, TKey): int): Closure(iterable<TKey, T>): Generator<TKey, T>
*/
static fn (int $type = Operation\Sortable::BY_VALUES): Closure =>
/**
* @param null|(Closure(T, T, TKey, TKey): int)|(callable(T, T, TKey, TKey): int) $callback
*
* @return Closure(iterable<TKey, T>): Generator<TKey, T>
*/
static function (null|callable|Closure $callback = null) use ($type): Closure {
if (Operation\Sortable::BY_VALUES !== $type && Operation\Sortable::BY_KEYS !== $type) {
throw new Exception('Invalid sort type.');
}
$callback ??=
/**
* @param T $left
* @param T $right
* @param TKey $leftKey
* @param TKey $rightKey
*/
static fn (mixed $left, mixed $right, mixed $leftKey, mixed $rightKey): int => $left <=> $right;
if (!($callback instanceof Closure)) {
trigger_deprecation(
'loophp/collection',
'7.4',
'Passing a callable as argument is deprecated and will be removed in 8.0. Use a closure instead.',
self::class
);
$callback = Closure::fromCallable($callback);
}
$operations = Operation\Sortable::BY_VALUES === $type ?
[
'before' => [],
'after' => [],
] :
[
'before' => [(new Flip())()],
'after' => [(new Flip())()],
];
$sortedIterator =
/**
* @param iterable<TKey, T> $iterable
*
* @return SortIterableAggregate<TKey, T>
*/
static fn (iterable $iterable): SortIterableAggregate => new SortIterableAggregate($iterable, $callback);
/** @var Closure(iterable<TKey, T>): Generator<TKey, T> $sort */
$sort = (new Pipe())()(
...$operations['before'],
...[$sortedIterator],
...$operations['after']
);
// Point free style.
return $sort;
};
}
}