DiscoverEvents.php
2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace Illuminate\Foundation\Events;
use Illuminate\Support\Reflector;
use Illuminate\Support\Str;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
class DiscoverEvents
{
/**
* Get all of the events and listeners by searching the given listener directory.
*
* @param string $listenerPath
* @param string $basePath
* @return array
*/
public static function within($listenerPath, $basePath)
{
$listeners = collect(static::getListenerEvents(
(new Finder)->files()->in($listenerPath), $basePath
));
$discoveredEvents = [];
foreach ($listeners as $listener => $events) {
foreach ($events as $event) {
if (! isset($discoveredEvents[$event])) {
$discoveredEvents[$event] = [];
}
$discoveredEvents[$event][] = $listener;
}
}
return $discoveredEvents;
}
/**
* Get all of the listeners and their corresponding events.
*
* @param iterable $listeners
* @param string $basePath
* @return array
*/
protected static function getListenerEvents($listeners, $basePath)
{
$listenerEvents = [];
foreach ($listeners as $listener) {
try {
$listener = new ReflectionClass(
static::classFromFile($listener, $basePath)
);
} catch (ReflectionException $e) {
continue;
}
if (! $listener->isInstantiable()) {
continue;
}
foreach ($listener->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if (! Str::is('handle*', $method->name) ||
! isset($method->getParameters()[0])) {
continue;
}
$listenerEvents[$listener->name.'@'.$method->name] =
Reflector::getParameterClassNames($method->getParameters()[0]);
}
}
return array_filter($listenerEvents);
}
/**
* Extract the class name from the given file path.
*
* @param \SplFileInfo $file
* @param string $basePath
* @return string
*/
protected static function classFromFile(SplFileInfo $file, $basePath)
{
$class = trim(Str::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
return str_replace(
[DIRECTORY_SEPARATOR, ucfirst(basename(app()->path())).'\\'],
['\\', app()->getNamespace()],
ucfirst(Str::replaceLast('.php', '', $class))
);
}
}