1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Arp\EventDispatcher\Listener; |
6
|
|
|
|
7
|
|
|
use Arp\EventDispatcher\Listener\Exception\EventListenerException; |
8
|
|
|
use Arp\Factory\Exception\FactoryException; |
9
|
|
|
use Arp\Factory\FactoryInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @author Alex Patterson <[email protected]> |
13
|
|
|
* @package Arp\EventDispatcher\Listener |
14
|
|
|
*/ |
15
|
|
|
final class LazyListenerConfig extends ListenerConfig |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var string|callable|FactoryInterface |
19
|
|
|
*/ |
20
|
|
|
private $factory; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
private $options; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param FactoryInterface|string $factory |
29
|
|
|
* @param string $eventName |
30
|
|
|
* @param int $priority |
31
|
|
|
* @param array $options |
32
|
|
|
* |
33
|
|
|
* @throws EventListenerException |
34
|
|
|
*/ |
35
|
|
|
public function __construct($factory, string $eventName, int $priority = 1, array $options = []) |
36
|
|
|
{ |
37
|
|
|
if ( |
38
|
|
|
is_callable($factory) |
39
|
|
|
&& !$factory instanceof FactoryInterface |
40
|
|
|
&& !is_a($factory, FactoryInterface::class, true) |
41
|
|
|
) { |
42
|
|
|
throw new EventListenerException( |
43
|
|
|
sprintf( |
44
|
|
|
'The \'listener\' argument must be a \'string\', \'callable\' or an object of type \'%s\'; ' |
45
|
|
|
. '\'%s\' provided in \'%s\'', |
46
|
|
|
FactoryInterface::class, |
47
|
|
|
is_object($factory) ? get_class($factory) : gettype($factory), |
|
|
|
|
48
|
|
|
static::class |
49
|
|
|
) |
50
|
|
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$this->factory = $factory; |
54
|
|
|
$this->options = $options; |
55
|
|
|
|
56
|
|
|
$listener = static function () { |
57
|
|
|
}; |
58
|
|
|
|
59
|
|
|
parent::__construct($listener, $eventName, $priority); |
|
|
|
|
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return callable |
64
|
|
|
* |
65
|
|
|
* @throws EventListenerException |
66
|
|
|
*/ |
67
|
|
|
public function getListener(): callable |
68
|
|
|
{ |
69
|
|
|
$listener = new LazyListener(); |
|
|
|
|
70
|
|
|
|
71
|
|
|
$listener = $this->listener; |
72
|
|
|
$factory = $this->factory; |
73
|
|
|
|
74
|
|
|
try { |
75
|
|
|
if (is_string($factory)) { |
76
|
|
|
$this->factory = $factory = new $factory(); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
if ($factory instanceof FactoryInterface) { |
80
|
|
|
$this->listener = $listener = $factory->create($this->options); |
81
|
|
|
} |
82
|
|
|
} catch (FactoryException $e) { |
83
|
|
|
throw new EventListenerException( |
84
|
|
|
sprintf( |
85
|
|
|
'Failed to lazy load the event listener from factory class \'%s\': %s', |
86
|
|
|
get_class($factory), |
|
|
|
|
87
|
|
|
$e->getMessage() |
88
|
|
|
), |
89
|
|
|
$e->getCode(), |
90
|
|
|
$e |
91
|
|
|
); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
return $listener; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|