-
-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathDiscoverEventHandlers.php
84 lines (63 loc) · 2.19 KB
/
DiscoverEventHandlers.php
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
<?php
namespace Spatie\EventSourcing\Support;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Spatie\EventSourcing\EventHandlers\EventHandler;
use Spatie\EventSourcing\Projectionist;
use SplFileInfo;
use Symfony\Component\Finder\Finder;
class DiscoverEventHandlers
{
private array $directories = [];
private string $basePath = '';
private string $rootNamespace = '';
private array $ignoredFiles = [];
public function __construct()
{
$this->basePath = app()->path();
}
public function within(array $directories): self
{
$this->directories = $directories;
return $this;
}
public function useBasePath(string $basePath): self
{
$this->basePath = $basePath;
return $this;
}
public function useRootNamespace(string $rootNamespace): self
{
$this->rootNamespace = $rootNamespace;
return $this;
}
public function ignoringFiles(array $ignoredFiles): self
{
$this->ignoredFiles = $ignoredFiles;
return $this;
}
public function addToProjectionist(Projectionist $projectionist)
{
if (empty($this->directories)) {
return;
}
$files = (new Finder())->files()->in($this->directories);
return collect($files)
->reject(fn (SplFileInfo $file) => in_array($file->getPathname(), $this->ignoredFiles))
->map(fn (SplFileInfo $file) => $this->fullQualifiedClassNameFromFile($file))
->filter(fn (string $eventHandlerClass) => is_subclass_of($eventHandlerClass, EventHandler::class))
->pipe(function (Collection $eventHandlers) use ($projectionist) {
$projectionist->addEventHandlers($eventHandlers->toArray());
});
}
private function fullQualifiedClassNameFromFile(SplFileInfo $file): string
{
$class = trim(Str::replaceFirst($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
$class = str_replace(
[DIRECTORY_SEPARATOR, 'App\\'],
['\\', app()->getNamespace()],
ucfirst(Str::replaceLast('.php', '', $class))
);
return $this->rootNamespace.$class;
}
}