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

RouteDispatcher::hasBeenTouched()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 2
nc 2
nop 1
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
     * Return the appropriate controller based on a PageView's type.
93
     *
94
     * @param BasePageView|DynamicPageView|RepeaterPageView|StaticPageView $pageView
95
     * @param Compiler     $compiler
96
     *
97
     * @return \Closure
98
     */
99
    private function createController(BasePageView $pageView, Compiler $compiler)
100
    {
101
        switch ($pageView->getType())
102
        {
103
            case BasePageView::STATIC_TYPE:
104
                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...
105
106
            case BasePageView::DYNAMIC_TYPE:
107
                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...
108
109
            default:
110
                return function () {
111
                    $errMsg = 'This URL type has not yet been implemented.';
112
113
                    return new Response(501, ['Content-Type' => 'text/plain'], $errMsg);
114
                };
115
        }
116
    }
117
118
    /**
119
     * Check to see if a file has been touched since we last read it.
120
     *
121
     * @param ReadableDocument $document
122
     *
123
     * @return bool True if the file has been modified since it was last accessed
124
     */
125
    private function hasBeenTouched(ReadableDocument $document)
126
    {
127
        $rPath = $document->getRelativeFilePath();
128
129
        if (!isset($this->lastModified[$rPath]))
130
        {
131
            $this->lastModified[$rPath] = $document->getLastModified();
132
            return true;
133
        }
134
135
        return ($document->getLastModified() > $this->lastModified[$rPath]);
136
    }
137
138
    /**
139
     * Create a FastRoute Dispatcher.
140
     *
141
     * @param PageViewRouter $router
142
     * @param Compiler       $compiler
143
     *
144
     * @return \FastRoute\Dispatcher
145
     */
146
    public static function create(PageViewRouter $router, Compiler $compiler)
147
    {
148
        self::$baseUrl = $router->getBaseUrl();
149
150
        return \FastRoute\simpleDispatcher(function (RouteCollector $r) use ($router, $compiler) {
151
            $dispatcher = new RouteDispatcher();
152
153
            foreach ($router->getRouteMapping() as $route => $pageView)
154
            {
155
                $r->get($route, $dispatcher->createController($pageView, $compiler));
156
            }
157
        });
158
    }
159
160
    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...
161
    {
162
        return str_replace(self::$baseUrl, '/', $url);
163
    }
164
165
    /**
166
     * Find a ContentItem from a Dynamic PageView or null if it doesn't exist.
167
     *
168
     * @param DynamicPageView $pageView
169
     * @param                 $permalink
170
     *
171
     * @return CollectableItem|ReadableDocument|TemplateReadyDocument|null
172
     */
173
    private static function getContentItem(DynamicPageView $pageView, $permalink)
174
    {
175
        foreach ($pageView->getCollectableItems() as $collectableItem)
176
        {
177
            if ($collectableItem['permalink'] === $permalink)
178
            {
179
                return $collectableItem;
180
            }
181
        }
182
183
        return null;
184
    }
185
}
186