Dispatcher.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace app\framework\Events;
  3. use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
  4. class Dispatcher extends \Illuminate\Events\Dispatcher
  5. {
  6. /**
  7. * @param $event
  8. * @param $id
  9. * @param array $payload
  10. * @return array
  11. * @throws \ReflectionException
  12. */
  13. public function safeFire($event, $id, $payload = [])
  14. {
  15. // When the given "event" is actually an object we will assume it is an event
  16. // object and use the class as the event name and this event itself as the
  17. // payload to the handler, which makes object based events quite simple.
  18. [$event, $payload] = $this->parseEventAndPayload(
  19. $event, $payload
  20. );
  21. if ($this->shouldBroadcast($payload)) {
  22. $this->broadcastEvent($payload[0]);
  23. }
  24. $responses = [];
  25. $listenerSources = [];
  26. foreach ($this->getListeners($event) as $listener) {
  27. $listenerSource = '';
  28. if ($listener instanceof \Closure) {
  29. $closureObj = new \ReflectionFunction($listener);
  30. if ($closureObj->getClosureThis() instanceof $this) {
  31. $listenerSource = $closureObj->getStaticVariables()['listener'];
  32. } else {
  33. $listenerSource = get_class($closureObj->getClosureThis());
  34. }
  35. }
  36. $listenerSources[] = $listenerSource;
  37. try {
  38. $response = $listener($event, $payload);
  39. }catch (\Exception $exception){
  40. \Log::order()->error($event . '事件监听者抛出异常:' . $id, $exception);
  41. throw $exception;
  42. }
  43. // If a boolean false is returned from a listener, we will stop propagating
  44. // the event to any further listeners down in the chain, else we keep on
  45. // looping through the listeners and firing every one in our sequence.
  46. if ($response === false) {
  47. \Log::order()->error($event . '事件监听者返回false:' . $id, $listenerSource);
  48. }
  49. $responses[] = $response;
  50. }
  51. \Log::order()->info("{$event}事件执行完毕:" . $id, $listenerSources);
  52. return $responses;
  53. }
  54. }