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

RouteDispatcher   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 155
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 13
dl 0
loc 155
rs 10
c 0
b 0
f 0

7 Methods

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