|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Brendt\Stitcher\Adapter; |
|
4
|
|
|
|
|
5
|
|
|
use Brendt\Stitcher\Exception\ConfigurationException; |
|
6
|
|
|
use Brendt\Stitcher\Factory\AdapterFactory; |
|
7
|
|
|
use Brendt\Stitcher\Site\Page; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Order a collection of variables by a specified field. |
|
11
|
|
|
* |
|
12
|
|
|
* Sample configuration: |
|
13
|
|
|
* |
|
14
|
|
|
* /examples: |
|
15
|
|
|
* template: examples/detail |
|
16
|
|
|
* data: |
|
17
|
|
|
* example: collection.yml |
|
18
|
|
|
* adapters: |
|
19
|
|
|
* order: |
|
20
|
|
|
* variable: example |
|
21
|
|
|
* field: id |
|
22
|
|
|
* direction: desc |
|
23
|
|
|
*/ |
|
24
|
|
|
class OrderAdapter extends AbstractAdapter |
|
25
|
|
|
{ |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* A collection of keywords which would reverse the data set. |
|
29
|
|
|
* |
|
30
|
|
|
* @var array |
|
31
|
|
|
*/ |
|
32
|
|
|
private static $reverse = [ |
|
33
|
|
|
'desc', |
|
34
|
|
|
'DESC', |
|
35
|
|
|
'-', |
|
36
|
|
|
]; |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param Page $page |
|
40
|
|
|
* @param string|null $filter |
|
41
|
|
|
* |
|
42
|
|
|
* @return Page[] |
|
43
|
|
|
*/ |
|
44
|
|
|
public function transformPage(Page $page, $filter = null) : array { |
|
45
|
|
|
$config = $page->getAdapterConfig(AdapterFactory::ORDER_ADAPTER); |
|
46
|
|
|
|
|
47
|
|
|
$this->validateConfig($config); |
|
48
|
|
|
$variable = $config['variable']; |
|
49
|
|
|
$field = $config['field']; |
|
50
|
|
|
$direction = isset($config['direction']) ? $config['direction'] : null; |
|
51
|
|
|
|
|
52
|
|
|
$entries = $this->getData($page->getVariable($variable)); |
|
53
|
|
|
|
|
54
|
|
|
uasort($entries, function ($a, $b) use ($field) { |
|
55
|
|
|
return strcmp($a[$field], $b[$field]); |
|
56
|
|
|
}); |
|
57
|
|
|
|
|
58
|
|
|
if (in_array($direction, self::$reverse)) { |
|
59
|
|
|
$entries = array_reverse($entries, true); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
$page->setVariableValue($variable, $entries) |
|
63
|
|
|
->setVariableIsParsed($variable); |
|
64
|
|
|
|
|
65
|
|
|
/** @var Page[] $result */ |
|
66
|
|
|
$result = [$page->getId() => $page]; |
|
67
|
|
|
|
|
68
|
|
|
return $result; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param array $config |
|
73
|
|
|
* |
|
74
|
|
|
* @throws ConfigurationException |
|
75
|
|
|
*/ |
|
76
|
|
|
private function validateConfig(array $config) { |
|
77
|
|
|
if (!isset($config['variable']) || !isset($config['field'])) { |
|
78
|
|
|
throw new ConfigurationException('Both the configuration entry `field` and `variable` are required when using the Order adapter.'); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|