Completed
Pull Request — master (#66)
by Vladimir
02:51
created

PageManager::getPageViewsFlattened()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 * @copyright 2018 Vladimir Jimenez
5
 * @license   https://github.com/stakx-io/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\Exception\CollectionNotFoundException;
19
use allejo\stakx\Filesystem\File;
20
use allejo\stakx\Filesystem\FileExplorer;
21
use allejo\stakx\Filesystem\FilesystemLoader as fs;
22
use Psr\Log\LoggerInterface;
23
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
24
25
/**
26
 * This class is responsible for handling all of the PageViews within a website.
27
 *
28
 * PageManager will parse all available dynamic and static PageViews. After, dynamic PageViews will be prepared by
29
 * setting the appropriate values for each ContentItem such as permalinks.
30
 */
31
class PageManager extends TrackingManager
32
{
33
    /** @var StaticPageView[] A place to store a reference to static PageViews with titles. */
34
    private $staticPages;
35
    private $configuration;
36
    private $collectionManager;
37
    private $dataManager;
38
    private $eventDispatcher;
39
    private $logger;
40
41
    /**
42
     * PageManager constructor.
43
     */
44 19
    public function __construct(Configuration $configuration, CollectionManager $collectionManager, DataManager $dataManager, EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)
45
    {
46 19
        $this->trackedItems = [
47
            BasePageView::STATIC_TYPE => [],
48
            BasePageView::DYNAMIC_TYPE => [],
49
            BasePageView::REPEATER_TYPE => [],
50
        ];
51 19
        $this->staticPages = [];
52 19
        $this->configuration = $configuration;
53 19
        $this->collectionManager = $collectionManager;
54 19
        $this->dataManager = $dataManager;
55 19
        $this->eventDispatcher = $eventDispatcher;
56 19
        $this->logger = $logger;
57 19
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 7
    public function compileManager()
63
    {
64 7
        $this->parsePageViews($this->configuration->getPageViewFolders());
65 6
    }
66
67
    /**
68
     * Go through all of the PageView directories and create a respective PageView for each and classify them by type.
69
     *
70
     * @param string[] $pageViewFolders
71
     *
72
     * @since 0.1.0
73
     */
74 19
    public function parsePageViews(array $pageViewFolders)
75
    {
76 19
        foreach ($pageViewFolders as $pageViewFolderName)
77
        {
78 19
            $pageViewFolderPath = fs::absolutePath($pageViewFolderName);
0 ignored issues
show
Documentation introduced by
$pageViewFolderName is of type string, but the function expects a object<string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

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