Debian Codegraph @

vendor/ipl/stdlib/src/Events.php

raw
1 <?php
2
3 namespace ipl\Stdlib;
4
5 use Evenement\EventEmitterTrait;
6 use InvalidArgumentException;
7
8 /**
9 * Register listeners and emit named events with optional event-name validation
10 */
11 trait Events
12 {
13 use EventEmitterTrait {
14 EventEmitterTrait::on as private evenementUnvalidatedOn;
15 }
16
17 /** @var array<string, true> */
18 protected array $eventsEmittedOnce = [];
19
20 /**
21 * Emit the given event at most once, ignoring subsequent calls
22 *
23 * @param string $event
24 * @param array $arguments
25 *
26 * @return void
27 */
28 protected function emitOnce(string $event, array $arguments = []): void
29 {
30 if (! isset($this->eventsEmittedOnce[$event])) {
31 $this->eventsEmittedOnce[$event] = true;
32 $this->emit($event, $arguments);
33 }
34 }
35
36 /**
37 * Register a listener for the given event, validating the event name first
38 *
39 * @param string $event
40 * @param callable $listener
41 *
42 * @return $this
43 *
44 * @throws InvalidArgumentException If the event name is not valid
45 */
46 public function on($event, callable $listener)
47 {
48 $this->assertValidEvent($event);
49 $this->evenementUnvalidatedOn($event, $listener);
50
51 return $this;
52 }
53
54 /**
55 * Assert that the given event name is valid
56 *
57 * @param string $event
58 *
59 * @return void
60 *
61 * @throws InvalidArgumentException If the event name is not valid
62 */
63 protected function assertValidEvent(string $event): void
64 {
65 if (! $this->isValidEvent($event)) {
66 throw new InvalidArgumentException("$event is not a valid event");
67 }
68 }
69
70 /**
71 * Check whether the given event name is valid
72 *
73 * @param string $event
74 *
75 * @return bool
76 */
77 public function isValidEvent($event)
78 {
79 return true;
80 }
81 }