Skip to content

Commit

Permalink
Allow faking only specific events (#19429)
Browse files Browse the repository at this point in the history
* Allow faking only specific events

* Update EventFake.php

* Update EventFake.php

* Update EventFake.php

* Update EventFake.php

* Update Event.php
  • Loading branch information
adamwathan authored and taylorotwell committed Jun 1, 2017
1 parent f8681bd commit fd39889
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/Illuminate/Support/Facades/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ class Event extends Facade
/**
* Replace the bound instance with a fake.
*
* @param array|string $eventsToFake
* @return void
*/
public static function fake()
public static function fake($eventsToFake = [])
{
static::swap($fake = new EventFake);
static::swap($fake = new EventFake(static::getFacadeRoot(), $eventsToFake));

Model::setEventDispatcher($fake);
}
Expand Down
48 changes: 46 additions & 2 deletions src/Illuminate/Support/Testing/Fakes/EventFake.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,47 @@

namespace Illuminate\Support\Testing\Fakes;

use Illuminate\Support\Arr;
use PHPUnit\Framework\Assert as PHPUnit;
use Illuminate\Contracts\Events\Dispatcher;

class EventFake implements Dispatcher
{
/**
* All of the events that have been dispatched keyed by type.
* The original event dispatcher.
*
* @var \Illuminate\Contracts\Events\Dispatcher
*/
protected $dispatcher;

/**
* The event types that should be intercepted instead of dispatched.
*
* @var array
*/
protected $eventsToFake;

/**
* All of the events that have been intercepted keyed by type.
*
* @var array
*/
protected $events = [];

/**
* Create a new event fake instance.
*
* @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
* @param array|string $eventsToFake
* @return void
*/
public function __construct(Dispatcher $dispatcher, $eventsToFake = [])
{
$this->dispatcher = $dispatcher;

$this->eventsToFake = Arr::wrap($eventsToFake);
}

/**
* Assert if an event was dispatched based on a truth-test callback.
*
Expand Down Expand Up @@ -159,7 +188,22 @@ public function dispatch($event, $payload = [], $halt = false)
{
$name = is_object($event) ? get_class($event) : (string) $event;

$this->events[$name][] = func_get_args();
if ($this->shouldFakeEvent($name)) {
$this->events[$name][] = func_get_args();
} else {
$this->dispatcher->dispatch($event, $payload, $halt);
}
}

/**
* Determine if an event should be faked or actually dispatched.
*
* @param string $eventName
* @return bool
*/
protected function shouldFakeEvent($eventName)
{
return empty($this->eventsToFake) || in_array($eventName, $this->eventsToFake);
}

/**
Expand Down

0 comments on commit fd39889

Please sign in to comment.