Debian Codegraph @

lib/3rdParty/composer/illuminate/support/Testing/Fakes/EventFake.php

raw symbols SCIP
1 <?php
2
3 namespace Illuminate\Support\Testing\Fakes;
4
5 use Closure;
6 use Illuminate\Container\Container;
7 use Illuminate\Contracts\Events\Dispatcher;
8 use Illuminate\Contracts\Events\ShouldDispatchAfterCommit;
9 use Illuminate\Support\Arr;
10 use Illuminate\Support\Collection;
11 use Illuminate\Support\Str;
12 use Illuminate\Support\Traits\ForwardsCalls;
13 use Illuminate\Support\Traits\ReflectsClosures;
14 use PHPUnit\Framework\Assert as PHPUnit;
15 use ReflectionFunction;
16
17 class EventFake implements Dispatcher, Fake
18 {
19 use ForwardsCalls, ReflectsClosures;
20
21 /**
22 * The original event dispatcher.
23 *
24 * @var \Illuminate\Contracts\Events\Dispatcher
25 */
26 public $dispatcher;
27
28 /**
29 * The event types that should be intercepted instead of dispatched.
30 *
31 * @var array
32 */
33 protected $eventsToFake = [];
34
35 /**
36 * The event types that should be dispatched instead of intercepted.
37 *
38 * @var array
39 */
40 protected $eventsToDispatch = [];
41
42 /**
43 * All of the events that have been intercepted keyed by type.
44 *
45 * @var array
46 */
47 protected $events = [];
48
49 /**
50 * Create a new event fake instance.
51 *
52 * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
53 * @param array|string $eventsToFake
54 */
55 public function __construct(Dispatcher $dispatcher, $eventsToFake = [])
56 {
57 $this->dispatcher = $dispatcher;
58
59 $this->eventsToFake = Arr::wrap($eventsToFake);
60 }
61
62 /**
63 * Specify the events that should be dispatched instead of faked.
64 *
65 * @param array|string $eventsToDispatch
66 * @return $this
67 */
68 public function except($eventsToDispatch)
69 {
70 $this->eventsToDispatch = array_merge(
71 $this->eventsToDispatch,
72 Arr::wrap($eventsToDispatch)
73 );
74
75 return $this;
76 }
77
78 /**
79 * Assert if an event has a listener attached to it.
80 *
81 * @param string $expectedEvent
82 * @param string|array $expectedListener
83 * @return void
84 */
85 public function assertListening($expectedEvent, $expectedListener)
86 {
87 foreach ($this->dispatcher->getListeners($expectedEvent) as $listenerClosure) {
88 $actualListener = (new ReflectionFunction($listenerClosure))
89 ->getStaticVariables()['listener'];
90
91 $normalizedListener = $expectedListener;
92
93 if (is_string($actualListener) && Str::contains($actualListener, '@')) {
94 $actualListener = Str::parseCallback($actualListener);
95
96 if (is_string($expectedListener)) {
97 if (Str::contains($expectedListener, '@')) {
98 $normalizedListener = Str::parseCallback($expectedListener);
99 } else {
100 $normalizedListener = [
101 $expectedListener,
102 method_exists($expectedListener, 'handle') ? 'handle' : '__invoke',
103 ];
104 }
105 }
106 }
107
108 if ($actualListener === $normalizedListener ||
109 ($actualListener instanceof Closure &&
110 $normalizedListener === Closure::class)) {
111 PHPUnit::assertTrue(true);
112
113 return;
114 }
115 }
116
117 PHPUnit::assertTrue(
118 false,
119 sprintf(
120 'Event [%s] does not have the [%s] listener attached to it',
121 $expectedEvent,
122 print_r($expectedListener, true)
123 )
124 );
125 }
126
127 /**
128 * Assert if an event was dispatched based on a truth-test callback.
129 *
130 * @param string|\Closure $event
131 * @param callable|int|null $callback
132 * @return void
133 */
134 public function assertDispatched($event, $callback = null)
135 {
136 if ($event instanceof Closure) {
137 [$event, $callback] = [$this->firstClosureParameterType($event), $event];
138 }
139
140 if (is_int($callback)) {
141 return $this->assertDispatchedTimes($event, $callback);
142 }
143
144 PHPUnit::assertTrue(
145 $this->dispatched($event, $callback)->count() > 0,
146 "The expected [{$event}] event was not dispatched."
147 );
148 }
149
150 /**
151 * Assert if an event was dispatched exactly once.
152 *
153 * @param string $event
154 * @return void
155 */
156 public function assertDispatchedOnce($event)
157 {
158 $this->assertDispatchedTimes($event, 1);
159 }
160
161 /**
162 * Assert if an event was dispatched a number of times.
163 *
164 * @param string $event
165 * @param int $times
166 * @return void
167 */
168 public function assertDispatchedTimes($event, $times = 1)
169 {
170 $count = $this->dispatched($event)->count();
171
172 PHPUnit::assertSame(
173 $times, $count,
174 sprintf(
175 "The expected [{$event}] event was dispatched {$count} %s instead of {$times} %s.",
176 Str::plural('time', $count),
177 Str::plural('time', $times)
178 )
179 );
180 }
181
182 /**
183 * Determine if an event was dispatched based on a truth-test callback.
184 *
185 * @param string|\Closure $event
186 * @param callable|null $callback
187 * @return void
188 */
189 public function assertNotDispatched($event, $callback = null)
190 {
191 if ($event instanceof Closure) {
192 [$event, $callback] = [$this->firstClosureParameterType($event), $event];
193 }
194
195 PHPUnit::assertCount(
196 0, $this->dispatched($event, $callback),
197 "The unexpected [{$event}] event was dispatched."
198 );
199 }
200
201 /**
202 * Assert that no events were dispatched.
203 *
204 * @return void
205 */
206 public function assertNothingDispatched()
207 {
208 $count = count(Arr::flatten($this->events));
209
210 $eventNames = (new Collection($this->events))
211 ->map(fn ($events, $eventName) => sprintf(
212 '%s dispatched %s %s',
213 $eventName,
214 count($events),
215 Str::plural('time', count($events)),
216 ))
217 ->join("\n- ");
218
219 PHPUnit::assertSame(
220 0, $count,
221 "{$count} unexpected events were dispatched:\n\n- $eventNames\n"
222 );
223 }
224
225 /**
226 * Get all of the events matching a truth-test callback.
227 *
228 * @param string $event
229 * @param callable|null $callback
230 * @return \Illuminate\Support\Collection
231 */
232 public function dispatched($event, $callback = null)
233 {
234 if (! $this->hasDispatched($event)) {
235 return new Collection;
236 }
237
238 $callback = $callback ?: fn () => true;
239
240 return (new Collection($this->events[$event]))->filter(
241 fn ($arguments) => $callback(...$arguments)
242 );
243 }
244
245 /**
246 * Determine if the given event has been dispatched.
247 *
248 * @param string $event
249 * @return bool
250 */
251 public function hasDispatched($event)
252 {
253 return isset($this->events[$event]) && ! empty($this->events[$event]);
254 }
255
256 /**
257 * Register an event listener with the dispatcher.
258 *
259 * @param \Closure|string|array $events
260 * @param mixed $listener
261 * @return void
262 */
263 public function listen($events, $listener = null)
264 {
265 $this->dispatcher->listen($events, $listener);
266 }
267
268 /**
269 * Determine if a given event has listeners.
270 *
271 * @param string $eventName
272 * @return bool
273 */
274 public function hasListeners($eventName)
275 {
276 return $this->dispatcher->hasListeners($eventName);
277 }
278
279 /**
280 * Register an event and payload to be dispatched later.
281 *
282 * @param string $event
283 * @param array $payload
284 * @return void
285 */
286 public function push($event, $payload = [])
287 {
288 //
289 }
290
291 /**
292 * Register an event subscriber with the dispatcher.
293 *
294 * @param object|string $subscriber
295 * @return void
296 */
297 public function subscribe($subscriber)
298 {
299 $this->dispatcher->subscribe($subscriber);
300 }
301
302 /**
303 * Flush a set of pushed events.
304 *
305 * @param string $event
306 * @return void
307 */
308 public function flush($event)
309 {
310 //
311 }
312
313 /**
314 * Fire an event and call the listeners.
315 *
316 * @param string|object $event
317 * @param mixed $payload
318 * @param bool $halt
319 * @return array|null
320 */
321 public function dispatch($event, $payload = [], $halt = false)
322 {
323 $name = is_object($event) ? get_class($event) : (string) $event;
324
325 if ($this->shouldFakeEvent($name, $payload)) {
326 $this->fakeEvent($event, $name, func_get_args());
327 } else {
328 return $this->dispatcher->dispatch($event, $payload, $halt);
329 }
330 }
331
332 /**
333 * Determine if an event should be faked or actually dispatched.
334 *
335 * @param string $eventName
336 * @param mixed $payload
337 * @return bool
338 */
339 protected function shouldFakeEvent($eventName, $payload)
340 {
341 if ($this->shouldDispatchEvent($eventName, $payload)) {
342 return false;
343 }
344
345 if (empty($this->eventsToFake)) {
346 return true;
347 }
348
349 return (new Collection($this->eventsToFake))
350 ->filter(function ($event) use ($eventName, $payload) {
351 return $event instanceof Closure
352 ? $event($eventName, $payload)
353 : $event === $eventName;
354 })
355 ->isNotEmpty();
356 }
357
358 /**
359 * Push the event onto the fake events array immediately or after the next database transaction.
360 *
361 * @param string|object $event
362 * @param string $name
363 * @param array $arguments
364 * @return void
365 */
366 protected function fakeEvent($event, $name, $arguments)
367 {
368 if ($event instanceof ShouldDispatchAfterCommit && Container::getInstance()->bound('db.transactions')) {
369 return Container::getInstance()->make('db.transactions')
370 ->addCallback(fn () => $this->events[$name][] = $arguments);
371 }
372
373 $this->events[$name][] = $arguments;
374 }
375
376 /**
377 * Determine whether an event should be dispatched or not.
378 *
379 * @param string $eventName
380 * @param mixed $payload
381 * @return bool
382 */
383 protected function shouldDispatchEvent($eventName, $payload)
384 {
385 if (empty($this->eventsToDispatch)) {
386 return false;
387 }
388
389 return (new Collection($this->eventsToDispatch))
390 ->filter(function ($event) use ($eventName, $payload) {
391 return $event instanceof Closure
392 ? $event($eventName, $payload)
393 : $event === $eventName;
394 })
395 ->isNotEmpty();
396 }
397
398 /**
399 * Remove a set of listeners from the dispatcher.
400 *
401 * @param string $event
402 * @return void
403 */
404 public function forget($event)
405 {
406 //
407 }
408
409 /**
410 * Forget all of the queued listeners.
411 *
412 * @return void
413 */
414 public function forgetPushed()
415 {
416 //
417 }
418
419 /**
420 * Dispatch an event and call the listeners.
421 *
422 * @param string|object $event
423 * @param mixed $payload
424 * @return mixed
425 */
426 public function until($event, $payload = [])
427 {
428 return $this->dispatch($event, $payload, true);
429 }
430
431 /**
432 * Get the events that have been dispatched.
433 *
434 * @return array
435 */
436 public function dispatchedEvents()
437 {
438 return $this->events;
439 }
440
441 /**
442 * Handle dynamic method calls to the dispatcher.
443 *
444 * @param string $method
445 * @param array $parameters
446 * @return mixed
447 */
448 public function __call($method, $parameters)
449 {
450 return $this->forwardCallTo($this->dispatcher, $method, $parameters);
451 }
452 }