Completed
Pull Request — master (#75)
by Vladimir
02:24
created

RouteDispatcher::dynamicPageViewController()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.536
c 0
b 0
f 0
cc 4
nc 1
nop 2
1
<?php
2
3
namespace allejo\stakx\Server;
4
5
use allejo\stakx\Compiler;
6
use allejo\stakx\Document\BasePageView;
7
use allejo\stakx\Document\CollectableItem;
8
use allejo\stakx\Document\DynamicPageView;
9
use allejo\stakx\Document\ReadableDocument;
10
use allejo\stakx\Document\RepeaterPageView;
11
use allejo\stakx\Document\StaticPageView;
12
use allejo\stakx\Document\TemplateReadyDocument;
13
use allejo\stakx\Filesystem\FilesystemLoader as fs;
14
use allejo\stakx\Service;
15
use FastRoute\RouteCollector;
16
use Psr\Http\Message\ServerRequestInterface;
17
use React\Http\Response;
18
19
class RouteDispatcher
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
20
{
21
    private static $baseUrl = '';
22
    private $lastModified = [];
23
24
    /**
25
     * @internal
26
     */
27
    private function __construct()
28
    {
29
    }
30
31
    /**
32
     * Build a controller for handling a Static PageView's URL.
33
     *
34
     * @param StaticPageView $pageView
35
     * @param Compiler       $compiler
36
     *
37
     * @return \Closure
38
     */
39
    private function staticPageViewController(StaticPageView $pageView, Compiler $compiler)
40
    {
41
        return function () use ($pageView, $compiler) {
42
            Service::setOption('currentTemplate', $pageView->getAbsoluteFilePath());
43
44
            if ($this->hasBeenTouched($pageView)) {
45
                $pageView->readContent();
46
            }
47
48
            $mimeType = MimeDetector::getMimeType(fs::getExtension($pageView->getTargetFile()));
0 ignored issues
show
Documentation introduced by
$pageView->getTargetFile() 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...
49
50
            return new Response(
51
                200,
52
                ['Content-Type' => $mimeType],
53
                $compiler->renderStaticPageView($pageView)
54
            );
55
        };
56
    }
57
58
    /**
59
     * Build a controller for handling a Dynamic PageView's URL.
60
     *
61
     * @param DynamicPageView $pageView
62
     * @param Compiler        $compiler
63
     *
64
     * @return \Closure
65
     */
66
    private function dynamicPageViewController(DynamicPageView $pageView, Compiler $compiler)
67
    {
68
        return function (ServerRequestInterface $request) use ($pageView, $compiler) {
69
            Service::setOption('currentTemplate', $pageView->getAbsoluteFilePath());
70
71
            $contentItem = self::getContentItem($pageView, self::normalizeUrl($request->getUri()->getPath()));
72
73
            if ($contentItem === null)
74
            {
75
                return DevServer::return404();
76
            }
77
78
            if ($this->hasBeenTouched($pageView))
79
            {
80
                $pageView->readContent();
81
            }
82
            if ($this->hasBeenTouched($contentItem))
0 ignored issues
show
Documentation introduced by
$contentItem is of type object<allejo\stakx\Document\CollectableItem>, but the function expects a object<allejo\stakx\Document\ReadableDocument>.

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...
83
            {
84
                $contentItem->readContent();
85
            }
86
87
            return DevServer::return200($compiler->renderDynamicPageView($pageView, $contentItem));
0 ignored issues
show
Documentation introduced by
$contentItem is of type object<allejo\stakx\Document\CollectableItem>, but the function expects a object<allejo\stakx\Docu...\TemplateReadyDocument>.

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...
88
        };
89
    }
90
91
    /**
92
     * Build a controller for handling a Repeater PageView's URL.
93
     *
94
     * @param RepeaterPageView $pageView
95
     * @param Compiler         $compiler
96
     *
97
     * @return \Closure
98
     */
99
    private function repeaterPageViewController(RepeaterPageView $pageView, Compiler $compiler)
100
    {
101
        return function (ServerRequestInterface $request) use ($pageView, $compiler) {
102
            $permalinks = $pageView->getRepeaterPermalinks();
103
            $url = self::normalizeUrl($request->getUri()->getPath());
104
105
            foreach ($permalinks as $permalink)
106
            {
107
                if ($permalink->getEvaluated() === $url)
108
                {
109
                    return DevServer::return200(
110
                        $compiler->renderRepeaterPageView($pageView, $permalink)
111
                    );
112
                }
113
            }
114
115
            return DevServer::return404();
116
        };
117
    }
118
119
    /**
120
     * Return the appropriate controller based on a PageView's type.
121
     *
122
     * @param BasePageView|DynamicPageView|RepeaterPageView|StaticPageView $pageView
123
     * @param Compiler     $compiler
124
     *
125
     * @return \Closure
126
     */
127
    private function createController(BasePageView $pageView, Compiler $compiler)
128
    {
129
        switch ($pageView->getType())
130
        {
131
            case BasePageView::STATIC_TYPE:
132
                return $this->staticPageViewController($pageView, $compiler);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\StaticPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
133
134
            case BasePageView::DYNAMIC_TYPE:
135
                return $this->dynamicPageViewController($pageView, $compiler);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\DynamicPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
136
137
            case BasePageView::REPEATER_TYPE:
138
                return $this->repeaterPageViewController($pageView, $compiler);
0 ignored issues
show
Compatibility introduced by
$pageView of type object<allejo\stakx\Document\BasePageView> is not a sub-type of object<allejo\stakx\Document\RepeaterPageView>. It seems like you assume a child class of the class allejo\stakx\Document\BasePageView to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
139
140
            default:
141
                return function () {
142
                    $errMsg = 'This URL type has not yet been implemented.';
143
144
                    return new Response(501, ['Content-Type' => 'text/plain'], $errMsg);
145
                };
146
        }
147
    }
148
149
    /**
150
     * Check to see if a file has been touched since we last read it.
151
     *
152
     * @param ReadableDocument $document
153
     *
154
     * @return bool True if the file has been modified since it was last accessed
155
     */
156
    private function hasBeenTouched(ReadableDocument $document)
157
    {
158
        $rPath = $document->getRelativeFilePath();
159
160
        if (!isset($this->lastModified[$rPath]))
161
        {
162
            $this->lastModified[$rPath] = $document->getLastModified();
163
            return true;
164
        }
165
166
        return ($document->getLastModified() > $this->lastModified[$rPath]);
167
    }
168
169
    /**
170
     * Create a FastRoute Dispatcher.
171
     *
172
     * @param PageViewRouter $router
173
     * @param Compiler       $compiler
174
     *
175
     * @return \FastRoute\Dispatcher
176
     */
177
    public static function create(PageViewRouter $router, Compiler $compiler)
178
    {
179
        self::$baseUrl = $router->getBaseUrl();
180
181
        return \FastRoute\simpleDispatcher(function (RouteCollector $r) use ($router, $compiler) {
182
            $dispatcher = new RouteDispatcher();
183
184
            foreach ($router->getRouteMapping() as $route => $pageView)
185
            {
186
                $r->get($route, $dispatcher->createController($pageView, $compiler));
187
            }
188
        });
189
    }
190
191
    public static function normalizeUrl($url)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
192
    {
193
        return str_replace(self::$baseUrl, '/', $url);
194
    }
195
196
    /**
197
     * Find a ContentItem from a Dynamic PageView or null if it doesn't exist.
198
     *
199
     * @param DynamicPageView $pageView
200
     * @param                 $permalink
201
     *
202
     * @return CollectableItem|ReadableDocument|TemplateReadyDocument|null
203
     */
204
    private static function getContentItem(DynamicPageView $pageView, $permalink)
205
    {
206
        foreach ($pageView->getCollectableItems() as $collectableItem)
207
        {
208
            if ($collectableItem['permalink'] === $permalink)
209
            {
210
                return $collectableItem;
211
            }
212
        }
213
214
        return null;
215
    }
216
}
217