Skip to content

Commit

Permalink
[9.x] Avoid mutating the $expectedLitener between loops on `Event::…
Browse files Browse the repository at this point in the history
…assertListening` (#46095)

* Avoid mutability when normalizing listeners for Event::assertListening

* formatting

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
phcostabh and taylorotwell committed Feb 13, 2023
1 parent d4df356 commit c72459a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
10 changes: 6 additions & 4 deletions src/Illuminate/Support/Testing/Fakes/EventFake.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,21 +85,23 @@ public function assertListening($expectedEvent, $expectedListener)
$actualListener = (new ReflectionFunction($listenerClosure))
->getStaticVariables()['listener'];

$normalizedListener = $expectedListener;

if (is_string($actualListener) && Str::contains($actualListener, '@')) {
$actualListener = Str::parseCallback($actualListener);

if (is_string($expectedListener)) {
if (Str::contains($expectedListener, '@')) {
$expectedListener = Str::parseCallback($expectedListener);
$normalizedListener = Str::parseCallback($expectedListener);
} else {
$expectedListener = [$expectedListener, 'handle'];
$normalizedListener = [$expectedListener, 'handle'];
}
}
}

if ($actualListener === $expectedListener ||
if ($actualListener === $normalizedListener ||
($actualListener instanceof Closure &&
$expectedListener === Closure::class)) {
$normalizedListener === Closure::class)) {
PHPUnit::assertTrue(true);

return;
Expand Down
18 changes: 14 additions & 4 deletions tests/Integration/Events/EventFakeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Closure;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;
use Orchestra\Testbench\TestCase;
Expand Down Expand Up @@ -140,11 +141,20 @@ public function testEventsListedInExceptAreProperlyDispatched()
public function testAssertListening()
{
Event::fake();
Event::listen('event', 'listener');
Event::listen('event', PostEventSubscriber::class);
Event::listen('event', 'Illuminate\\Tests\\Integration\\Events\\PostAutoEventSubscriber@handle');
Event::listen('event', [PostEventSubscriber::class, 'foo']);

$listenersOfSameEventInRandomOrder = Arr::shuffle([
'listener',
'Illuminate\\Tests\\Integration\\Events\\PostAutoEventSubscriber@handle',
PostEventSubscriber::class,
[PostEventSubscriber::class, 'foo'],
]);

foreach ($listenersOfSameEventInRandomOrder as $listener) {
Event::listen('event', $listener);
}

Event::subscribe(PostEventSubscriber::class);

Event::listen(function (NonImportantEvent $event) {
// do something
});
Expand Down

0 comments on commit c72459a

Please sign in to comment.