SpyDispatcher   A
last analyzed

Complexity

Total Complexity 35

Size/Duplication

Total Lines 156
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 156
rs 9.6
c 0
b 0
f 0
wmc 35
lcom 1
cbo 4

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getOriginalListeners() 0 15 4
B listen() 0 27 6
A error() 0 6 2
B validateCallback() 0 28 8
A stringify() 0 4 2
A noClass() 0 7 1
A noMethod() 0 7 1
A getTypeHintedClass() 0 11 3
A addOriginInterfaceListeners() 0 12 4
A stringifyClosure() 0 12 2
A addOriginalListener() 0 8 2
1
<?php
2
3
namespace Imanghafoori\LaravelMicroscope\SpyClasses;
4
5
use Illuminate\Events\Dispatcher;
6
use Illuminate\Support\Str;
7
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
8
use Imanghafoori\LaravelMicroscope\ErrorReporters\PendingError;
9
use Imanghafoori\LaravelMicroscope\LaravelPaths\FilePath;
10
use ReflectionException;
11
use ReflectionFunction;
12
13
class SpyDispatcher extends Dispatcher
14
{
15
    public $originalListeners = [];
16
17
    public static $listeningNum = 0;
18
19
    public $wildcardsOriginal = [];
20
21
    public function listen($events, $listener = null)
22
    {
23
        parent::listen($events, $listener);
0 ignored issues
show
Bug introduced by
It seems like $listener defined by parameter $listener on line 21 can also be of type null; however, Illuminate\Events\Dispatcher::listen() does only seem to accept object<Closure>|string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
24
25
        $events = (array) $events;
26
        foreach ($events as $event) {
27
            self::$listeningNum++;
28
            $this->validateCallback($event, $listener);
29
        }
30
31
        // Do not move this loop into a private method or something, it breaks.
32
        foreach ((array) $events as $event) {
33
            $i = 0;
34
            $excludes = [
35
                base_path('vendor'.DIRECTORY_SEPARATOR.'laravel'),
36
            ];
37
            while (($callSite = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, $i + 1)[$i]) && Str::startsWith($callSite['file'] ?? '', $excludes)) {
38
                $i++;
39
            }
40
            unset($callSite['object']);
41
            if ($listener instanceof \Closure) {
42
                $listener = $this->stringifyClosure($listener);
43
            }
44
45
            $this->addOriginalListener([$listener, $callSite], $event);
46
        }
47
    }
48
49
    public function getOriginalListeners($eventName)
50
    {
51
        $listeners = $this->originalListeners[$eventName] ?? [];
52
53
        $wildcards = [];
54
        foreach ($this->wildcardsOriginal as $key => $wildcardListeners) {
55
            if (Str::is($key, $eventName)) {
56
                $wildcards = array_merge($wildcards, $wildcardListeners);
57
            }
58
        }
59
60
        $listeners = array_merge($listeners, $wildcards);
61
62
        return class_exists($eventName, false) ? $this->addOriginInterfaceListeners($eventName, $listeners) : $listeners;
63
    }
64
65
    private function error($string)
66
    {
67
        $len = strlen($string);
68
        PendingError::$maxLength < $len && PendingError::$maxLength = $len;
69
        app(ErrorPrinter::class)->pended[] = $string;
70
    }
71
72
    protected function validateCallback($event, $listener)
73
    {
74
        if (! is_string($listener)) {
75
            return;
76
        }
77
78
        [$listenerClass, $methodName] = $this->parseClassCallable($listener);
0 ignored issues
show
Bug introduced by
The variable $listenerClass does not exist. Did you mean $listener?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
Bug introduced by
The variable $methodName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
79
80
        try {
81
            $listenerObj = app()->make($listenerClass);
0 ignored issues
show
Bug introduced by
The variable $listenerClass does not exist. Did you mean $listener?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
82
        } catch (\Exception $e) {
83
            return $this->error($this->noClass($event, $listenerClass, $methodName));
0 ignored issues
show
Bug introduced by
The variable $listenerClass does not exist. Did you mean $listener?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
84
        }
85
86
        if (! method_exists($listenerObj, $methodName)) {
87
            return $this->error($this->noMethod($event, $listenerClass, $methodName));
0 ignored issues
show
Bug introduced by
The variable $listenerClass does not exist. Did you mean $listener?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
88
        }
89
90
        $typeHintClassPath = $this->getTypeHintedClass($listenerObj, $methodName);
91
92
        $eventName = $this->stringify($event);
93
94
        if (class_exists($eventName) && $typeHintClassPath) {
95
            if ($eventName !== $typeHintClassPath && ! is_subclass_of($eventName, $typeHintClassPath)) {
96
                return $this->error('The type hint on the listener: '.$listener.' does not match the event class path.');
97
            }
98
        }
99
    }
100
101
    private function stringify($event)
102
    {
103
        return is_object($event) ? get_class($event) : $event;
104
    }
105
106
    protected function noClass($event, $class, $method)
107
    {
108
        $at = \implode('@', [$class, $method]);
109
        $e = $this->stringify($event);
110
111
        return 'The class of '.$at.' can not be resolved as a listener for "'.$e.'" event';
112
    }
113
114
    protected function noMethod($event, $class, $method)
115
    {
116
        $at = \implode('@', [$class, $method]);
117
        $e = $this->stringify($event);
118
119
        return 'The method of '.$at.' is not callable as an event listener for "'.$e.'" event';
120
    }
121
122
    protected function getTypeHintedClass($listenerObj, $methodName)
123
    {
124
        try {
125
            $ref = new \ReflectionParameter([$listenerObj, $methodName], 0);
126
            $typeHint = $ref->getType();
127
128
            return $typeHint ? $typeHint->getName() : null;
129
        } catch (\Exception $e) {
130
            return null;
131
        }
132
    }
133
134
    private function addOriginInterfaceListeners($eventName, $listeners)
135
    {
136
        foreach (class_implements($eventName) as $interface) {
137
            if (isset($this->originalListeners[$interface])) {
138
                foreach ($this->originalListeners[$interface] as $names) {
139
                    $listeners = array_merge($listeners, (array) $names);
140
                }
141
            }
142
        }
143
144
        return $listeners;
145
    }
146
147
    private function stringifyClosure($listener)
148
    {
149
        try {
150
            $reflection = new ReflectionFunction($listener);
151
            $line = $reflection->getStartLine();
152
            $path = FilePath::getRelativePath($reflection->getFileName());
153
154
            return 'Closure at: '.$path.':'.$line;
155
        } catch (ReflectionException $e) {
156
            return '';
157
        }
158
    }
159
160
    private function addOriginalListener($listener, $event)
161
    {
162
        if (Str::contains($event, '*')) {
163
            $this->wildcardsOriginal[$event][] = $listener;
164
        } else {
165
            $this->originalListeners[$event][] = $listener;
166
        }
167
    }
168
}
169