1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ByTIC\EventDispatcher\Queue\Dispatcher; |
4
|
|
|
|
5
|
|
|
use ByTIC\EventDispatcher\Queue\Listeners\CallQueuedListener; |
6
|
|
|
use ByTIC\EventDispatcher\Queue\Listeners\ShouldQueue; |
7
|
|
|
use Closure; |
8
|
|
|
use Exception; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Trait QueuedListenerTrait |
13
|
|
|
* @package ByTIC\EventDispatcher\ListenerProviders\Traits |
14
|
|
|
*/ |
15
|
|
|
trait QueuedListenerTrait |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* Determine if the event handler class should be queued. |
19
|
|
|
* |
20
|
|
|
* @param string $class |
21
|
|
|
* @return bool |
22
|
|
|
*/ |
23
|
|
|
protected function handlerShouldBeQueued($class): bool |
24
|
|
|
{ |
25
|
|
|
try { |
26
|
|
|
return (new ReflectionClass($class))->implementsInterface( |
27
|
|
|
ShouldQueue::class |
28
|
|
|
); |
29
|
|
|
} catch (Exception $e) { |
30
|
|
|
return false; |
31
|
|
|
} |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Create a callable for putting an event handler on the queue. |
36
|
|
|
* |
37
|
|
|
* @param string $class Listener class |
38
|
|
|
* @param string $method |
39
|
|
|
* @return Closure |
40
|
|
|
*/ |
41
|
|
|
protected function createQueuedHandlerCallable(string $class, string $method): Closure |
42
|
|
|
{ |
43
|
|
|
return function ($event) use ($class, $method) { |
44
|
|
|
// $arguments = array_map(function ($a) { |
45
|
|
|
// return is_object($a) ? clone $a : $a; |
46
|
|
|
// }, func_get_args()); |
47
|
|
|
|
48
|
|
|
if ($this->handlerWantsToBeQueued($class, $event)) { |
49
|
|
|
$this->queueHandler($class, $method, $event); |
50
|
|
|
} |
51
|
|
|
}; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Determine if the event handler wants to be queued. |
56
|
|
|
* |
57
|
|
|
* @param string $class |
58
|
|
|
* @param mixed $event |
59
|
|
|
* @return bool |
60
|
|
|
*/ |
61
|
|
|
protected function handlerWantsToBeQueued(string $class, $event): bool |
62
|
|
|
{ |
63
|
|
|
if (method_exists($class, 'shouldQueue')) { |
64
|
|
|
$listener = new $class(); |
65
|
|
|
/** @noinspection PhpUndefinedMethodInspection */ |
66
|
|
|
return $listener->shouldQueue($event); |
67
|
|
|
} |
68
|
|
|
return true; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Queue the handler class. |
73
|
|
|
* |
74
|
|
|
* @param string $class |
75
|
|
|
* @param string $method |
76
|
|
|
* @param mixed $event |
77
|
|
|
* @return void |
78
|
|
|
*/ |
79
|
|
|
protected function queueHandler($class, $method, $event) |
80
|
|
|
{ |
81
|
|
|
$listener = new CallQueuedListener(); |
82
|
|
|
$listener->setListener([$class, $method]); |
83
|
|
|
$listener->handle($event); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|