Completed
Push — master ( c0f250...321e24 )
by Filipe
15:10
created

RouteFactory::parse()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 3
1
<?php
2
3
/**
4
 * This file is part of slick/web_stack 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\WebStack\Router\Builder;
11
12
use Aura\Router\Map;
13
use Aura\Router\Route;
14
15
/**
16
 * RouteFactory
17
 *
18
 * @package Slick\WebStack\Router\Builder
19
 */
20
class RouteFactory implements FactoryInterface
21
{
22
23
    /**
24
     * Receives an array with parameters to create a route or route group
25
     *
26
     * @param string $name The route name
27
     * @param string|array $data Meta data fo the route
28
     * @param Map $map The route map to populate
29
     *
30
     * @return Route
31
     */
32
    public function parse($name, $data, Map $map)
33
    {
34
        if (is_array($data)) {
35
            return $this->complexRoute($name, $data, $map);
36
        }
37
        return $map->get($name, $data);
38
    }
39
40
    /**
41
     * Route construct chain start
42
     *
43
     * @param string $name The route name
44
     * @param string|array $data Meta data fo the route
45
     * @param Map $map The route map to populate
46
     *
47
     * @return Route
48
     */
49
    private function complexRoute($name, array $data, Map $map)
50
    {
51
        $route = $map->route($name, $data['path']);
52
        $method = array_key_exists('method', $data)
53
            ? [$data['method']]
54
            : ['GET'];
55
        $allows = array_key_exists('allows', $data)
56
            ? $data['allows']
57
            : [];
58
        $route->allows(array_merge($method, $allows));
59
        $this->addProperties($route, $data);
60
        return $route;
61
    }
62
63
    /**
64
     * Parses data array to set route properties
65
     *
66
     * @param Route $route
67
     * @param array $data
68
     *
69
     * @return Route
70
     */
71
    private function addProperties(Route $route, array $data)
72
    {
73
        $methods = get_class_methods(Route::class);
74
        $methods = array_diff($methods, ["allows", "path"]);
75
        foreach ($data as $method => $args) {
76
            if (in_array($method, $methods)) {
77
                $route->$method($args);
78
            }
79
        }
80
        return $route;
81
    }
82
}
83