Passed
Push — master ( 69d06b...aefa73 )
by Gabriel
06:27 queued 12s
created

QueuedListenerTrait::createQueuedHandlerCallable()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 1
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
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