Completed
Push — dev-master ( 4d197b...82c8e5 )
by Derek Stephen
05:07
created

Dispatcher::getResponseBody()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 14
cts 14
cp 1
rs 9.0534
c 0
b 0
f 0
cc 4
eloc 12
nc 5
nop 0
crap 4
1
<?php
2
3
namespace Bone\Mvc;
4
5
use Bone\Filter;
6
use Exception;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Bone\Mvc\Exception.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use ReflectionClass;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use Zend\Diactoros\Response\SapiEmitter;
11
12
/**
13
 * Class Dispatcher
14
 * @package Bone\Mvc
15
 */
16
class Dispatcher
17
{
18
    // Garrrr! An arrrray!
19
    private $config = array();
20
21
    /** @var ServerRequestInterface $request */
22
    private $request;
23
24
    /** @var Controller */
25
    private $controller;
26
27
    /** @var ResponseInterface $response */
28
    private $response;
29
30
31 10
    public function __construct(ServerRequestInterface $request, ResponseInterface $response)
32 10
    {
33 10
        $this->request = $request;
34 10
        $this->response = $response;
35
36 10
        $router = new Router($request);
37 10
        $router->parseRoute();
38
39
        // what controller be we talkin' about?
40 10
        $filtered = Filter::filterString($router->getController(), 'DashToCamelCase');
41 10
        $this->config['controller_name'] = '\App\Controller\\' . ucwords($filtered) . 'Controller';
42
43
        // whit be yer action ?
44 10
        $filtered = Filter::filterString($router->getAction(), 'DashToCamelCase');
45 10
        $this->config['action_name'] = $filtered . 'Action';
46 10
        $this->config['controller'] = $router->getController();
47 10
        $this->config['action'] = $router->getAction();
48 10
    }
49
50
51
    /**
52
     *  Gaaarrr! Check the Navigator be readin' the map!
53
     */
54 2
    public function checkNavigator()
55 2
    {
56
        // can we find th' darned controller?
57 1
        if (!$this->checkControllerExists()) {
58 1
            $this->setNotFound();
59 1
            return;
60
        }
61
62
        // gaaarr! there be the controller!
63 1
        $this->controller = new $this->config['controller_name']($this->request);
64
65
        // where's the bloody action?
66 1
        if (!$this->checkActionExists()) {
67 1
            $this->setNotFound();
68 1
        }
69 1
    }
70
71
72
    /**
73
     * @return bool
74
     */
75 2
    private function checkControllerExists()
76 2
    {
77 2
        return class_exists($this->config['controller_name']);
78
    }
79
80
81
    /**
82
     * @return bool
83
     */
84 2
    private function checkActionExists()
85 2
    {
86 2
        return method_exists($this->controller, $this->config['action_name']);
87
    }
88
89
90
    /**
91
     * @return string
92
     * @throws \Exception
93
     */
94 3
    private function getResponseBody()
95 3
    {
96
        /** @var \stdClass $view_vars */
97 3
        $view_vars = $this->controller->view;
98
99 3
        $response_body = $this->controller->getBody();
100
101 3
        if ($this->controller->hasViewEnabled()) {
102 2
            $view = $this->config['controller'] . '/' . $this->config['action'];
103
            try {
104 2
                $response_body = $this->controller->getViewEngine()->render($view, (array) $view_vars);
105 2
            } catch (Exception $e) {
106 1
                throw $e;
107
            }
108 1
        }
109
110 2
        if ($this->controller->hasLayoutEnabled()) {
111 1
            $response_body = $this->templateCheck($this->controller, $response_body);
112 1
        }
113 2
        return $response_body;
114
    }
115
116
117
    /**
118
     *
119
     */
120 2
    public function fireCannons()
121 2
    {
122
        try {
123
            // Where be the navigator? Be we on course?
124 1
            $this->checkNavigator();
125
126
            // boom! direct hit Cap'n! Be gettin' the booty!
127 1
            $this->plunderEnemyShip();
128
129
            // show th' cap'n th' booty
130 1
            $booty = $this->getResponseBody();
131 1
        } catch (Exception $e) {
132 1
            $booty = $this->sinkingShip($e);
133
        }
134
135 1
        $this->response->getBody()->write($booty);
136
137
        // report back to th' cap'n
138 1
        $this->setHeaders();
139
140 1
        $emitter = new SapiEmitter();
141 1
        ob_start();
142 1
        $emitter->emit($this->response);
143 1
        $content = ob_get_contents();
144 1
        ob_end_clean();
145 1
        return  $content;
146
    }
147
148 1
    private function setHeaders()
149 1
    {
150 1
        foreach ($this->controller->getHeaders() as $key => $value) {
151 1
            $this->response = $this->response->withHeader($key, $value);
152 1
        }
153 1
    }
154
155
156 2
    private function plunderEnemyShip()
157 2
    {
158
        // run th' controller action
159 2
        $action = $this->config['action_name'];
160 2
        $this->controller->init();
161 2
        $vars = $this->controller->$action();
162 2
        if (is_array($vars)) {
163 1
            $viewVars = (array) $this->controller->view;
164 1
            $view = (object) array_merge($vars, $viewVars);
165 1
            $this->controller->view =$view;
166 1
        }
167 2
        $this->controller->postDispatch();
168 2
    }
169
170
171 2
    public function sinkingShip($e)
172 2
    {
173 1
        $this->controller = class_exists('\App\Controller\ErrorController') ? new \App\Controller\ErrorController($this->request) : new Controller($this->request);
0 ignored issues
show
Documentation Bug introduced by
It seems like class_exists('\\App\\Con...troller($this->request) can also be of type object<App\Controller\ErrorController>. However, the property $controller is declared as type object<Bone\Mvc\Controller>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
174 1
        $this->controller->setParam('error', $e);
175 1
        $reflection = new ReflectionClass(get_class($this->controller));
176 1
        $method = $reflection->getMethod('errorAction');
177 1
        $method->setAccessible(true);
178 1
        $method->invokeArgs($this->controller, []);
179 1
        $this->controller->error = $e;
180 1
        $this->config['controller'] = 'error';
181 1
        $this->config['action'] = 'error';
182 1
        return $this->getResponseBody();
183
    }
184
185
186
    /**
187
     * @param Controller $controller
188
     * @param string $content
189
     * @return string
190
     */
191 2
    private function templateCheck($controller, $content)
192 2
    {
193 2
        $response_body = '';
194
        //check we be usin' th' templates in th' config
195 2
        $templates = Registry::ahoy()->get('templates');
196 2
        $template = ($templates != null) ? $templates[0] : null;
197 2
        if ($template) {
198 2
            $response_body = $controller->getViewEngine()->render('layouts/' . $template, array('content' => $content));
199 2
        }
200 2
        return $response_body;
201
    }
202
203
204
    /**
205
     * Sets controller to error and action to not found
206
     * @return void
207
     */
208 2
    private function setNotFound()
209 2
    {
210 2
        $this->config['controller_name'] = class_exists('\App\Controller\ErrorController') ? '\App\Controller\ErrorController' : '\Bone\Mvc\Controller';
211 2
        $this->config['action_name'] = 'notFoundAction';
212 2
        $this->config['controller'] = 'error';
213 2
        $this->config['action'] = 'not-found';
214 2
        $this->controller = new $this->config['controller_name']($this->request);
215 2
    }
216
}
217