File tree Expand file tree Collapse file tree 2 files changed +38
-5
lines changed Expand file tree Collapse file tree 2 files changed +38
-5
lines changed Original file line number Diff line number Diff line change 1616
1717class RandomizedListenerProvider implements ListenerProviderInterface
1818{
19+ /** @var array<string, callable[]> */
1920 private $ listeners = [];
2021
2122 public function getListenersForEvent (object $ event ) : iterable
@@ -28,11 +29,9 @@ public function getListenersForEvent(object $event) : iterable
2829 }
2930 }
3031
31- while (count ($ listeners )) {
32- $ index = array_rand ($ listeners );
33- yield $ listeners [$ index ];
34- unset($ listeners [$ index ]);
35- }
32+ shuffle ($ listeners );
33+
34+ yield from $ listeners ;
3635 }
3736
3837 public function listen (string $ name , callable $ listener ) : void
Original file line number Diff line number Diff line change 1+ <?php
2+ /**
3+ * @see https://github.com/phly/phly-event-dispatcher for the canonical source repository
4+ * @copyright Copyright (c) 2018-2019 Matthew Weier O'Phinney (https:/mwop.net)
5+ * @license https://github.com/phly/phly-event-dispatcher/blob/master/LICENSE.md New BSD License
6+ */
7+
8+ declare (strict_types=1 );
9+
10+ namespace PhlyTest \EventDispatcher \ListenerProvider ;
11+
12+ use Phly \EventDispatcher \ListenerProvider \RandomizedListenerProvider ;
13+ use PhlyTest \EventDispatcher \TestAsset \TestEvent ;
14+ use PHPUnit \Framework \TestCase ;
15+
16+ class RandomizedListenerProviderTest extends TestCase
17+ {
18+ public function testRandomizesOrderOfListeners ()
19+ {
20+ $ listeners = [];
21+ for ($ i = 0 ; $ i < 10 ; $ i += 1 ) {
22+ $ listeners [] = function (TestEvent $ event ) {
23+ };
24+ }
25+
26+ $ provider = new RandomizedListenerProvider ();
27+ foreach ($ listeners as $ listener ) {
28+ $ provider ->listen (TestEvent::class, $ listener );
29+ }
30+
31+ $ received = iterator_to_array ($ provider ->getListenersForEvent (new TestEvent ()));
32+ $ this ->assertNotSame ($ listeners , $ received );
33+ }
34+ }
You can’t perform that action at this time.
0 commit comments