Completed
Push — master ( b00e9b...6e0e0e )
by Vladimir
03:28
created

PageManager::parsePageViews()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
ccs 10
cts 10
cp 1
cc 3
eloc 9
nc 3
nop 1
crap 3
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\RepeaterPageView;
17
use allejo\stakx\Document\StaticPageView;
18
use allejo\stakx\Filesystem\File;
19
use allejo\stakx\Filesystem\FilesystemLoader as fs;
20
use allejo\stakx\Event\PageViewsCompleted;
21
use allejo\stakx\Exception\CollectionNotFoundException;
22
use allejo\stakx\Filesystem\FileExplorer;
23
use Psr\Log\LoggerInterface;
24
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
25
26
/**
27
 * This class is responsible for handling all of the PageViews within a website.
28
 *
29
 * PageManager will parse all available dynamic and static PageViews. After, dynamic PageViews will be prepared by
30
 * setting the appropriate values for each ContentItem such as permalinks.
31
 */
32
class PageManager extends TrackingManager
33
{
34
    /** @var StaticPageView[] A place to store a reference to static PageViews with titles. */
35
    private $staticPages;
36
    private $configuration;
37
    private $collectionManager;
38
    private $dataManager;
39
    private $eventDispatcher;
40
    private $logger;
41
42
    /**
43
     * PageManager constructor.
44
     */
45 19
    public function __construct(Configuration $configuration, CollectionManager $collectionManager, DataManager $dataManager, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
46
    {
47 19
        $this->trackedItems = [
48
            BasePageView::STATIC_TYPE   => [],
49
            BasePageView::DYNAMIC_TYPE  => [],
50
            BasePageView::REPEATER_TYPE => [],
51
        ];
52 19
        $this->staticPages = [];
53 19
        $this->configuration = $configuration;
54 19
        $this->collectionManager = $collectionManager;
55 19
        $this->dataManager = $dataManager;
56 19
        $this->eventDispatcher = $eventDispatcher;
57 19
        $this->logger = $logger;
58 19
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63 7
    public function compileManager()
64
    {
65 7
        $this->parsePageViews($this->configuration->getPageViewFolders());
66 6
    }
67
68
    /**
69
     * Go through all of the PageView directories and create a respective PageView for each and classify them by type.
70
     *
71
     * @param string[] $pageViewFolders
72
     *
73
     * @since 0.1.0
74
     */
75 19
    public function parsePageViews(array $pageViewFolders)
76
    {
77 19
        foreach ($pageViewFolders as $pageViewFolderName)
78
        {
79 19
            $pageViewFolderPath = fs::absolutePath($pageViewFolderName);
80
81 19
            if (!fs::exists($pageViewFolderPath))
82
            {
83 1
                $this->logger->warning("The '$pageViewFolderName' folder could not be found");
84 1
                continue;
85
            }
86
87 18
            $this->scanTrackableItems($pageViewFolderPath, [
88 18
                'fileExplorer' => FileExplorer::INCLUDE_ONLY_FILES,
89 18
            ], ['/.html$/', '/.twig$/']);
90
        }
91 18
    }
92
93
    /**
94
     * Get all of the PageViews in an associative array with PageView types as the keys.
95
     *
96
     * @since  0.1.1
97
     *
98
     * @return BasePageView[][]
99
     */
100
    public function &getPageViews()
101
    {
102
        return $this->trackedItems;
103
    }
104
105
    /**
106
     * Get all of the PageViews in flat array.
107
     *
108
     * @since  0.1.1
109
     *
110
     * @return BasePageView[]
111
     */
112 17
    public function &getPageViewsFlattened()
113
    {
114 17
        return $this->trackedItemsFlattened;
115
    }
116
117
    /**
118
     * Get the static PageViews tracked by this manager indexed by their title.
119
     *
120
     * @since 0.1.0
121
     *
122
     * @return StaticPageView[]
123
     */
124 1
    public function getStaticPageViews()
125
    {
126 1
        return $this->staticPages;
127
    }
128
129
    /**
130
     * Get the jailed version of the static PageViews indexed by their title.
131
     *
132
     * @since 0.1.0
133
     *
134
     * @return JailedDocument[]
135
     */
136 13
    public function getJailedStaticPageViews()
137
    {
138 13
        $jailedObjects = array();
139
140 13
        foreach ($this->staticPages as $key => $value)
141
        {
142 1
            $jailedObjects[$key] = $value->createJail();
143
        }
144
145 13
        return $jailedObjects;
146
    }
147
148
    /**
149
     * Add a new ContentItem to the respective parent PageView of the ContentItem.
150
     *
151
     * @param ContentItem $contentItem
152
     *
153
     * @since 0.1.0
154
     */
155 1
    public function trackNewContentItem(&$contentItem)
156
    {
157 1
        $collection = $contentItem->getNamespace();
158 1
        $this->trackedItems[BasePageView::DYNAMIC_TYPE][$collection]->addCollectableItem($contentItem);
159 1
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164 18
    protected function &handleTrackableItem(File $filePath, array $options = array())
165
    {
166 18
        $pageView = BasePageView::create($filePath, [
167 18
            'site' => $this->configuration->getConfiguration(),
168
        ]);
169 18
        $namespace = $pageView->getType();
170
171
        switch ($namespace)
172
        {
173 18
            case BasePageView::STATIC_TYPE:
174 11
                $this->handleTrackableStaticPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...n->getConfiguration())) on line 166 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...
175 11
                break;
176
177 7
            case BasePageView::DYNAMIC_TYPE:
178 4
                $this->handleTrackableDynamicPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...n->getConfiguration())) on line 166 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...
179 3
                break;
180
181 3
            case BasePageView::REPEATER_TYPE:
182 3
                $this->handleTrackableRepeaterPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...n->getConfiguration())) on line 166 can also be of type object<allejo\stakx\Document\DynamicPageView> or object<allejo\stakx\Document\StaticPageView>; however, allejo\stakx\Manager\Pag...kableRepeaterPageView() does only seem to accept object<allejo\stakx\Document\RepeaterPageView>, 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 17
        $this->addObjectToTracker($pageView, $namespace);
190
191 17
        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 11
    private function handleTrackableStaticPageView(&$pageView)
202
    {
203 11
        $pageView->evaluateFrontMatter([], [
204 11
            'site' => $this->configuration->getConfiguration(),
205
        ]);
206
207 11
        if (empty($pageView['title']))
208
        {
209 11
            return;
210
        }
211
212 2
        $this->staticPages[$pageView['title']] = &$pageView;
213 2
    }
214
215
    /**
216
     * Handle special behavior and treatment for dynamic PageViews while we're iterating through them.
217
     *
218
     * @param DynamicPageView $pageView
219
     *
220
     * @since 0.1.0
221
     *
222
     * @throws \Exception
223
     */
224 4
    private function handleTrackableDynamicPageView(&$pageView)
225
    {
226 4
        $frontMatter = $pageView->getRawFrontMatter();
227 4
        $dataSource = null;
228 4
        $namespace = null;
229
230 4
        if (isset($frontMatter['collection']))
231
        {
232 4
            $dataSource = &$this->collectionManager->getCollections();
233 4
            $namespace = 'collection';
234
        }
235
        elseif (isset($frontMatter['dataset']))
236
        {
237
            $dataSource = &$this->dataManager->getDataItems();
238
            $namespace = 'dataset';
239
        }
240
241 4
        if ($dataSource === null)
242
        {
243
            throw new \Exception('Invalid Dynamic PageView defined');
244
        }
245
246 4
        $collection = $frontMatter[$namespace];
247
248 4
        if (!isset($dataSource[$collection]))
249
        {
250 1
            throw new CollectionNotFoundException("The '$collection' $namespace is not defined");
251
        }
252
253
        /** @var ContentItem|DataItem $item */
254 3
        foreach ($dataSource[$collection] as &$item)
255
        {
256 3
            $item->evaluateFrontMatter($frontMatter, [
257 3
                'site' => $this->configuration->getConfiguration(),
258
            ]);
259 3
            $item->setParentPageView($pageView);
260 3
            $item->buildPermalink(true);
261
262 3
            $pageView->addCollectableItem($item);
263
        }
264 3
    }
265
266
    /**
267
     * Handle special behavior and treatment for repeater PageViews while we're iterating through them.
268
     *
269
     * @param RepeaterPageView $pageView
270
     *
271
     * @since 0.2.0
272
     */
273 3
    private function handleTrackableRepeaterPageView(&$pageView)
274
    {
275 3
        $pageView->evaluateFrontMatter([], [
276 3
            'site' => $this->configuration->getConfiguration(),
277
        ]);
278 3
        $pageView->configurePermalinks();
279 3
    }
280
}
281