Completed
Pull Request — master (#148)
by Freek
10:52 queued 09:17
created

DiscoverEventHandlers   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 67
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 19 1
A fullQualifiedClassNameFromFile() 0 12 1
1
<?php
2
3
namespace Spatie\EventProjector;
4
5
use Error;
6
use SplFileInfo;
7
use Illuminate\Support\Str;
8
use Illuminate\Support\Collection;
9
use Symfony\Component\Finder\Finder;
10
use Spatie\EventProjector\EventHandlers\EventHandler;
11
12
final class DiscoverEventHandlers
13
{
14
    private $directories = [];
15
16
    private $basePath;
17
18
    private $rootNamespace = '';
19
20
    public function __construct()
21
    {
22
        $this->basePath = app_path();
23
    }
24
25
    public function within(array $directories): self
26
    {
27
        $this->directories = $directories;
28
29
        return $this;
30
    }
31
32
    public function useBasePath(string $basePath): self
33
    {
34
        $this->basePath = $basePath;
35
36
        return $this;
37
    }
38
39
    public function useRootNamespace(string $rootNamespace): self
40
    {
41
        $this->rootNamespace = $rootNamespace;
42
43
        return $this;
44
    }
45
46
    public function addToProjectionist(Projectionist $projectionist)
47
    {
48
        $files = (new Finder())->files()->in($this->directories);
49
50
        return collect($files)
51
            ->map(function (SplFileInfo $file) {
52
                return static::fullQualifiedClassNameFromFile($file);
53
            })
54
            ->filter(function (string $eventHandlerClass) {
55
               // try {
56
                    return is_subclass_of($eventHandlerClass, EventHandler::class);
57
                //} catch (Error $error) {
58
                 //   return false;
59
               // }
60
            })
61
            ->pipe(function (Collection $eventHandlers) use ($projectionist) {
62
                $projectionist->addEventHandlers($eventHandlers->toArray());
63
            });
64
    }
65
66
    protected function fullQualifiedClassNameFromFile(SplFileInfo $file): string
67
    {
68
        $class = trim(str_replace($this->basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR);
69
70
        $class = str_replace(
71
            [DIRECTORY_SEPARATOR, 'App\\'],
72
            ['\\', app()->getNamespace()],
73
            ucfirst(Str::replaceLast('.php', '', $class))
74
        );
75
76
        return $this->rootNamespace . $class;
77
    }
78
}
79