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

RouteDispatcher::createController()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 3
nc 3
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 FastRoute\RouteCollector;
15
use Psr\Http\Message\ServerRequestInterface;
16
use React\Http\Response;
17
18
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...
19
{
20
    private static $baseUrl = '';
21
    private $lastModified = [];
22
23
    /**
24
     * @internal
25
     */
26
    private function __construct()
27
    {
28
    }
29
30
    /**
31
     * Build a controller for handling a Static PageView's URL.
32
     *
33
     * @param StaticPageView $pageView
34
     * @param Compiler       $compiler
35
     *
36
     * @return \Closure
37
     */
38
    private function staticPageViewController(StaticPageView $pageView, Compiler $compiler)
39
    {
40
        return function () use ($pageView, $compiler) {
41
            if ($this->hasBeenTouched($pageView)) {
42
                $pageView->readContent();
43
            }
44
45
            $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...
46
47
            return new Response(
48
                200,
49
                ['Content-Type' => $mimeType],
50
                $compiler->renderStaticPageView($pageView)
51
            );
52
        };
53
    }
54
55
    /**
56
     * Build a controller for handling a Dynamic PageView's URL.
57
     *
58
     * @param DynamicPageView $pageView
59
     * @param Compiler        $compiler
60
     *
61
     * @return \Closure
62
     */
63
    private function dynamicPageViewController(DynamicPageView $pageView, Compiler $compiler)
64
    {
65
        return function (ServerRequestInterface $request) use ($pageView, $compiler) {
66
            $contentItem = self::getContentItem($pageView, self::normalizeUrl($request->getUri()->getPath()));
67
68
            if ($contentItem === null)
69
            {
70
                return DevServer::return404();
71
            }
72
73
            if ($this->hasBeenTouched($pageView))
74
            {
75
                $pageView->readContent();
76
            }
77
            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...
78
            {
79
                $contentItem->readContent();
80
            }
81
82
            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...
83
        };
84
    }
85
86
    /**
87
     * Return the appropriate controller based on a PageView's type.
88
     *
89
     * @param BasePageView|DynamicPageView|RepeaterPageView|StaticPageView $pageView
90
     * @param Compiler     $compiler
91
     *
92
     * @return \Closure
93
     */
94
    private function createController(BasePageView $pageView, Compiler $compiler)
95
    {
96
        switch ($pageView->getType())
97
        {
98
            case BasePageView::STATIC_TYPE:
99
                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...
100
101
            case BasePageView::DYNAMIC_TYPE:
102
                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...
103
104
            default:
105
                return function () {
106
                    $errMsg = 'This URL type has not yet been implemented.';
107
108
                    return new Response(501, ['Content-Type' => 'text/plain'], $errMsg);
109
                };
110
        }
111
    }
112
113
    /**
114
     * Check to see if a file has been touched since we last read it.
115
     *
116
     * @param ReadableDocument $document
117
     *
118
     * @return bool True if the file has been modified since it was last accessed
119
     */
120
    private function hasBeenTouched(ReadableDocument $document)
121
    {
122
        $rPath = $document->getRelativeFilePath();
123
124
        if (!isset($this->lastModified[$rPath]))
125
        {
126
            $this->lastModified[$rPath] = $document->getLastModified();
127
            return true;
128
        }
129
130
        return ($document->getLastModified() > $this->lastModified[$rPath]);
131
    }
132
133
    /**
134
     * Create a FastRoute Dispatcher.
135
     *
136
     * @param PageViewRouter $router
137
     * @param Compiler       $compiler
138
     *
139
     * @return \FastRoute\Dispatcher
140
     */
141
    public static function create(PageViewRouter $router, Compiler $compiler)
142
    {
143
        self::$baseUrl = $router->getBaseUrl();
144
145
        return \FastRoute\simpleDispatcher(function (RouteCollector $r) use ($router, $compiler) {
146
            $dispatcher = new RouteDispatcher();
147
148
            foreach ($router->getRouteMapping() as $route => $pageView)
149
            {
150
                $r->get($route, $dispatcher->createController($pageView, $compiler));
151
            }
152
        });
153
    }
154
155
    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...
156
    {
157
        return str_replace(self::$baseUrl, '/', $url);
158
    }
159
160
    /**
161
     * Find a ContentItem from a Dynamic PageView or null if it doesn't exist.
162
     *
163
     * @param DynamicPageView $pageView
164
     * @param                 $permalink
165
     *
166
     * @return CollectableItem|ReadableDocument|TemplateReadyDocument|null
167
     */
168
    private static function getContentItem(DynamicPageView $pageView, $permalink)
169
    {
170
        foreach ($pageView->getCollectableItems() as $collectableItem)
171
        {
172
            if ($collectableItem['permalink'] === $permalink)
173
            {
174
                return $collectableItem;
175
            }
176
        }
177
178
        return null;
179
    }
180
}
181