Passed
Push — master ( 7af232...f59808 )
by Brent
02:35
created

OrderAdapter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
B transform() 0 26 3
A validateConfig() 0 5 3
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 transform(Page $page, $filter = null) {
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