RouteCollection::isRouteMatchesPattern()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 11
cp 0
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 4
nop 2
crap 20
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