DiscoverEventHandlers::useRootNamespace()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\EventProjector;
4
5
use SplFileInfo;
6
use Illuminate\Support\Str;
7
use Illuminate\Support\Collection;
8
use Symfony\Component\Finder\Finder;
9
use Spatie\EventProjector\EventHandlers\EventHandler;
10
11
final class DiscoverEventHandlers
12
{
13
    private $directories = [];
14
15
    private $basePath = '';
16
17
    private $rootNamespace = '';
18
19
    private $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(function (SplFileInfo $file) {
64
                return in_array($file->getPathname(), $this->ignoredFiles);
65
            })
66
            ->map(function (SplFileInfo $file) {
67
                return $this->fullQualifiedClassNameFromFile($file);
68
            })
69
            ->filter(function (string $eventHandlerClass) {
70
                return is_subclass_of($eventHandlerClass, EventHandler::class);
71
            })
72
            ->pipe(function (Collection $eventHandlers) use ($projectionist) {
73
                $projectionist->addEventHandlers($eventHandlers->toArray());
74
            });
75
    }
76
77
    private function fullQualifiedClassNameFromFile(SplFileInfo $file): string
78
    {
79
        $class = trim(str_replace($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
80
81
        $class = str_replace(
82
            [DIRECTORY_SEPARATOR, 'App\\'],
83
            ['\\', app()->getNamespace()],
84
            ucfirst(Str::replaceLast('.php', '', $class))
85
        );
86
87
        return $this->rootNamespace.$class;
88
    }
89
}
90