|
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(...); |
|
|
|
|
|
|
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
|
|
|
|