1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector\EventHandlers; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
|
7
|
|
|
trait HandlesEvents |
8
|
|
|
{ |
9
|
|
|
public function handlesEvents(): array |
10
|
|
|
{ |
11
|
|
|
return $this->handlesEvents ?? []; |
|
|
|
|
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
public function handlesEvent(object $event): bool |
15
|
|
|
{ |
16
|
|
|
$handlesEvents = $this->handlesEvents(); |
17
|
|
|
$eventClass = get_class($event); |
18
|
|
|
|
19
|
|
|
return array_key_exists($eventClass, $handlesEvents) |
20
|
|
|
|| $this->checkNonAssociativeEvent($handlesEvents, $eventClass); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function methodNameThatHandlesEvent(object $event): string |
24
|
|
|
{ |
25
|
|
|
$handlesEvents = $this->handlesEvents(); |
26
|
|
|
|
27
|
|
|
$eventClass = get_class($event); |
28
|
|
|
|
29
|
|
|
$methodName = $this->getAssociativeMethodName($handlesEvents, $eventClass); |
30
|
|
|
|
31
|
|
|
if ($methodName === '') { |
32
|
|
|
$methodName = $this->getNonAssociativeMethodName($handlesEvents, $eventClass); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return $methodName; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function handleException(Exception $exception) |
39
|
|
|
{ |
40
|
|
|
report($exception); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
protected function checkNonAssociativeEvent(array $handlesEvents, string $eventClass): bool |
44
|
|
|
{ |
45
|
|
|
return array_key_exists($eventClass, array_flip($handlesEvents)); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
protected function getAssociativeMethodName(array $handlesEvents, string $eventClass): string |
49
|
|
|
{ |
50
|
|
|
$methodName = $handlesEvents[$eventClass] ?? ''; |
51
|
|
|
|
52
|
|
|
if ($methodName !== '') { |
53
|
|
|
return $methodName; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
$wildcardMethod = $handlesEvents['*'] ?? ''; |
57
|
|
|
|
58
|
|
|
if ($wildcardMethod !== '') { |
59
|
|
|
return $wildcardMethod; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return ''; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
protected function getNonAssociativeMethodName(array $handlesEvents, string $eventClass): string |
66
|
|
|
{ |
67
|
|
|
if ($this->checkNonAssociativeEvent($handlesEvents, $eventClass)) { |
68
|
|
|
return 'on'.ucfirst(class_basename($eventClass)); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return ''; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: