Completed
Push — master ( bff1a4...59b7c9 )
by Filipe
03:06
created

Dispatcher   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 184
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 98.61%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 19
c 3
b 0
f 0
lcom 1
cbo 9
dl 0
loc 184
ccs 71
cts 72
cp 0.9861
rs 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
B handle() 0 24 2
A setViewVars() 0 11 1
A createController() 0 11 2
A checkClass() 0 9 3
B setAttributes() 0 16 5
A normalize() 0 7 1
A checkAction() 0 10 2
A checkView() 0 17 3
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 10
        } catch (ControllerNotFoundException $caught) {
79 2
            $this->checkView($request, $caught);
0 ignored issues
show
Bug introduced by
It seems like $request defined by $this->setViewVars($controller, $request) on line 76 can also be of type object<Slick\Mvc\Dispatcher>; however, Slick\Mvc\Dispatcher::checkView() does only seem to accept object<Psr\Http\Message\ServerRequestInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
80
        }
81
82 4
        return $this->executeNext($request, $response);
0 ignored issues
show
Bug introduced by
It seems like $request defined by $this->setViewVars($controller, $request) on line 76 can also be of type object<Slick\Mvc\Dispatcher>; however, Slick\Http\Server\Abstra...ddleware::executeNext() does only seem to accept object<Psr\Http\Message\ServerRequestInterface>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
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
                return;
99
            }
100 2
        }
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 4
            $key,
119 4
            array_merge($data, $controller->getViewVars())
120 4
        );
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 = Application::container()->make($controller);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Interop\Container\ContainerInterface as the method make() does only exist in the following implementations of said interface: Slick\Di\Container.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
135 8
        if (! $handler instanceof ControllerInterface) {
136 2
            throw new InvalidControllerException(
137 2
                "The class '{$controller}' does not implement ControllerInterface."
138 2
            );
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 2
            );
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 10
            ? $route->attributes['namespace']
168 10
            : null;
169 10
        $this->controller = array_key_exists('controller', $route->attributes)
170 10
            ? ucfirst($this->normalize($route->attributes['controller']))
171 10
            : null;
172 10
        $this->action = array_key_exists('action', $route->attributes)
173 10
            ? $this->normalize($route->attributes['action'])
174 10
            : null;
175 10
        $this->args  = array_key_exists('args', $route->attributes)
176 10
            ? $route->attributes['args']
177 10
            : [];
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 2
            );
209
        }
210 4
        return $this;
211
    }
212
}