1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Illuminate\Support\Str; |
7
|
|
|
use Spatie\EventProjector\EventHandlers\EventHandler; |
8
|
|
|
use Spatie\EventProjector\Projectors\Projector; |
9
|
|
|
use Spatie\EventProjector\Projectors\QueuedProjector; |
10
|
|
|
use SplFileInfo; |
11
|
|
|
use Symfony\Component\Finder\Finder; |
12
|
|
|
|
13
|
|
|
final class DiscoverEventHandlers |
14
|
|
|
{ |
15
|
|
|
private $directories = []; |
16
|
|
|
|
17
|
|
|
private $basePath; |
18
|
|
|
|
19
|
|
|
private $rootNamespace = ''; |
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 addToProjectionist(Projectionist $projectionist) |
48
|
|
|
{ |
49
|
|
|
$files = (new Finder())->files()->in($this->directories); |
50
|
|
|
|
51
|
|
|
return collect($files) |
52
|
|
|
->map(function (SplFileInfo $file) { |
53
|
|
|
return static::fullQualifiedClassNameFromFile($file); |
54
|
|
|
}) |
55
|
|
|
->filter(function(string $eventHandlerClass) { |
56
|
|
|
return is_subclass_of($eventHandlerClass, EventHandler::class); |
57
|
|
|
}) |
58
|
|
|
->pipe(function(Collection $eventHandlers) use ($projectionist) { |
59
|
|
|
$projectionist->addEventHandlers($eventHandlers->toArray()); |
60
|
|
|
}); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function fullQualifiedClassNameFromFile(SplFileInfo $file): string { |
64
|
|
|
$class = trim(str_replace($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); |
65
|
|
|
|
66
|
|
|
$class = str_replace( |
67
|
|
|
[DIRECTORY_SEPARATOR, 'App\\'], |
68
|
|
|
['\\', app()->getNamespace()], |
69
|
|
|
ucfirst(Str::replaceLast('.php', '', $class)) |
70
|
|
|
); |
71
|
|
|
|
72
|
|
|
return $this->rootNamespace . $class; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
|