forked from apisearch-io/symfony-async-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncEventDispatcher.php
88 lines (78 loc) · 2.3 KB
/
AsyncEventDispatcher.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
<?php
/*
* This file is part of the Symfony Async Kernel
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <[email protected]>
*/
declare(strict_types=1);
namespace Symfony\Component\HttpKernel;
use React\Promise\FulfilledPromise;
use React\Promise\PromiseInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpKernel\Event\PromiseEvent;
/**
* Class AsyncEventDispatcher.
*/
class AsyncEventDispatcher extends EventDispatcher
{
/**
* Dispatch an event asynchronously.
*
* @param string $eventName
* @param PromiseEvent $event
*
* @return PromiseInterface
*/
public function asyncDispatch(
string $eventName,
PromiseEvent $event
) {
if ($listeners = $this->getListeners($eventName)) {
return $this->doAsyncDispatch($listeners, $eventName, $event);
}
return new FulfilledPromise($event);
}
/**
* Triggers the listeners of an event.
*
* This method can be overridden to add functionality that is executed
* for each listener.
*
* @param callable[] $listeners
* @param string $eventName
* @param PromiseEvent $event
*
* @return PromiseInterface
*/
protected function doAsyncDispatch(
array $listeners,
string $eventName,
PromiseEvent $event
) {
$promise = new FulfilledPromise();
foreach ($listeners as $listener) {
if ($event->isPropagationStopped()) {
break;
}
$result = $listener($event, $eventName, $this);
if (!$result instanceof PromiseInterface) {
$result = new FulfilledPromise($result);
}
$promise = $promise->then(function () use ($result) {
return new FulfilledPromise(function (PromiseEvent $event) use ($result) {
return $event->hasPromise()
? new FulfilledPromise()
: $result;
});
});
}
return $promise->then(function () use ($event) {
return $event;
});
}
}