forked from ILIAS-eLearning/ILIAS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Order.php
67 lines (57 loc) · 1.59 KB
/
Order.php
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
<?php
declare(strict_types=1);
namespace ILIAS\Data;
/**
* Both the subject and the direction need to be specified when expressing an order.
*
* @author Nils Haagen <[email protected]>
*/
class Order
{
public const ASC = 'ASC';
public const DESC = 'DESC';
/**
* @var array<string, string>
*/
protected array $order = [];
public function __construct(string $subject, string $direction)
{
$this->checkDirection($direction);
$this->order[$subject] = $direction;
}
protected function checkSubject(string $subject): void
{
if (array_key_exists($subject, $this->order)) {
throw new \InvalidArgumentException("already sorted by subject '$subject'", 1);
}
}
protected function checkDirection(string $direction): void
{
if ($direction !== self::ASC && $direction !== self::DESC) {
throw new \InvalidArgumentException("Direction bust be Order::ASC or Order::DESC.", 1);
}
}
public function append(string $subject, string $direction): Order
{
$this->checkSubject($subject);
$this->checkDirection($direction);
$clone = clone $this;
$clone->order[$subject] = $direction;
return $clone;
}
/**
* @return array<string, string>
*/
public function get(): array
{
return $this->order;
}
public function join($init, callable $fn)
{
$ret = $init;
foreach ($this->order as $key => $value) {
$ret = $fn($ret, $key, $value);
}
return $ret;
}
}