Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix PrioritizedListenersForEvent when OneTimeListener added #101

Merged
merged 1 commit into from Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/PrioritizedListenersForEvent.php
Expand Up @@ -48,6 +48,7 @@ public function getListeners(): iterable
private function sortListeners(): void
{
$this->isSorted = true;
$this->sortedListeners = [];
krsort($this->listeners, SORT_NUMERIC);

foreach ($this->listeners as $group) {
Expand All @@ -66,7 +67,7 @@ private function removeOneTimeListeners(): void
$this->sortedListeners = array_filter($this->sortedListeners, $filter);

foreach ($this->listeners as $priority => $listeners) {
$this->listeners[$priority] = array_filter($this->sortedListeners, $filter);
$this->listeners[$priority] = array_filter($listeners, $filter);
}
}
}
42 changes: 42 additions & 0 deletions src/PrioritizedListenersForEventTest.php
@@ -0,0 +1,42 @@
<?php

namespace League\Event;

use PHPUnit\Framework\TestCase;

class PrioritizedListenersForEventTest extends TestCase
{
public function testOneTimeListener(): void
{
$group = new PrioritizedListenersForEvent();
$group->addListener(function () {
return 1;
}, 1);
$group->addListener(function () {
return 2;
}, 2);
$group->addListener(new OneTimeListener(function () {
return 3;
}), 3);
$listener1 = $group->getListeners();
$this->assertCount(3, $listener1);
$this->assertEquals([null, 2, 1], self::inspectListener($listener1));

$group->addListener(function () {
return 4;
}, 4);
$listener2 = $group->getListeners();
$this->assertCount(3, $listener2);
$this->assertEquals([4, 2, 1], self::inspectListener($listener2));
}

public static function inspectListener(iterable $listeners): array
{
$event = new \stdClass();
$ret = [];
foreach ($listeners as $listener) {
$ret[] = $listener($event);
}
return $ret;
}
}