1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector; |
4
|
|
|
|
5
|
|
|
use Error; |
6
|
|
|
use SplFileInfo; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
use Symfony\Component\Finder\Finder; |
10
|
|
|
use Spatie\EventProjector\EventHandlers\EventHandler; |
11
|
|
|
|
12
|
|
|
final class DiscoverEventHandlers |
13
|
|
|
{ |
14
|
|
|
private $directories = []; |
15
|
|
|
|
16
|
|
|
private $basePath; |
17
|
|
|
|
18
|
|
|
private $rootNamespace = ''; |
19
|
|
|
|
20
|
|
|
public function __construct() |
21
|
|
|
{ |
22
|
|
|
$this->basePath = app_path(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function within(array $directories): self |
26
|
|
|
{ |
27
|
|
|
$this->directories = $directories; |
28
|
|
|
|
29
|
|
|
return $this; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function useBasePath(string $basePath): self |
33
|
|
|
{ |
34
|
|
|
$this->basePath = $basePath; |
35
|
|
|
|
36
|
|
|
return $this; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function useRootNamespace(string $rootNamespace): self |
40
|
|
|
{ |
41
|
|
|
$this->rootNamespace = $rootNamespace; |
42
|
|
|
|
43
|
|
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function addToProjectionist(Projectionist $projectionist) |
47
|
|
|
{ |
48
|
|
|
$files = (new Finder())->files()->in($this->directories); |
49
|
|
|
|
50
|
|
|
return collect($files) |
51
|
|
|
->map(function (SplFileInfo $file) { |
52
|
|
|
return static::fullQualifiedClassNameFromFile($file); |
53
|
|
|
}) |
54
|
|
|
->filter(function (string $eventHandlerClass) { |
55
|
|
|
// try { |
56
|
|
|
return is_subclass_of($eventHandlerClass, EventHandler::class); |
57
|
|
|
//} catch (Error $error) { |
58
|
|
|
// return false; |
59
|
|
|
// } |
60
|
|
|
}) |
61
|
|
|
->pipe(function (Collection $eventHandlers) use ($projectionist) { |
62
|
|
|
$projectionist->addEventHandlers($eventHandlers->toArray()); |
63
|
|
|
}); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function fullQualifiedClassNameFromFile(SplFileInfo $file): string |
67
|
|
|
{ |
68
|
|
|
$class = trim(str_replace($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); |
69
|
|
|
|
70
|
|
|
$class = str_replace( |
71
|
|
|
[DIRECTORY_SEPARATOR, 'App\\'], |
72
|
|
|
['\\', app()->getNamespace()], |
73
|
|
|
ucfirst(Str::replaceLast('.php', '', $class)) |
74
|
|
|
); |
75
|
|
|
|
76
|
|
|
return $this->rootNamespace . $class; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|