Completed
Push — master ( 2319eb...3c4d84 )
by Vladimir
02:22
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 7
    public function __construct(Configuration $configuration, CollectionManager $collectionManager, DataManager $dataManager, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
46
    {
47 7
        $this->trackedItems = [
48
            BasePageView::STATIC_TYPE   => [],
49
            BasePageView::DYNAMIC_TYPE  => [],
50
            BasePageView::REPEATER_TYPE => [],
51
        ];
52 7
        $this->staticPages = [];
53 7
        $this->configuration = $configuration;
54 7
        $this->collectionManager = $collectionManager;
55 7
        $this->dataManager = $dataManager;
56 7
        $this->eventDispatcher = $eventDispatcher;
57 7
        $this->logger = $logger;
58 7
    }
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
     * @throws \Exception When the EventDispatcher service couldn't be found.
76
     */
77 7
    public function parsePageViews(array $pageViewFolders)
78
    {
79 7
        foreach ($pageViewFolders as $pageViewFolderName)
80
        {
81 7
            $pageViewFolderPath = fs::absolutePath($pageViewFolderName);
82
83 7
            if (!fs::exists($pageViewFolderPath))
84
            {
85 1
                $this->logger->warning("The '$pageViewFolderName' folder could not be found");
86 1
                continue;
87
            }
88
89 6
            $this->scanTrackableItems($pageViewFolderPath, [
90 6
                'fileExplorer' => FileExplorer::INCLUDE_ONLY_FILES,
91 6
            ], ['/.html$/', '/.twig$/']);
92
        }
93 6
    }
94
95
    /**
96
     * Get all of the PageViews in an associative array with PageView types as the keys.
97
     *
98
     * @since  0.1.1
99
     *
100
     * @return BasePageView[][]
101
     */
102
    public function &getPageViews()
103
    {
104
        return $this->trackedItems;
105
    }
106
107
    /**
108
     * Get all of the PageViews in flat array.
109
     *
110
     * @since  0.1.1
111
     *
112
     * @return BasePageView[]
113
     */
114 5
    public function &getPageViewsFlattened()
115
    {
116 5
        return $this->trackedItemsFlattened;
117
    }
118
119
    /**
120
     * Get the static PageViews tracked by this manager indexed by their title.
121
     *
122
     * @since 0.1.0
123
     *
124
     * @return StaticPageView[]
125
     */
126 1
    public function getStaticPageViews()
127
    {
128 1
        return $this->staticPages;
129
    }
130
131
    /**
132
     * Get the jailed version of the static PageViews indexed by their title.
133
     *
134
     * @since 0.1.0
135
     *
136
     * @return JailedDocument[]
137
     */
138 1
    public function getJailedStaticPageViews()
139
    {
140 1
        $jailedObjects = array();
141
142 1
        foreach ($this->staticPages as $key => $value)
143
        {
144 1
            $jailedObjects[$key] = $value->createJail();
145
        }
146
147 1
        return $jailedObjects;
148
    }
149
150
    /**
151
     * Add a new ContentItem to the respective parent PageView of the ContentItem.
152
     *
153
     * @param ContentItem $contentItem
154
     *
155
     * @since 0.1.0
156
     */
157 1
    public function trackNewContentItem(&$contentItem)
158
    {
159 1
        $collection = $contentItem->getNamespace();
160 1
        $this->trackedItems[BasePageView::DYNAMIC_TYPE][$collection]->addCollectableItem($contentItem);
161 1
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166 6
    protected function &handleTrackableItem(File $filePath, array $options = array())
167
    {
168 6
        $pageView = BasePageView::create($filePath, [
169 6
            'site' => $this->configuration->getConfiguration(),
170
        ]);
171 6
        $namespace = $pageView->getType();
172
173
        switch ($namespace)
174
        {
175 6
            case BasePageView::STATIC_TYPE:
176 2
                $this->handleTrackableStaticPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...n->getConfiguration())) on line 168 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...
177 2
                break;
178
179 4
            case BasePageView::DYNAMIC_TYPE:
180 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 168 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...
181 3
                break;
182
183
            case BasePageView::REPEATER_TYPE:
184
                $this->handleTrackableRepeaterPageView($pageView);
0 ignored issues
show
Bug introduced by
It seems like $pageView defined by \allejo\stakx\Document\B...n->getConfiguration())) on line 168 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...
185
                break;
186
187
            default:
188
                break;
189
        }
190
191 5
        $this->addObjectToTracker($pageView, $namespace);
192
193 5
        return $pageView;
194
    }
195
196
    /**
197
     * Handle special behavior and treatment for static PageViews while we're iterating through them.
198
     *
199
     * @param StaticPageView $pageView
200
     *
201
     * @since 0.1.0
202
     */
203 2
    private function handleTrackableStaticPageView(&$pageView)
204
    {
205 2
        $pageView->evaluateFrontMatter([], [
206 2
            'site' => $this->configuration->getConfiguration(),
207
        ]);
208
209 2
        if (empty($pageView['title']))
210
        {
211 2
            return;
212
        }
213
214 2
        $this->staticPages[$pageView['title']] = &$pageView;
215 2
    }
216
217
    /**
218
     * Handle special behavior and treatment for dynamic PageViews while we're iterating through them.
219
     *
220
     * @param DynamicPageView $pageView
221
     *
222
     * @since 0.1.0
223
     *
224
     * @throws \Exception
225
     */
226 4
    private function handleTrackableDynamicPageView(&$pageView)
227
    {
228 4
        $frontMatter = $pageView->getRawFrontMatter();
229 4
        $dataSource = null;
230 4
        $namespace = null;
231
232 4
        if (isset($frontMatter['collection']))
233
        {
234 4
            $dataSource = &$this->collectionManager->getCollections();
235 4
            $namespace = 'collection';
236
        }
237
        elseif (isset($frontMatter['dataset']))
238
        {
239
            $dataSource = &$this->dataManager->getDataItems();
240
            $namespace = 'dataset';
241
        }
242
243 4
        if ($dataSource === null)
244
        {
245
            throw new \Exception('Invalid Dynamic PageView defined');
246
        }
247
248 4
        $collection = $frontMatter[$namespace];
249
250 4
        if (!isset($dataSource[$collection]))
251
        {
252 1
            throw new CollectionNotFoundException("The '$collection' $namespace is not defined");
253
        }
254
255
        /** @var ContentItem|DataItem $item */
256 3
        foreach ($dataSource[$collection] as &$item)
257
        {
258 3
            $item->evaluateFrontMatter($frontMatter, [
259 3
                'site' => $this->configuration->getConfiguration(),
260
            ]);
261 3
            $item->setParentPageView($pageView);
262 3
            $item->buildPermalink(true);
263
264 3
            $pageView->addCollectableItem($item);
265
        }
266 3
    }
267
268
    /**
269
     * Handle special behavior and treatment for repeater PageViews while we're iterating through them.
270
     *
271
     * @param RepeaterPageView $pageView
272
     *
273
     * @since 0.2.0
274
     */
275
    private function handleTrackableRepeaterPageView(&$pageView)
276
    {
277
        $pageView->evaluateFrontMatter([], [
278
            'site' => $this->configuration->getConfiguration(),
279
        ]);
280
        $pageView->configurePermalinks();
281
    }
282
}
283