Completed
Push — master ( b239b2...a9d0a0 )
by Filipe
02:58
created

Dispatcher::handle()   B

Complexity

Conditions 2
Paths 8

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 24
ccs 14
cts 14
cp 1
rs 8.9713
cc 2
eloc 16
nc 8
nop 2
crap 2
1
<?php
2
3
/**
4
 * This file is part of slick/mvc package
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Slick\Mvc;
11
12
use Aura\Router\Route;
13
use Guzzle\Http\Message\RequestInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Psr\Http\Message\ServerRequestInterface;
16
use Slick\Http\Server\AbstractMiddleware;
17
use Slick\Http\Server\MiddlewareInterface;
18
use Slick\Mvc\Exception\ControllerMethodNotFoundException;
19
use Slick\Mvc\Exception\ControllerNotFoundException;
20
use Slick\Mvc\Exception\InvalidControllerException;
21
use Slick\Template\Template;
22
23
/**
24
 * Dispatcher
25
 *
26
 * @package Slick\Mvc
27
 * @author  Filipe Silva <[email protected]>
28
 */
29
class Dispatcher extends AbstractMiddleware implements MiddlewareInterface
30
{
31
32
    /**
33
     * @var string
34
     */
35
    protected $namespace;
36
37
    /**
38
     * @var string
39
     */
40
    protected $action;
41
42
    /**
43
     * @var string
44
     */
45
    protected $controller;
46
47
    /**
48
     * @var string
49
     */
50
    protected $args = [];
51
52
    /**
53
     * Handles a Request and updated the response
54
     *
55
     * @param ServerRequestInterface $request
56
     * @param ResponseInterface $response
57
     *
58
     * @return ResponseInterface
59
     */
60 10
    public function handle(
61
        ServerRequestInterface $request, ResponseInterface $response
62
    )
63
    {
64
        /** @var Route $route */
65 10
        $route = $request->getAttribute('route', false);
66 10
        $this->setAttributes($route);
67 10
        $class = $this->namespace.'\\'.$this->controller;
68
        try {
69 10
            $controller = $this->createController($class);
70 6
            $controller->register($request, $response);
71
72 6
            $this->checkAction($class);
73
74 4
            call_user_func_array([$controller, $this->action], $this->args);
75 4
            $request = $controller->getRequest();
76 4
            $request = $this->setViewVars($controller, $request);
77 4
            $response = $controller->getResponse();
78 8
        } catch (ControllerNotFoundException $caught) {
79 2
            $this->checkView($request, $caught);
80
        }
81
82 4
        return $this->executeNext($request, $response);
83
    }
84
85
86 2
    protected function checkView(
87
        ServerRequestInterface $request,
88
        ControllerNotFoundException $caught
89
    ) {
90
        /** @var Route $route */
91 2
        $route = $request->getAttribute('route');
92 2
        $def = $route->attributes;
93 2
        $viewName = "{$def['controller']}/{$def['action']}.twig";
94 2
        $paths = Template::getPaths();
95 2
        foreach ($paths as $path) {
96 2
            $filename = str_replace('//', '/', "{$path}/{$viewName}");
97 2
            if (is_file($filename)) {
98 1
                return;
99
            }
100 1
        }
101 2
        throw $caught;
102
    }
103
104
    /**
105
     * Sets the data values into request
106
     * 
107
     * @param ControllerInterface $controller
108
     * @param ServerRequestInterface $request
109
     * 
110
     * @return ServerRequestInterface|static
111
     */
112 4
    protected function setViewVars(
113
        ControllerInterface $controller, ServerRequestInterface $request
114
    ) {
115 4
        $key = $controller::REQUEST_ATTR_VIEW_DATA;
116 4
        $data = $request->getAttribute($key, []);
117 4
        $request = $request->withAttribute(
118 2
            $key,
119 4
            array_merge($data, $controller->getViewVars())
120 2
        );
121 4
        return $request;
122
    }
123
124
    /**
125
     * Creates the controller with provided class name
126
     *
127
     * @param string $controller
128
     *
129
     * @return ControllerInterface
130
     */
131 10
    protected function createController($controller)
132
    {
133 10
        $this->checkClass($controller);
134 8
        $handler = new $controller;
135 8
        if (! $handler instanceof ControllerInterface) {
136 2
            throw new InvalidControllerException(
137 2
                "The class '{$controller}' does not implement ControllerInterface."
138 1
            );
139
        }
140 6
        return $handler;
141
    }
142
143
    /**
144
     * Check if class exists
145
     *
146
     * @param string $className
147
     * @return $this|self|Dispatcher
148
     */
149 10
    protected function checkClass($className)
150
    {
151 10
        if ($className == '\\' || !class_exists($className)) {
152 2
            throw new ControllerNotFoundException(
153 2
                "The controller '{$className}' was not found."
154 1
            );
155
        }
156 8
        return $this;
157
    }
158
159
    /**
160
     * @param Route $route
161
     *
162
     * @return $this|self|Dispatcher
163
     */
164 10
    protected function setAttributes(Route $route)
165
    {
166 10
        $this->namespace = array_key_exists('namespace', $route->attributes)
167 9
            ? $route->attributes['namespace']
168 6
            : null;
169 10
        $this->controller = array_key_exists('controller', $route->attributes)
170 10
            ? ucfirst($this->normalize($route->attributes['controller']))
171 5
            : null;
172 10
        $this->action = array_key_exists('action', $route->attributes)
173 9
            ? $this->normalize($route->attributes['action'])
174 6
            : null;
175 10
        $this->args  = array_key_exists('args', $route->attributes)
176 6
            ? $route->attributes['args']
177 9
            : [];
178 10
        return $this;
179
    }
180
181
    /**
182
     * Normalize controller/action names
183
     *
184
     * @param string $name
185
     * @return string
186
     */
187 10
    protected function normalize($name)
188
    {
189 10
        $name = str_replace(['_', '-'], '#', $name);
190 10
        $words = explode('#', $name);
191
        array_walk($words, function(&$item){$item = ucfirst($item);});
192 10
        return lcfirst(implode('', $words));
193
    }
194
195
    /**
196
     * Check if action is defined in the controller
197
     *
198
     * @param string $className
199
     *
200
     * @return Dispatcher
201
     */
202 6
    protected function checkAction($className)
203
    {
204 6
        if (!in_array($this->action, get_class_methods($className))) {
205 2
            throw new ControllerMethodNotFoundException(
206 2
                "The method {$this->action} is not defined in ".
207 2
                "'{$className}' controller."
208 1
            );
209
        }
210 4
        return $this;
211
    }
212
}