Completed
Pull Request — master (#148)
by Freek
01:23
created

DiscoverEventHandlers   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 63
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A within() 0 6 1
A useBasePath() 0 6 1
A useRootNamespace() 0 6 1
A addToProjectionist() 0 15 1
A fullQualifiedClassNameFromFile() 0 12 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
    public function __construct()
20
    {
21
        $this->basePath = app_path();
22
    }
23
24
    public function within(array $directories): self
25
    {
26
        $this->directories = $directories;
27
28
        return $this;
29
    }
30
31
    public function useBasePath(string $basePath): self
32
    {
33
        $this->basePath = $basePath;
34
35
        return $this;
36
    }
37
38
    public function useRootNamespace(string $rootNamespace): self
39
    {
40
        $this->rootNamespace = $rootNamespace;
41
42
        return $this;
43
    }
44
45
    public function addToProjectionist(Projectionist $projectionist)
46
    {
47
        $files = (new Finder())->files()->in($this->directories);
48
49
        return collect($files)
50
            ->map(function (SplFileInfo $file) {
51
                return static::fullQualifiedClassNameFromFile($file);
52
            })
53
            ->filter(function (string $eventHandlerClass) {
54
                return is_subclass_of($eventHandlerClass, EventHandler::class);
55
            })
56
            ->pipe(function (Collection $eventHandlers) use ($projectionist) {
57
                $projectionist->addEventHandlers($eventHandlers->toArray());
58
            });
59
    }
60
61
    protected function fullQualifiedClassNameFromFile(SplFileInfo $file): string
62
    {
63
        $class = trim(str_replace($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
64
65
        $class = str_replace(
66
            [DIRECTORY_SEPARATOR, 'App\\'],
67
            ['\\', app()->getNamespace()],
68
            ucfirst(Str::replaceLast('.php', '', $class))
69
        );
70
71
        return $this->rootNamespace.$class;
72
    }
73
}
74