Completed
Push — master ( a71bd7...d6582d )
by Alex
15s queued 13s
created

LazyListener   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
eloc 35
c 2
b 0
f 0
dl 0
loc 83
ccs 27
cts 27
cp 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Arp\EventDispatcher\Listener;
6
7
use Arp\EventDispatcher\Listener\Exception\EventListenerException;
8
9
class LazyListener
10
{
11
    private object $factory;
12
13
    private string $factoryMethodName = '__invoke';
14
15
    private string $listenerMethodName = '__invoke';
16
17
    public function __construct(
18
        callable|object $factory,
19
        ?string $factoryMethodName = null,
20
        ?string $listenerMethodName = null,
21
    ) {
22
        if (is_callable($factory)) {
23
            $this->factory = $factory(...);
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ')' on line 23 at column 41
Loading history...
24
        } elseif (is_object($factory)) {
25
            $this->factory = $factory;
26
        }
27
28
        $this->factoryMethodName = $factoryMethodName ?? $this->factoryMethodName;
29
        $this->listenerMethodName = $listenerMethodName ?? $this->listenerMethodName;
30
    }
31
32
    /**
33
     * @throws EventListenerException
34
     */
35
    public function __invoke(object $event): mixed
36
    {
37 9
        $factory = is_callable($this->factory)
38
            ? $this->factory
39 9
            : [$this->factory, $this->factoryMethodName];
40 3
41 6
        if (is_callable($factory)) {
42 3
            $listener = $factory();
43
        } else {
44 3
            throw new EventListenerException(
45 3
                sprintf(
46
                    'The method \'%s\' is not callable for lazy load factory \'%s\'',
47 3
                    $this->factoryMethodName,
48
                    gettype($factory)
49
                )
50
            );
51
        }
52
53 6
        $listener = is_callable($listener) ? $listener : [$listener, $this->listenerMethodName];
54 6
        if (!is_callable($listener)) {
55
            throw new EventListenerException(
56
                sprintf(
57
                    'The method \'%s\' is not callable for lazy load event listener \'%s\'',
58
                    $this->listenerMethodName,
59
                    gettype($listener)
60
                )
61
            );
62
        }
63
64
        return $listener($event);
65
    }
66
}
67