RouteCollection   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 1
dl 0
loc 76
ccs 0
cts 30
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B filterMatch() 0 23 6
A filterExcept() 0 10 2
A isRouteMatchesPattern() 0 18 4
1
<?php
2
3
namespace Loadsman\LaravelPlugin\Collections;
4
5
use Illuminate\Support\Collection;
6
7
/**
8
 * Class RouteCollection
9
 *
10
 * @package \Loadsman\Laravel
11
 */
12
class RouteCollection extends Collection
13
{
14
    /**
15
     * Include routes that match patterns.
16
     *
17
     * @param array <array|string> $patterns
18
     *
19
     * @return static
20
     */
21
    public function filterMatch($patterns)
22
    {
23
        $patterns = is_string($patterns) ? [$patterns] : $patterns;
24
25
        // String pattern is assumed to be path.
26
        foreach ($patterns as $key => $pattern) {
27
            if (is_string($pattern)) {
28
                $patterns[$key] = ['path' => $pattern];
29
            }
30
        }
31
32
        return $this->filter(function ($route) use ($patterns) {
33
            // If any of patterns matches - route passes.
34
            foreach ($patterns as $pattern) {
35
                if ($this->isRouteMatchesPattern($route, $pattern)) {
36
                    return true;
37
                }
38
            }
39
40
            // If all patterns don't match - route is filtered out.
41
            return false;
42
        });
43
    }
44
45
46
    /**
47
     * Exclude routes that match patterns.
48
     *
49
     * @param array <array|string> $patterns
50
     *
51
     * @return static
52
     */
53
    public function filterExcept($patterns = [])
54
    {
55
        if (empty($patterns)) {
56
            return $this;
57
        }
58
59
        $toExclude = $this->filterMatch($patterns)->keys()->toArray();
60
61
        return $this->except($toExclude);
62
    }
63
64
    /**
65
     * @param array $route
66
     * @param array $pattern
67
     * @return bool
68
     */
69
    private function isRouteMatchesPattern(array $route, array $pattern)
70
    {
71
        foreach ($route as $key => $value) {
72
            if (! array_key_exists($key, $pattern)) {
73
                continue;
74
            }
75
76
            if(is_array($value)){
77
                $value = implode(',', $value);
78
            }
79
80
            $regex = '#'.$pattern[$key].'#';
81
82
            return ! ! preg_match($regex, $value);
83
        }
84
85
        return true;
86
    }
87
}
88