Collection::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
namespace Te7aHoudini\Laroute\Routes;
4
5
use Illuminate\Support\Arr;
6
use Illuminate\Routing\Route;
7
use Illuminate\Routing\RouteCollection;
8
use Te7aHoudini\Laroute\Routes\Exceptions\ZeroRoutesException;
9
10
class Collection extends \Illuminate\Support\Collection
11
{
12
    public function __construct(RouteCollection $routes, $filter, $namespace)
13
    {
14
        $this->items = $this->parseRoutes($routes, $filter, $namespace);
15
    }
16
17
    /**
18
     * Parse the routes into a jsonable output.
19
     *
20
     * @param RouteCollection $routes
21
     * @param string $filter
22
     * @param string $namespace
23
     *
24
     * @return array
25
     * @throws ZeroRoutesException
26
     */
27
    protected function parseRoutes(RouteCollection $routes, $filter, $namespace)
28
    {
29
        $this->guardAgainstZeroRoutes($routes);
30
        $results = [];
31
        foreach ($routes as $route) {
32
            $results[] = $this->getRouteInformation($route, $filter, $namespace);
33
        }
34
35
        return array_values(array_filter($results));
36
    }
37
38
    /**
39
     * Throw an exception if there aren't any routes to process.
40
     *
41
     * @param RouteCollection $routes
42
     *
43
     * @throws ZeroRoutesException
44
     */
45
    protected function guardAgainstZeroRoutes(RouteCollection $routes)
46
    {
47
        if (count($routes) < 1) {
48
            throw new ZeroRoutesException("You don't have any routes!");
49
        }
50
    }
51
52
    /**
53
     * Get the route information for a given route.
54
     *
55
     * @param $route \Illuminate\Routing\Route
56
     * @param $filter string
57
     * @param $namespace string
58
     *
59
     * @return array
60
     */
61
    protected function getRouteInformation(Route $route, $filter, $namespace)
62
    {
63
        $host = $route->domain();
64
        $methods = $route->methods();
65
        $uri = $route->uri();
66
        $name = $route->getName();
67
        $action = $route->getActionName();
68
        $laroute = Arr::get($route->getAction(), 'laroute', null);
69
        if (! empty($namespace)) {
70
            $a = $route->getAction();
71
            if (isset($a['controller'])) {
72
                $action = str_replace($namespace.'\\', '', $action);
73
            }
74
        }
75
        switch ($filter) {
76
            case 'all':
77
                if ($laroute === false) {
78
                    return;
79
                }
80
                break;
81
            case 'only':
82
                if ($laroute !== true) {
83
                    return;
84
                }
85
                break;
86
        }
87
88
        return compact('host', 'methods', 'uri', 'name', 'action');
89
    }
90
}
91