-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvent.php
128 lines (108 loc) · 2.96 KB
/
Event.php
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
namespace ICanBoogie;
use ICanBoogie\Accessor\AccessorTrait;
use function func_num_args;
use function get_called_class;
use function is_object;
use function trigger_error;
use const E_USER_DEPRECATED;
/**
* An event.
*
* @property-read bool $stopped
* Whether the even propagation has been stopped.
* {@see self::get_stopped()}
*/
abstract class Event
{
use AccessorTrait;
/**
* @param object|class-string $sender
*
* @return string
* A qualified event type made of the sender class and the unqualified event type;
* for example, "Exception::recover"
*/
public static function for(string|object $sender): string
{
if (is_object($sender)) {
$sender = $sender::class;
}
return $sender . '::' . get_called_class();
}
/**
* The sender of the event.
*
* **Note**: The property is only initialized if the event is constructed with a sender.
*/
public readonly object $sender; // @phpstan-ignore-line
/**
* Event unqualified type; for example, `MyEvent`.
*/
public readonly string $unqualified_type;
/**
* Event qualified type; for example, `Exception::MyEvent`.
*/
public readonly string $qualified_type;
/**
* @param object|null $sender The sender of the event.
*/
public function __construct(?object $sender = null)
{
if (func_num_args() > 1) {
trigger_error(
"The 'type' parameter is no longer supported, the event class is used instead.",
E_USER_DEPRECATED,
);
}
if (func_num_args() > 2) {
trigger_error(
"The 'payload' parameter is no longer supported, better write an event class.",
E_USER_DEPRECATED,
);
}
$this->unqualified_type = $this::class;
if ($sender) {
$this->sender = $sender;
$this->qualified_type = static::for($sender);
} else {
$this->qualified_type = $this->unqualified_type;
}
}
private bool $stopped = false;
private function get_stopped(): bool
{
return $this->stopped;
}
/**
* Stops the hook chain.
*
* After the `stop()` method is called, the hook chain is broken and no other hook is called.
*/
public function stop(): void
{
$this->stopped = true;
}
/**
* Chain of hooks to execute once the event has been fired.
*
* @var callable[]
*
* @internal
*/
public array $internal_chain = [];
/**
* Add an event hook to the finish chain.
*
* The finish chain is executed after the event chain was traversed without being stopped.
*
* @phpstan-param (callable(Event, ?object): void) $hook
*
* @return $this
*/
public function chain(callable $hook): static
{
$this->internal_chain[] = $hook;
return $this;
}
}