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|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 (!$factory instanceof FactoryInterface && !is_a($factory, FactoryInterface::class, true)) { |
38
|
|
|
throw new EventListenerException( |
39
|
|
|
sprintf( |
40
|
|
|
'The \'listener\' argument must be a \'string\' or an object of type \'%s\'; ' |
41
|
|
|
. '\'%s\' provided in \'%s\'', |
42
|
|
|
FactoryInterface::class, |
43
|
|
|
is_object($factory) ? get_class($factory) : gettype($factory), |
|
|
|
|
44
|
|
|
static::class |
45
|
|
|
) |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$this->factory = $factory; |
50
|
|
|
$this->options = $options; |
51
|
|
|
|
52
|
|
|
$listener = static function () { |
53
|
|
|
}; |
54
|
|
|
|
55
|
|
|
parent::__construct($listener, $eventName, $priority); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @return callable |
60
|
|
|
* |
61
|
|
|
* @throws EventListenerException |
62
|
|
|
*/ |
63
|
|
|
public function getListener(): callable |
64
|
|
|
{ |
65
|
|
|
$listener = $this->listener; |
66
|
|
|
$factory = $this->factory; |
67
|
|
|
|
68
|
|
|
try { |
69
|
|
|
if (is_string($factory)) { |
70
|
|
|
$this->factory = $factory = new $factory(); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if ($factory instanceof FactoryInterface) { |
74
|
|
|
$this->listener = $listener = $factory->create($this->options); |
75
|
|
|
} |
76
|
|
|
} catch (FactoryException $e) { |
77
|
|
|
throw new EventListenerException( |
78
|
|
|
sprintf( |
79
|
|
|
'Failed to lazy load the event listener from factory class \'%s\': %s', |
80
|
|
|
get_class($factory), |
81
|
|
|
$e->getMessage() |
82
|
|
|
), |
83
|
|
|
$e->getCode(), |
84
|
|
|
$e |
85
|
|
|
); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
return $listener; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|