Completed
Push — master ( e306f1...c9eaa1 )
by Iman
05:24
created

RouterEventManager::wrapCallbackForIgnore()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Imanghafoori\HeyMan\WatchingStrategies;
4
5
use Illuminate\Support\Str;
6
7
class RouterEventManager
8
{
9
    private $target;
10
11
    private $value;
12
13
    private $routeNames = [];
14
15
    private $actions = [];
16
17
    private $urls = [];
18
19
    /**
20
     * RouterEventManager constructor.
21
     *
22
     * @param $target
23
     * @param $value
24
     * @return \Imanghafoori\HeyMan\WatchingStrategies\RouterEventManager
25
     */
26 48
    public function init($target, $value)
27
    {
28 48
        $this->target = $target;
29 48
        $this->value = $value;
30
31 48
        return $this;
32
    }
33
34 40
    public function getUrls($url)
35
    {
36 40
        return $this->resolveCallback($url, 'urls');
37
    }
38
39 28
    public function getRouteNames($routeName)
40
    {
41 28
        return $this->resolveCallback($routeName, 'routeNames');
42
    }
43
44 26
    public function getActions($action)
45
    {
46 26
        return $this->resolveCallback($action, 'actions');
47
    }
48
49
    /**
50
     * @param $callback
51
     */
52 40
    public function startGuarding(callable $callback)
53
    {
54 40
        foreach ($this->value as $value) {
55 40
            $this->{$this->target}[$value] = $callback;
56
        }
57 40
    }
58
59
    /**
60
     * @param $action
61
     * @param $type
62
     *
63
     * @return \Closure
64
     */
65 40
    private function resolveCallback($action, $type): \Closure
66
    {
67 40
        if (array_key_exists($action, $this->{$type})) {
68 31
            $callback = $this->{$type}[$action];
69
70 31
            return $this->wrapCallbackForIgnore($callback);
71
        }
72
73 29
        foreach ($this->{$type} as $pattern => $callback) {
74 11
            if (Str::is($pattern, $action)) {
75 11
                return $this->wrapCallbackForIgnore($callback);
76
            }
77
        }
78
79
        return function () {
80 28
        };
81
    }
82
83
    /**
84
     * @param $callback
85
     * @return \Closure
86
     */
87 36
    private function wrapCallbackForIgnore($callback): \Closure
88
    {
89
        return function () use ($callback) {
90 36
            if (! config('heyman_ignore_route', false)) {
91 27
                $callback();
92
            }
93 36
        };
94
    }
95
}
96