1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Stitcher\Page\Adapter; |
4
|
|
|
|
5
|
|
|
use Stitcher\Exception\InvalidOrderAdapter; |
6
|
|
|
use Stitcher\Page\Adapter; |
7
|
|
|
use Stitcher\Configureable; |
8
|
|
|
use Stitcher\Variable\VariableParser; |
9
|
|
|
|
10
|
|
|
class OrderAdapter implements Adapter, Configureable |
11
|
|
|
{ |
12
|
|
|
private const REVERSE = [ |
13
|
|
|
'desc', |
14
|
|
|
'DESC', |
15
|
|
|
'-', |
16
|
|
|
]; |
17
|
|
|
|
18
|
|
|
/** @var \Stitcher\Variable\VariableParser */ |
19
|
|
|
private $variableParser; |
20
|
|
|
|
21
|
|
|
/** @var string */ |
22
|
|
|
private $variable; |
23
|
|
|
|
24
|
|
|
/** @var string */ |
25
|
|
|
private $field; |
26
|
|
|
|
27
|
|
|
/** @var string */ |
28
|
|
|
private $direction; |
29
|
|
|
|
30
|
|
|
public function __construct( |
31
|
|
|
array $adapterConfiguration, |
32
|
|
|
VariableParser $variableParser |
33
|
|
|
) { |
34
|
|
|
if (! $this->isValidConfiguration($adapterConfiguration)) { |
35
|
|
|
throw InvalidOrderAdapter::create(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$this->variable = $adapterConfiguration['variable']; |
39
|
|
|
$this->field = $adapterConfiguration['field']; |
40
|
|
|
$this->direction = $adapterConfiguration['direction'] ?? 'asc'; |
41
|
|
|
|
42
|
|
|
$this->variableParser = $variableParser; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public static function make( |
46
|
|
|
array $adapterConfiguration, |
47
|
|
|
VariableParser $variableParser |
48
|
|
|
): OrderAdapter { |
49
|
|
|
return new self($adapterConfiguration, $variableParser); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function transform(array $pageConfiguration): array |
53
|
|
|
{ |
54
|
|
|
$entries = $this->getEntries($pageConfiguration); |
55
|
|
|
|
56
|
|
|
$orderedEntries = $this->orderEntries($entries); |
57
|
|
|
|
58
|
|
|
$pageConfiguration['variables'][$this->variable] = $orderedEntries; |
59
|
|
|
|
60
|
|
|
unset($pageConfiguration['config']['order']); |
61
|
|
|
|
62
|
|
|
return [$pageConfiguration]; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function isValidConfiguration($subject): bool |
66
|
|
|
{ |
67
|
|
|
return \is_array($subject) |
68
|
|
|
&& isset($subject['variable']) |
69
|
|
|
&& isset($subject['field']); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function getEntries($pageConfiguration): ?array |
73
|
|
|
{ |
74
|
|
|
$variable = $pageConfiguration['variables'][$this->variable] ?? null; |
75
|
|
|
|
76
|
|
|
return $this->variableParser->parse($variable) ?? $variable; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
private function orderEntries(array $entries): array |
80
|
|
|
{ |
81
|
|
|
uasort($entries, function ($a, $b) { |
82
|
|
|
return strcmp($a[$this->field] ?? '', $b[$this->field] ?? ''); |
83
|
|
|
}); |
84
|
|
|
|
85
|
|
|
if (!in_array($this->direction, self::REVERSE)) { |
86
|
|
|
$entries = array_reverse($entries, true); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
return $entries; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|