Completed
Push — master ( a50eb2...240fb3 )
by Freek
05:11 queued 03:53
created

HandlesEvents::autoDetectHandlesEvents()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 2
nc 1
nop 0
1
<?php
2
3
namespace Spatie\EventProjector\EventHandlers;
4
5
use Exception;
6
use Illuminate\Support\Collection;
7
use ReflectionClass;
8
use ReflectionMethod;
9
use ReflectionParameter;
10
use Spatie\EventProjector\Models\StoredEvent;
11
use Spatie\EventProjector\Exceptions\InvalidEventHandler;
12
use Spatie\EventProjector\ShouldBeStored;
13
14
trait HandlesEvents
15
{
16
    public function handles(): array
17
    {
18
        return $this->getEventHandlingMethods()->keys()->toArray();
19
    }
20
21
    public function handle(StoredEvent $storedEvent)
22
    {
23
        $eventClass = $storedEvent->event_class;
24
25
        $handlerClassOrMethod = $this->getEventHandlingMethods()->get($eventClass);
26
27
        $parameters = [
28
            'event' => $storedEvent->event,
29
            'storedEvent' => $storedEvent,
30
            'aggregateUuid' => $storedEvent->aggregate_uuid,
31
        ];
32
33
        if (class_exists($handlerClassOrMethod)) {
34
            return app()->call([app($handlerClassOrMethod), '__invoke'], $parameters);
35
        }
36
37
        if (!method_exists($this, $handlerClassOrMethod)) {
38
            throw InvalidEventHandler::eventHandlingMethodDoesNotExist($this, $storedEvent->event, $handlerClassOrMethod);
39
        }
40
41
        app()->call([$this, $handlerClassOrMethod], $parameters);
42
    }
43
44
    public function handleException(Exception $exception): void
45
    {
46
        report($exception);
47
    }
48
49
    private function getEventHandlingMethods(): Collection
50
    {
51
        $handlesEvents = collect($this->handlesEvents ?? [])
0 ignored issues
show
Bug introduced by
The property handlesEvents does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
52
            ->mapWithKeys(function (string $handlerMethod, $eventClass) {
53
                if (is_numeric($eventClass)) {
54
                    return [$handlerMethod => 'on'.ucfirst(class_basename($handlerMethod))];
55
                }
56
57
                return [$eventClass => $handlerMethod];
58
            });
59
60
        if ($this->handleEvent ?? false) {
0 ignored issues
show
Bug introduced by
The property handleEvent does not seem to exist. Did you mean handlesEvents?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
61
            $handlesEvents->put($this->handleEvent, get_class($this));
0 ignored issues
show
Bug introduced by
The property handleEvent does not seem to exist. Did you mean handlesEvents?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
62
        }
63
64
        if (! isset($this->handlesEvents) && ! isset($this->handleEvent)) {
65
            $handlesEvents = $this->autoDetectHandlesEvents();
66
        }
67
68
        return $handlesEvents;
69
    }
70
71
    private function autoDetectHandlesEvents(): Collection
72
    {
73
        return collect((new ReflectionClass($this))->getMethods())
74
            ->flatMap(function (ReflectionMethod $method) {
75
                $method = new ReflectionMethod($this, $method->name);
76
77
                $eventClass = collect($method->getParameters())
78
                    ->map(function (ReflectionParameter $parameter) {
79
                        return optional($parameter->getType())->getName();
80
                    })
81
                    ->first(function ($typeHint) {
82
                        return is_subclass_of($typeHint, ShouldBeStored::class);
83
                    });
84
85
                if (!$eventClass) {
86
                    return null;
87
                }
88
89
                return [$eventClass => $method->name];
90
            })
91
            ->filter();
92
    }
93
}
94