Completed
Push — master ( a6c8f9...b97be3 )
by Vladimir
03:52 queued 19s
created

PageManager::parsePageViews()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.0879

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 14
cts 17
cp 0.8235
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 12
nc 6
nop 1
crap 4.0879
1
<?php
2
3
/**
4
 * @copyright 2017 Vladimir Jimenez
5
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
6
 */
7
8
namespace allejo\stakx\Manager;
9
10
use allejo\stakx\Configuration;
11
use allejo\stakx\Document\BasePageView;
12
use allejo\stakx\Document\ContentItem;
13
use allejo\stakx\Document\DataItem;
14
use allejo\stakx\Document\DynamicPageView;
15
use allejo\stakx\Document\JailedDocument;
16
use allejo\stakx\Document\StaticPageView;
17
use allejo\stakx\Filesystem\FilesystemLoader as fs;
18
use allejo\stakx\Event\PageViewsCompleted;
19
use allejo\stakx\Exception\CollectionNotFoundException;
20
use allejo\stakx\Filesystem\FileExplorer;
21
22
/**
23
 * This class is responsible for handling all of the PageViews within a website.
24
 *
25
 * PageManager will parse all available dynamic and static PageViews. After, dynamic PageViews will be prepared by
26
 * setting the appropriate values for each ContentItem such as permalinks.
27
 *
28
 * @internal
29
 */
30
class PageManager extends TrackingManager
31
{
32
    /** @var StaticPageView[] A place to store a reference to static PageViews with titles. */
33
    private $staticPages;
34
    private $configuration;
35
    private $collectionManager;
36
    private $dataManager;
37
38
    /**
39
     * PageManager constructor.
40
     */
41 7
    public function __construct(Configuration $configuration, CollectionManager $collectionManager = null, DataManager $dataManager = null)
42
    {
43 7
        parent::__construct();
44
45 7
        $this->trackedItems = array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array(\allejo\stakx\Docu...PEATER_TYPE => array()) of type array<string|integer,array> is incompatible with the declared type array<integer,object<all...ment\ReadableDocument>> of property $trackedItems.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
46 7
            BasePageView::STATIC_TYPE   => array(),
47 7
            BasePageView::DYNAMIC_TYPE  => array(),
48 7
            BasePageView::REPEATER_TYPE => array(),
49
        );
50 7
        $this->staticPages = array();
51 7
        $this->configuration = $configuration;
52 7
        $this->collectionManager = $collectionManager;
53 7
        $this->dataManager = $dataManager;
54 7
    }
55
56
    /**
57
     * Go through all of the PageView directories and create a respective PageView for each and classify them by type.
58
     *
59
     * @param string[] $pageViewFolders
60
     *
61
     * @since 0.1.0
62
     *
63
     * @throws \Exception When the EventDispatcher service couldn't be found.
64
     */
65 7
    public function parsePageViews(array $pageViewFolders)
66
    {
67 7
        foreach ($pageViewFolders as $pageViewFolderName)
68
        {
69 7
            $pageViewFolderPath = fs::absolutePath($pageViewFolderName);
70
71 7
            if (!fs::exists($pageViewFolderPath))
72 7
            {
73 1
                $this->output->warning("The '$pageViewFolderName' folder could not be found");
74 1
                continue;
75
            }
76
77 6
            $this->scanTrackableItems($pageViewFolderPath, [
78 6
                'fileExplorer' => FileExplorer::INCLUDE_ONLY_FILES,
79 6
            ], ['/.html$/', '/.twig$/']);
80 6
        }
81
82 6
        if ($this->container !== null)
83 6
        {
84
            $ed = $this->container->get('event_dispatcher');
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $ed. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
85
            $ed->dispatch(PageViewsCompleted::NAME, null);
86
        }
87 6
    }
88
89
    /**
90
     * {@inheritdoc}
91
     *
92
     * @throws \Exception
93
     */
94 7
    public function compileManager()
95
    {
96 7
        $this->parsePageViews($this->configuration->getPageViewFolders());
97 6
    }
98
99
    /**
100
     * Get all of the PageViews in an associative array with PageView types as the keys.
101
     *
102
     * @since  0.1.1
103
     *
104
     * @return BasePageView[][]
0 ignored issues
show
Documentation introduced by
Should the return type not be \allejo\stakx\Document\ReadableDocument[]?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
105
     */
106
    public function &getPageViews()
107
    {
108
        return $this->trackedItems;
109
    }
110
111
    /**
112
     * Get all of the PageViews in flat array.
113
     *
114
     * @since  0.1.1
115
     *
116
     * @return BasePageView[]
0 ignored issues
show
Documentation introduced by
Should the return type not be \allejo\stakx\Document\ReadableDocument[]?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
117
     */
118 5
    public function &getPageViewsFlattened()
119
    {
120 5
        return $this->trackedItemsFlattened;
121
    }
122
123
    /**
124
     * Get the static PageViews tracked by this manager indexed by their title.
125
     *
126
     * @since 0.1.0
127
     *
128
     * @return StaticPageView[]
129
     */
130 1
    public function getStaticPageViews()
131
    {
132 1
        return $this->staticPages;
133
    }
134
135
    /**
136
     * Get the jailed version of the static PageViews indexed by their title.
137
     *
138
     * @since 0.1.0
139
     *
140
     * @return JailedDocument[]
141
     */
142 1
    public function getJailedStaticPageViews()
143
    {
144 1
        $jailedObjects = array();
145
146 1
        foreach ($this->staticPages as $key => $value)
147
        {
148 1
            $jailedObjects[$key] = $value->createJail();
149 1
        }
150
151 1
        return $jailedObjects;
152
    }
153
154
    /**
155
     * Add a new ContentItem to the respective parent PageView of the ContentItem.
156
     *
157
     * @param ContentItem $contentItem
158
     *
159
     * @since 0.1.0
160
     */
161 1
    public function trackNewContentItem(&$contentItem)
162
    {
163 1
        $collection = $contentItem->getNamespace();
164 1
        $this->trackedItems[BasePageView::DYNAMIC_TYPE][$collection]->addCollectableItem($contentItem);
165 1
    }
166
167
    /**
168
     * {@inheritdoc}
169
     */
170 6
    protected function &handleTrackableItem($filePath, array $options = array())
171
    {
172 6
        $pageView = BasePageView::create($filePath);
173 6
        $namespace = $pageView->getType();
174
175
        switch ($namespace)
176
        {
177 6
            case BasePageView::STATIC_TYPE:
178 2
                $this->handleTrackableStaticPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...View::create($filePath) on line 172 can also be of type object<allejo\stakx\Document\DynamicPageView> or object<allejo\stakx\Document\RepeaterPageView>; however, allejo\stakx\Manager\Pag...ackableStaticPageView() does only seem to accept object<allejo\stakx\Document\StaticPageView>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
179 2
                break;
180
181 4
            case BasePageView::DYNAMIC_TYPE:
182 4
                $this->handleTrackableDynamicPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...View::create($filePath) on line 172 can also be of type object<allejo\stakx\Document\RepeaterPageView> or object<allejo\stakx\Document\StaticPageView>; however, allejo\stakx\Manager\Pag...ckableDynamicPageView() does only seem to accept object<allejo\stakx\Document\DynamicPageView>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
183 3
                break;
184
185
            default:
186
                break;
187
        }
188
189 5
        $this->addObjectToTracker($pageView, $namespace);
190
191 5
        return $pageView;
192
    }
193
194
    /**
195
     * Handle special behavior and treatment for static PageViews while we're iterating through them.
196
     *
197
     * @param StaticPageView $pageView
198
     *
199
     * @since 0.1.0
200
     */
201 2
    private function handleTrackableStaticPageView(&$pageView)
202
    {
203 2
        if (empty($pageView['title']))
204 2
        {
205 2
            return;
206
        }
207
208 2
        $this->staticPages[$pageView['title']] = &$pageView;
209 2
    }
210
211
    /**
212
     * Handle special behavior and treatment for dynamic PageViews while we're iterating through them.
213
     *
214
     * @param DynamicPageView $pageView
215
     *
216
     * @since 0.1.0
217
     *
218
     * @throws \Exception
219
     */
220 4
    private function handleTrackableDynamicPageView(&$pageView)
221
    {
222 4
        $frontMatter = $pageView->getFrontMatter(false);
223 4
        $dataSource = null;
224 4
        $namespace = null;
225
226 4
        if (isset($frontMatter['collection']))
227 4
        {
228 4
            $dataSource = &$this->collectionManager->getCollections();
229 4
            $namespace = 'collection';
230 4
        }
231
        elseif (isset($frontMatter['dataset']))
232
        {
233
            $dataSource = &$this->dataManager->getDataItems();
234
            $namespace = 'dataset';
235
        }
236
237 4
        if ($dataSource === null)
238 4
        {
239
            throw new \Exception('Invalid Dynamic PageView defined');
240
        }
241
242 4
        $collection = $frontMatter[$namespace];
243
244 4
        if (!isset($dataSource[$collection]))
245 4
        {
246 1
            throw new CollectionNotFoundException("The '$collection' $namespace is not defined");
247
        }
248
249
        /** @var ContentItem|DataItem $item */
250 3
        foreach ($dataSource[$collection] as &$item)
251
        {
252 3
            $item->evaluateFrontMatter($frontMatter);
253 3
            $item->setParentPageView($pageView);
254 3
            $item->buildPermalink(true);
255
256 3
            $pageView->addCollectableItem($item);
257 3
        }
258 3
    }
259
}
260