Test Failed
Push — master ( a58c94...1bcec0 )
by Brent
03:26
created

CollectionAdapter::transform()   D

Complexity

Conditions 9
Paths 6

Size

Total Lines 44
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 26
nc 6
nop 2
dl 0
loc 44
rs 4.909
c 0
b 0
f 0
1
<?php
2
3
namespace Brendt\Stitcher\Adapter;
4
5
use Brendt\Stitcher\Exception\IdFieldNotFoundException;
6
use Brendt\Stitcher\Exception\VariableNotFoundException;
7
use Brendt\Stitcher\Factory\AdapterFactory;
8
use Brendt\Stitcher\Site\Page;
9
10
/**
11
 * The CollectionAdapter takes a page with a collection of entries, and generates a detail page for each entry in the
12
 * collection.
13
 *
14
 * Sample configuration:
15
 *
16
 *  /examples/{id}:
17
 *      template: examples/detail
18
 *      data:
19
 *          example: collection.yml
20
 *      adapters:
21
 *          collection:
22
 *              variable: example
23
 *              field: id
24
 *
25
 * @todo Rename `field` option to `urlVariable`
26
 */
27
class CollectionAdapter extends AbstractAdapter {
28
29
    /**
30
     * @param Page  $page
31
     * @param mixed $filter
32
     *
33
     * @return Page[]
34
     * @throws IdFieldNotFoundException
35
     * @throws VariableNotFoundException
36
     */
37
    public function transform(Page $page, $filter = null) {
38
        $config = $page->getAdapterConfig(AdapterFactory::COLLECTION_ADAPTER);
39
40
        if (!isset($config['field']) || !isset($config['variable'])) {
41
            return [$page];
42
        }
43
44
        $variable = $config['variable'];
45
46
        if (!$source = $page->getVariable($variable)) {
47
            throw new VariableNotFoundException("Variable \"{$variable}\" was not set as a data variable for page \"{$page->getId()}\"");
48
        }
49
50
        $pageId = $page->getId();
51
        $entries = $this->getData($source);
52
        $field = $config['field'];
53
54
        if (strpos($pageId, '{' . $field . '}') === false) {
55
            throw new IdFieldNotFoundException("The field \"{{$field}}\" was not found in the URL \"{$page->getId()}\"");
56
        }
57
58
        $result = [];
59
60
        foreach ($entries as $entry) {
61
            if (!isset($entry[$field]) || ($filter && $entry[$field] !== $filter)) {
62
                continue;
63
            }
64
65
            $fieldValue = $entry[$field];
66
67
            $url = str_replace('{' . $field . '}', $fieldValue, $pageId);
68
            $entryPage = clone $page;
69
70
            $entryPage
71
                ->removeAdapter(AdapterFactory::COLLECTION_ADAPTER)
72
                ->setVariableValue($variable, $entry)
73
                ->setVariableIsParsed($variable)
74
                ->setId($url);
75
76
            $result[$url] = $entryPage;
77
        }
78
79
        return $result;
80
    }
81
82
}
83