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