-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
77 lines (59 loc) · 1.72 KB
/
index.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
<?php
use Acme\Command;
use Acme\Event;
use Acme\Registration;
use Acme\User;
use Acme\UserID;
include __DIR__ . '/vendor/autoload.php';
$users = [];
$listeners = [
Event\UserNameChanged::class => [
function (Event\UserNameChanged $event) {
echo "Old user name: {$event->oldName}.\n";
echo "New user name: {$event->newName}.\n";
}
]
];
$handlers = [
Command\RegisterUser::class => function (Command\RegisterUser $command) use (&$users) {
$id = new UserID($command->id);
$user = User::register($id, $command->name);
$users[(string) $id] = $user;
fire($user->pullEvents());
},
Command\ChangeUserName::class => function (Command\ChangeUserName $command) use (&$users) {
/** @var User $user */
$user = $users[$command->id];
$user->changeName($command->name);
fire($user->pullEvents());
},
];
function fire(array $events): void
{
global $listeners;
foreach ($events as $event) {
$handlers = $listeners[\get_class($event)] ?? [];
foreach ($handlers as $handler) {
$handler($event);
}
}
}
function handle(array $commands): void
{
global $handlers;
foreach ($commands as $command) {
$handler = $handlers[\get_class($command)] ?? null;
if (true === \is_callable($handler)) {
$handler($command);
}
}
}
$registration = Registration::start('Eric');
foreach (Registration::subscribe() as $event) {
$listeners[$event][] = [$registration, 'transition'];
}
$command = new Command\ChangeUserName();
$command->id = (string) $registration->getID();
$command->name = 'Greg';
handle($registration->pullCommands());
handle([$command]);