Passed
Push — master ( 9e4977...ad78b7 )
by Brent
02:46
created

CollectionAdapter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 10
c 0
b 0
f 0
wmc 9
lcom 0
cbo 4

1 Method

Rating   Name   Duplication   Size   Complexity  
D transform() 0 44 9
1
<?php
2
3
namespace brendt\stitcher\adapter;
4
5
use brendt\stitcher\element\Page;
6
use brendt\stitcher\exception\IdFieldNotFoundException;
7
use brendt\stitcher\exception\VariableNotFoundException;
8
use brendt\stitcher\factory\AdapterFactory;
9
10
class CollectionAdapter extends AbstractAdapter {
11
12
    /**
13
     * @param Page  $page
14
     * @param mixed $filter
15
     *
16
     * @return \brendt\stitcher\element\Page[]
17
     * @throws IdFieldNotFoundException
18
     * @throws VariableNotFoundException
19
     */
20
    public function transform(Page $page, $filter = null) {
21
        $config = $page->getAdapter(AdapterFactory::COLLECTION_ADAPTER);
22
23
        if (!isset($config['field']) || !isset($config['variable'])) {
24
            return [$page];
25
        }
26
27
        $variable = $config['variable'];
28
29
        if (!$source = $page->getVariable($variable)) {
30
            throw new VariableNotFoundException("Variable \"{$variable}\" was not set as a data variable for page \"{$page->getId()}\"");
31
        }
32
33
        $pageId = $page->getId();
34
        $entries = $this->getData($source);
35
        $field = $config['field'];
36
37
        if (strpos($pageId, '{' . $field . '}') === false) {
38
            throw new IdFieldNotFoundException("The field \"{{$field}}\" was not found in the URL \"{$page->getId()}\"");
39
        }
40
41
        $result = [];
42
43
        foreach ($entries as $entry) {
44
            if (!isset($entry[$field]) || ($filter && $entry[$field] !== $filter)) {
45
                continue;
46
            }
47
48
            $fieldValue = $entry[$field];
49
50
            $url = str_replace('{' . $field . '}', $fieldValue, $pageId);
51
            $entryPage = clone $page;
52
53
            $entryPage
54
                ->clearAdapter(AdapterFactory::COLLECTION_ADAPTER)
55
                ->setVariable($variable, $entry)
56
                ->setParsedField($variable)
57
                ->setId($url);
58
59
            $result[$url] = $entryPage;
60
        }
61
62
        return $result;
63
    }
64
65
}
66