1
|
|
|
<?php |
2
|
|
|
namespace Yiisoft\EventDispatcher\Tests; |
3
|
|
|
|
4
|
|
|
use PHPUnit\Framework\TestCase; |
5
|
|
|
use Psr\EventDispatcher\ListenerProviderInterface; |
6
|
|
|
use Yiisoft\EventDispatcher\Dispatcher; |
7
|
|
|
use Yiisoft\EventDispatcher\Tests\Event\Event; |
8
|
|
|
use Yiisoft\EventDispatcher\Tests\Event\StoppableEvent; |
9
|
|
|
|
10
|
|
|
class DispatcherTest extends TestCase |
11
|
|
|
{ |
12
|
|
|
public function testCallsAllListeners() |
13
|
|
|
{ |
14
|
|
|
$event = new Event(); |
15
|
|
|
|
16
|
|
View Code Duplication |
$provider = new class implements ListenerProviderInterface |
|
|
|
|
17
|
|
|
{ |
18
|
|
|
public function getListenersForEvent(object $event): iterable |
19
|
|
|
{ |
20
|
|
|
yield function (Event $event) { |
21
|
|
|
$event->register(1); |
22
|
|
|
}; |
23
|
|
|
yield function (Event $event) { |
24
|
|
|
$event->register(2); |
25
|
|
|
}; |
26
|
|
|
yield function (Event $event) { |
27
|
|
|
$event->register(3); |
28
|
|
|
}; |
29
|
|
|
} |
30
|
|
|
}; |
31
|
|
|
|
32
|
|
|
$dispatcher = new Dispatcher($provider); |
33
|
|
|
$dispatcher->dispatch($event); |
34
|
|
|
|
35
|
|
|
$this->assertEquals([1, 2, 3], $event->registered()); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function testPropagationStops() |
39
|
|
|
{ |
40
|
|
|
$event = new StoppableEvent(); |
41
|
|
|
|
42
|
|
View Code Duplication |
$provider = new class implements ListenerProviderInterface |
|
|
|
|
43
|
|
|
{ |
44
|
|
|
public function getListenersForEvent(object $event): iterable |
45
|
|
|
{ |
46
|
|
|
yield function (StoppableEvent $event) { |
47
|
|
|
$event->register(1); |
48
|
|
|
$event->stopPropagation(); |
49
|
|
|
}; |
50
|
|
|
yield function (StoppableEvent $event) { |
51
|
|
|
$event->register(2); |
52
|
|
|
}; |
53
|
|
|
yield function (StoppableEvent $event) { |
54
|
|
|
$event->register(3); |
55
|
|
|
}; |
56
|
|
|
} |
57
|
|
|
}; |
58
|
|
|
|
59
|
|
|
$dispatcher = new Dispatcher($provider); |
60
|
|
|
$dispatcher->dispatch($event); |
61
|
|
|
|
62
|
|
|
$this->assertEquals([1], $event->registered()); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.