|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Onoi\EventDispatcher\Listener; |
|
4
|
|
|
|
|
5
|
|
|
use Onoi\EventDispatcher\EventListener; |
|
6
|
|
|
use Onoi\EventDispatcher\EventListenerCollection; |
|
7
|
|
|
use RuntimeException; |
|
8
|
|
|
use InvalidArgumentException; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* @license GNU GPL v2+ |
|
12
|
|
|
* @since 1.0 |
|
13
|
|
|
* |
|
14
|
|
|
* @author mwjames |
|
15
|
|
|
*/ |
|
16
|
|
|
class GenericEventListenerCollection implements EventListenerCollection { |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* @var array |
|
20
|
|
|
*/ |
|
21
|
|
|
private $collection = array(); |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @since 1.0 |
|
25
|
|
|
* |
|
26
|
|
|
* @param string $event |
|
27
|
|
|
* @param EventListener $listener |
|
28
|
|
|
* |
|
29
|
|
|
* @throws InvalidArgumentException |
|
30
|
|
|
*/ |
|
31
|
2 |
|
public function registerListener( $event, EventListener $listener ) { |
|
32
|
|
|
|
|
33
|
2 |
|
if ( !is_string( $event ) ) { |
|
34
|
1 |
|
throw new InvalidArgumentException( "Event is not a string" ); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
1 |
|
$this->addToCollection( $event, $listener ); |
|
38
|
1 |
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* @since 1.0 |
|
42
|
|
|
* |
|
43
|
|
|
* @param string $event |
|
44
|
|
|
* @param Closure|callable $callback |
|
45
|
|
|
* |
|
46
|
|
|
* @throws InvalidArgumentException |
|
47
|
|
|
* @throws RuntimeException |
|
48
|
|
|
*/ |
|
49
|
5 |
|
public function registerCallback( $event, $callback ) { |
|
50
|
|
|
|
|
51
|
5 |
|
if ( !is_string( $event ) ) { |
|
52
|
1 |
|
throw new InvalidArgumentException( "Event is not a string" ); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
4 |
|
if ( !is_callable( $callback ) ) { |
|
56
|
1 |
|
throw new RuntimeException( "Invoked object is not a valid callback or Closure" ); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
3 |
|
$this->addToCollection( $event, new GenericCallbackEventListener( $callback ) ); |
|
60
|
3 |
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* @since 1.0 |
|
64
|
|
|
* |
|
65
|
|
|
* {@inheritDoc} |
|
66
|
|
|
*/ |
|
67
|
4 |
|
public function getCollection() { |
|
68
|
4 |
|
return $this->collection; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
4 |
|
private function addToCollection( $event, EventListener $listener ) { |
|
72
|
|
|
|
|
73
|
4 |
|
$event = strtolower( $event ); |
|
74
|
|
|
|
|
75
|
4 |
|
if ( !isset( $this->collection[$event] ) ) { |
|
76
|
4 |
|
$this->collection[$event] = array(); |
|
77
|
4 |
|
} |
|
78
|
|
|
|
|
79
|
4 |
|
$this->collection[$event][] = $listener; |
|
80
|
4 |
|
} |
|
81
|
|
|
|
|
82
|
|
|
} |
|
83
|
|
|
|