Skip to content

Commit 21ca920

Browse files
committed
qa: provide tests for RandomizedListenerProvider
Adds RandomizedListenerProviderTest, to test the behavior of the class. Refactors the internals to use a combination of `shuffle` and `yield from` instead of looping + `array_rand()`.
1 parent ca0d60a commit 21ca920

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

src/ListenerProvider/RandomizedListenerProvider.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
class 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
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
 (0)