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
|
|
|
private $ignoredFiles = []; |
21
|
|
|
|
22
|
|
|
public function __construct() |
23
|
|
|
{ |
24
|
|
|
$this->basePath = app_path(); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function within(array $directories): self |
28
|
|
|
{ |
29
|
|
|
$this->directories = $directories; |
30
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function useBasePath(string $basePath): self |
35
|
|
|
{ |
36
|
|
|
$this->basePath = $basePath; |
37
|
|
|
|
38
|
|
|
return $this; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function useRootNamespace(string $rootNamespace): self |
42
|
|
|
{ |
43
|
|
|
$this->rootNamespace = $rootNamespace; |
44
|
|
|
|
45
|
|
|
return $this; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function ignoringFiles(array $ignoredFiles): self |
49
|
|
|
{ |
50
|
|
|
$this->ignoredFiles = $ignoredFiles; |
51
|
|
|
|
52
|
|
|
return $this; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function addToProjectionist(Projectionist $projectionist) |
56
|
|
|
{ |
57
|
|
|
$files = (new Finder())->files()->in($this->directories); |
58
|
|
|
|
59
|
|
|
return collect($files) |
60
|
|
|
->reject(function(SplFileInfo $file) { |
61
|
|
|
return in_array($file->getPathname(), $this->ignoredFiles); |
62
|
|
|
}) |
63
|
|
|
->map(function (SplFileInfo $file) { |
64
|
|
|
return static::fullQualifiedClassNameFromFile($file); |
65
|
|
|
}) |
66
|
|
|
->filter(function (string $eventHandlerClass) { |
67
|
|
|
return is_subclass_of($eventHandlerClass, EventHandler::class); |
68
|
|
|
}) |
69
|
|
|
->pipe(function (Collection $eventHandlers) use ($projectionist) { |
70
|
|
|
$projectionist->addEventHandlers($eventHandlers->toArray()); |
71
|
|
|
}); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
protected function fullQualifiedClassNameFromFile(SplFileInfo $file): string |
75
|
|
|
{ |
76
|
|
|
$class = trim(str_replace($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); |
77
|
|
|
|
78
|
|
|
$class = str_replace( |
79
|
|
|
[DIRECTORY_SEPARATOR, 'App\\'], |
80
|
|
|
['\\', app()->getNamespace()], |
81
|
|
|
ucfirst(Str::replaceLast('.php', '', $class)) |
82
|
|
|
); |
83
|
|
|
|
84
|
|
|
return $this->rootNamespace . $class; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|