Completed
Push — master ( c2bd55...6b7717 )
by Todd
09:04
created

ResourceRoute   C

Complexity

Total Complexity 60

Size/Duplication

Total Lines 360
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 92.9%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 60
c 3
b 0
f 1
lcom 2
cbo 6
dl 0
loc 360
ccs 170
cts 183
cp 0.929
rs 6.0976

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A isIdentifier() 0 6 2
A failsCondition() 0 14 3
F dispatch() 0 155 29
C actionExists() 0 22 8
B allowedMethods() 0 26 5
C matches() 0 57 11

How to fix   Complexity   

Complex Class

Complex classes like ResourceRoute often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ResourceRoute, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2014 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden;
9
10
use Garden\Exception\NotFoundException;
11
use Garden\Exception\MethodNotAllowedException;
12
13
/**
14
 * Maps paths to controllers that act as RESTful resources.
15
 *
16
 * The following are examples of urls that will map using this resource route.
17
 * - METHOD /controller/:id -> method
18
 * - METHOD /controller/:id/action -> methodAction
19
 * - GET /controller -> index
20
 * - METHOD /controller/action -> methodAction
21
 */
22
class ResourceRoute extends Route {
23
    protected $controllerPattern = '%sApiController';
24
25
    /**
26
     * @var array An array of controller method names that can't be dispatched to by name.
27
     */
28
    public static $specialActions = ['delete', 'get', 'index', 'initialize', 'options', 'patch', 'post'];
29
30
    /**
31
     * Initialize an instance of the {@link ResourceRoute} class.
32
     *
33
     * @param string $root The url root of that this route will map to.
34
     * @param string $controllerPattern A pattern suitable for {@link sprintf} that will map
35
     * a path to a controller object name.
36
     */
37 34
    public function __construct($root = '', $controllerPattern = null) {
38 34
        $this->pattern($root);
39
40 34
        if ($controllerPattern !== null) {
41 34
            $this->controllerPattern = $controllerPattern;
42 34
        }
43 34
    }
44
45
    /**
46
     * Dispatch the route.
47
     *
48
     * @param Request $request The current request we are dispatching against.
49
     * @param array &$args The args to pass to the dispatch.
50
     * These are the arguments returned from {@link Route::matches()}.
51
     * @return mixed Returns the result from the controller method.
52
     * @throws NotFoundException Throws a 404 when the path doesn't map to a controller action.
53
     * @throws MethodNotAllowedException Throws a 405 when the http method does not map to a controller action,
54
     * but other methods do.
55
     */
56 34
    public function dispatch(Request $request, array &$args) {
57 34
        $controller = new $args['controller']();
58 34
        $method = strtolower($args['method']);
59 34
        $pathArgs = $args['pathArgs'];
60
61
        // See if the initialize method can take any of the parameters.
62 34
        $initialize = false;
63 34
        $initArgs = [];
64 34
        $initParams = [];
65 34
        $actionIndex = 0;
66 34
        if (method_exists($controller, 'initialize')) {
67 28
            $initialize = true;
68 28
            $initMethod = new \ReflectionMethod($controller, 'initialize');
69
70
            // Walk through the initialize() arguments and supply all of the ones that are required.
71 28
            foreach ($initMethod->getParameters() as $initParam) {
72 28
                $i = $initParam->getPosition();
73 28
                $initArgs[$i] = null;
74 28
                $initParams[$i] = $initParam->getName();
75
76 28
                if ($initParam->isDefaultValueAvailable()) {
77 23
                    $initArgs[$i] = $initParam->getDefaultValue();
78 28
                } elseif (!isset($pathArgs[$i])) {
79 1
                    throw new NotFoundException('Page', "Missing argument $i for {$args['controller']}::initialize().");
80 4
                } elseif ($this->failsCondition($initParams[$i], $pathArgs[$i])) {
81
                    // This isn't a valid value for a required parameter.
82 1
                    throw new NotFoundException('Page', "Invalid argument '{$pathArgs[$i]}' for {$initParams[$i]}.");
83
                } else {
84 3
                    $initArgs[$i] = $pathArgs[$i];
85 3
                    $actionIndex = $i + 1;
86
                }
87 26
            }
88 26
        }
89
90 32
        $action = '';
91 32
        $initComplete = false;
92 32
        for ($i = $actionIndex; $i < count($pathArgs); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
93 22
            $pathArg = $pathArgs[$i];
94
95 22
            $action = $this->actionExists($controller, $pathArg, $method, true);
96 22
            if ($action) {
97
                // We found an action and can move on to the next step.
98 4
                $actionIndex = $i + 1;
99 4
                break;
100
            } else {
101
                // This is a method argument. See whether to add it to the initialize method or not.
102 18
                if (!$initComplete && $actionIndex < count($initArgs)) {
103
                    // Make sure the argument is valid.
104 14
                    if ($this->failsCondition($initParams[$actionIndex], $pathArg)) {
105
                        // The argument doesn't validate against its condition so this can't be an init argument.
106 3
                        $initComplete = true;
107 3
                    } else {
108
                        // The argument can be added to initialize().
109 11
                        $initArgs[$actionIndex] = $pathArg;
110 11
                        $actionIndex++;
111
                    }
112 14
                }
113
            }
114 18
        }
115
116 32
        if (!$action) {
117
            // There is no specific action at this point so we have to check for a resource action.
118 28
            if ($actionIndex === 0) {
119 14
                $actions = ['get' => 'index', 'post' => 'post', 'options' => 'options'];
120 14
            } else {
121 14
                $actions = ['get' => 'get', 'patch' => 'patch', 'put' => 'put', 'delete' => 'delete'];
122
            }
123
124 28
            if (!isset($actions[$method])) {
125 5
                if ($actionIndex < count($pathArgs)) {
126
                    // There are more path args left to go then just throw a 404.
127 2
                    throw new NotFoundException();
128
                } else {
129
                    // The http method isn't allowed.
130 3
                    $allowed = array_keys($actions);
131 3
                    throw new MethodNotAllowedException($method, $allowed);
132
                }
133
            }
134
135 23
            $action = $actions[$method];
136 23
            if (!$this->actionExists($controller, $action)) {
137
                // If there are more path args left to go then just throw a 404.
138 4
                if ($actionIndex < count($pathArgs)) {
139 1
                    throw new NotFoundException();
140
                }
141
142
                // Check to see what actions are allowed.
143 3
                unset($actions[$method]);
144 3
                $allowed = [];
145 3
                foreach ($actions as $otherMethod => $otherAction) {
146 3
                    if ($this->actionExists($controller, $otherAction)) {
147 3
                        $allowed[] = strtoupper($otherMethod);
148 3
                    }
149 3
                }
150
151 3
                if (!empty($allowed)) {
152
                    // Other methods are allowed. Show them.
153 3
                    throw new MethodNotAllowedException($method, $allowed);
154
                } else {
155
                    // The action does not exist at all.
156
                    throw new NotFoundException();
157
                }
158
            }
159 19
        }
160
161
        // Make sure the number of action arguments match the action method.
162 23
        $actionMethod = new \ReflectionMethod($controller, $action);
163 23
        $action = $actionMethod->getName(); // make correct case.
164 23
        $actionParams = $actionMethod->getParameters();
165 23
        $actionArgs = array_slice($pathArgs, $actionIndex);
166
167 23
        if (count($actionArgs) > count($actionParams)) {
168
            // Double check to see if the first argument might be a method, but one that isn't allowed.
169 6
            $allowed = $this->allowedMethods($controller, $actionArgs[0]);
170 6
            if (count($allowed) > 0) {
171
                // At least one method was allowed for this action so throw an exception.
172 1
                throw new MethodNotAllowedException($method, $allowed);
173
            }
174
175
            // Too many arguments were passed.
176 5
            throw new NotFoundException();
177
        }
178
        // Fill in missing default parameters.
179 17
        foreach ($actionParams as $param) {
180 10
            $i = $param->getPosition();
181 10
            $paramName = $param->getName();
182
183 10
            if ($this->isMapped($paramName)) {
184
                // The parameter is mapped to a specific request item.
185 2
                array_splice($actionArgs, $i, 0, [$this->mappedData($paramName, $request)]);
186 10
            } elseif (!isset($actionArgs[$i]) || !$actionArgs[$i]) {
187 4
                if ($param->isDefaultValueAvailable()) {
188 3
                    $actionArgs[$i] = $param->getDefaultValue();
189 3
                } else {
190 1
                    throw new NotFoundException('Page', "Missing argument $i for {$args['controller']}::$action().");
191
                }
192 7
            } elseif ($this->failsCondition($paramName, $actionArgs[$i])) {
193 1
                throw new NotFoundException('Page', "Invalid argument '{$actionArgs[$i]}' for {$paramName}.");
194
            }
195 15
        }
196
197 15
        $args = array_replace($args, [
198 15
            'init' => $initialize,
199 15
            'initArgs' => $initArgs,
200 15
            'action' => $action,
201
            'actionArgs' => $actionArgs
202 15
        ]);
203
204 15
        if ($initialize) {
205 15
            Event::callUserFuncArray([$controller, 'initialize'], $initArgs);
206 15
        }
207
208 15
        $result = Event::callUserFuncArray([$controller, $action], $actionArgs);
209 15
        return $result;
210
    }
211
212
    /**
213
     * Tests whether or not a string is a valid identifier.
214
     *
215
     * @param string $str The string to test.
216
     * @return bool Returns true if {@link $str} can be used as an identifier.
217
     */
218 30
    protected static function isIdentifier($str) {
219 30
        if (preg_match('`[_a-zA-Z][_a-zA-Z0-9]{0,30}`i', $str)) {
220 28
            return true;
221
        }
222 11
        return false;
223
    }
224
225
    /**
226
     * Tests whether a controller action exists.
227
     *
228
     * @param object $object The controller object that the method should be on.
229
     * @param string $action The name of the action.
230
     * @param string $method The http method.
231
     * @param bool $special Whether or not to blacklist the special methods.
232
     * @return string Returns the name of the action method or an empty string if it doesn't exist.
233
     */
234 30
    protected function actionExists($object, $action, $method = '', $special = false) {
235 30
        if ($special && in_array($action, self::$specialActions)) {
236 3
            return '';
237
        }
238
239
        // Short circuit on a badly named action.
240 30
        if (!$this->isIdentifier($action)) {
241 11
            return '';
242
        }
243
244 28
        if ($method && $method !== $action) {
245 10
            $calledAction = $method.$action;
246 10
            if (Event::methodExists($object, $calledAction)) {
247 4
                return $calledAction;
248
            }
249 6
        }
250 24
        $calledAction = $action;
251 24
        if (Event::methodExists($object, $calledAction)) {
252 22
            return $calledAction;
253
        }
254 10
        return '';
255
    }
256
257
    /**
258
     * Find the allowed http methods on a controller object.
259
     *
260
     * @param object $object The object to test.
261
     * @param string $action The action to test.
262
     * @return array Returns an array of allowed http methods.
263
     */
264 6
    protected function allowedMethods($object, $action) {
265
        $allMethods = [
266 6
            Request::METHOD_GET, Request::METHOD_POST, Request::METHOD_DELETE,
267 6
            Request::METHOD_PATCH, Request::METHOD_PUT,
268 6
            Request::METHOD_HEAD, Request::METHOD_OPTIONS
269 6
        ];
270
271
        // Special actions should not be considered.
272 6
        if (in_array($action, self::$specialActions)) {
273 1
            return [];
274
        }
275
276 5
        if (Event::methodExists($object, $action)) {
277
            // The controller has the named action and thus supports all methods.
278
            return $allMethods;
279
        }
280
281
        // Loop through all the methods and check to see if they exist in the form $method.$action.
282 5
        $allowed = [];
283 5
        foreach ($allMethods as $method) {
284 5
            if (Event::methodExists($object, $method.$action)) {
285 1
                $allowed[] = $method;
286 1
            }
287 5
        }
288 5
        return $allowed;
289
    }
290
291
    /**
292
     * Try matching a route to a request.
293
     *
294
     * @param Request $request The request to match the route with.
295
     * @param Application $app The application instantiating the route.
296
     * @return array|null Whether or not the route matches the request.
297
     * If the route matches an array of args is returned, otherwise the function returns null.
298
     */
299 34
    public function matches(Request $request, Application $app) {
300 34
        if (!$this->matchesMethods($request)) {
301
            return null;
302
        }
303
304 34
        if ($this->getMatchFullPath()) {
305
            $path = $request->getFullPath();
306
        } else {
307 34
            $path = $request->getPath();
308
        }
309
310
        // If this route is off of a root then check that first.
311 34
        if ($root = $this->pattern()) {
312 34
            if (stripos($path, $root) === 0) {
313
                // Strip the root off the path that we are examining.
314 34
                $path = substr($path, strlen($root));
315 34
            } else {
316
                return null;
317
            }
318 34
        }
319
320 34
        $pathParts = explode('/', trim($path, '/'));
321
322 34
        $controller = array_shift($pathParts);
323 34
        if (!$controller) {
324
            return null;
325
        }
326
327
        // Check to see if a class exists with the desired controller name.
328
        // If a controller is found then it is responsible for the route, regardless of any other parameters.
329 34
        $basename = sprintf($this->controllerPattern, ucfirst($controller));
330 34
        if (class_exists('\Garden\Addons', false)) {
331 34
            list($classname) = Addons::classMap($basename);
332
333
            // TODO: Optimize this second check.
334 34
            if (!$classname && class_exists($basename)) {
335
                $classname = $basename;
336
            }
337 34
        } elseif (class_exists($basename)) {
338
            $classname = $basename;
339
        } else {
340
            $classname = '';
341
        }
342
343 34
        if (!$classname) {
344
            return null;
345
        }
346
347
        $result = array(
348 34
            'controller' => $classname,
349 34
            'method' => $request->getMethod(),
350 34
            'path' => $path,
351 34
            'pathArgs' => $pathParts,
352 34
            'query' => $request->getQuery()
353 34
        );
354 34
        return $result;
355
    }
356
357
    /**
358
     * Tests whether an argument fails against a condition.
359
     *
360
     * @param string $name The name of the parameter.
361
     * @param string $value The value of the argument.
362
     * @return bool|null Returns one of the following:
363
     * - true: The condition fails.
364
     * - false: The condition passes.
365
     * - null: There is no condition.
366
     */
367 19
    protected function failsCondition($name, $value) {
368 19
        $name = strtolower($name);
369 19
        if (isset($this->conditions[$name])) {
370 18
            $regex = $this->conditions[$name];
371 18
            return !preg_match("`^$regex$`", $value);
372
        }
373
374 4
        if (isset(self::$globalConditions[$name])) {
375 3
            $regex = self::$globalConditions[$name];
376 3
            return !preg_match("`^$regex$`", $value);
377
        }
378
379 1
        return null;
380
    }
381
}
382