-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventHandler.php
More file actions
78 lines (68 loc) · 2.04 KB
/
EventHandler.php
File metadata and controls
78 lines (68 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/*
* Copyright 2025 Cloud Creativity Limited
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
declare(strict_types=1);
namespace CloudCreativity\Modules\Application\DomainEventDispatching;
use Closure;
use CloudCreativity\Modules\Contracts\Application\UnitOfWork\DispatchAfterCommit;
use CloudCreativity\Modules\Contracts\Application\UnitOfWork\DispatchBeforeCommit;
use CloudCreativity\Modules\Contracts\Domain\Events\DomainEvent;
final readonly class EventHandler
{
/**
* EventHandler constructor.
*
* @param object $listener
*/
public function __construct(private object $listener)
{
assert(
!($this->listener instanceof DispatchBeforeCommit && $this->listener instanceof DispatchAfterCommit),
sprintf(
'Listener "%s" cannot be dispatched both before and after a unit of work is committed..',
get_debug_type($this->listener),
),
);
}
/**
* Should the handler be executed before the transaction is committed?
*
* @return bool
*/
public function beforeCommit(): bool
{
return $this->listener instanceof DispatchBeforeCommit;
}
/**
* Should the handler be executed after the transaction is committed?
*
* @return bool
*/
public function afterCommit(): bool
{
return $this->listener instanceof DispatchAfterCommit;
}
/**
* Execute the listener.
*
* @param DomainEvent $event
* @return void
*/
public function __invoke(DomainEvent $event): void
{
if ($this->listener instanceof Closure) {
($this->listener)($event);
return;
}
assert(method_exists($this->listener, 'handle'), sprintf(
'Listener "%s" is not an object with a handle method or a closure.',
get_debug_type($this->listener),
));
$this->listener->handle($event);
}
}