HasEvents.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Concerns;
  3. use Illuminate\Contracts\Events\Dispatcher;
  4. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  5. use Illuminate\Events\NullDispatcher;
  6. use Illuminate\Support\Arr;
  7. use InvalidArgumentException;
  8. use ReflectionClass;
  9. trait HasEvents
  10. {
  11. /**
  12. * The event map for the model.
  13. *
  14. * Allows for object-based events for native Eloquent events.
  15. *
  16. * @var array
  17. */
  18. protected $dispatchesEvents = [];
  19. /**
  20. * User exposed observable events.
  21. *
  22. * These are extra user-defined events observers may subscribe to.
  23. *
  24. * @var array
  25. */
  26. protected $observables = [];
  27. /**
  28. * Boot the has event trait for a model.
  29. *
  30. * @return void
  31. */
  32. public static function bootHasEvents()
  33. {
  34. static::observe(static::resolveObserveAttributes());
  35. }
  36. /**
  37. * Resolve the observe class names from the attributes.
  38. *
  39. * @return array
  40. */
  41. public static function resolveObserveAttributes()
  42. {
  43. $reflectionClass = new ReflectionClass(static::class);
  44. return collect($reflectionClass->getAttributes(ObservedBy::class))
  45. ->map(fn ($attribute) => $attribute->getArguments())
  46. ->flatten()
  47. ->all();
  48. }
  49. /**
  50. * Register observers with the model.
  51. *
  52. * @param object|array|string $classes
  53. * @return void
  54. *
  55. * @throws \RuntimeException
  56. */
  57. public static function observe($classes)
  58. {
  59. $instance = new static;
  60. foreach (Arr::wrap($classes) as $class) {
  61. $instance->registerObserver($class);
  62. }
  63. }
  64. /**
  65. * Register a single observer with the model.
  66. *
  67. * @param object|string $class
  68. * @return void
  69. *
  70. * @throws \RuntimeException
  71. */
  72. protected function registerObserver($class)
  73. {
  74. $className = $this->resolveObserverClassName($class);
  75. // When registering a model observer, we will spin through the possible events
  76. // and determine if this observer has that method. If it does, we will hook
  77. // it into the model's event system, making it convenient to watch these.
  78. foreach ($this->getObservableEvents() as $event) {
  79. if (method_exists($class, $event)) {
  80. static::registerModelEvent($event, $className.'@'.$event);
  81. }
  82. }
  83. }
  84. /**
  85. * Resolve the observer's class name from an object or string.
  86. *
  87. * @param object|string $class
  88. * @return string
  89. *
  90. * @throws \InvalidArgumentException
  91. */
  92. private function resolveObserverClassName($class)
  93. {
  94. if (is_object($class)) {
  95. return get_class($class);
  96. }
  97. if (class_exists($class)) {
  98. return $class;
  99. }
  100. throw new InvalidArgumentException('Unable to find observer: '.$class);
  101. }
  102. /**
  103. * Get the observable event names.
  104. *
  105. * @return array
  106. */
  107. public function getObservableEvents()
  108. {
  109. return array_merge(
  110. [
  111. 'retrieved', 'creating', 'created', 'updating', 'updated',
  112. 'saving', 'saved', 'restoring', 'restored', 'replicating',
  113. 'deleting', 'deleted', 'forceDeleting', 'forceDeleted',
  114. ],
  115. $this->observables
  116. );
  117. }
  118. /**
  119. * Set the observable event names.
  120. *
  121. * @param array $observables
  122. * @return $this
  123. */
  124. public function setObservableEvents(array $observables)
  125. {
  126. $this->observables = $observables;
  127. return $this;
  128. }
  129. /**
  130. * Add an observable event name.
  131. *
  132. * @param array|mixed $observables
  133. * @return void
  134. */
  135. public function addObservableEvents($observables)
  136. {
  137. $this->observables = array_unique(array_merge(
  138. $this->observables, is_array($observables) ? $observables : func_get_args()
  139. ));
  140. }
  141. /**
  142. * Remove an observable event name.
  143. *
  144. * @param array|mixed $observables
  145. * @return void
  146. */
  147. public function removeObservableEvents($observables)
  148. {
  149. $this->observables = array_diff(
  150. $this->observables, is_array($observables) ? $observables : func_get_args()
  151. );
  152. }
  153. /**
  154. * Register a model event with the dispatcher.
  155. *
  156. * @param string $event
  157. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  158. * @return void
  159. */
  160. protected static function registerModelEvent($event, $callback)
  161. {
  162. if (isset(static::$dispatcher)) {
  163. $name = static::class;
  164. static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback);
  165. }
  166. }
  167. /**
  168. * Fire the given event for the model.
  169. *
  170. * @param string $event
  171. * @param bool $halt
  172. * @return mixed
  173. */
  174. protected function fireModelEvent($event, $halt = true)
  175. {
  176. if (! isset(static::$dispatcher)) {
  177. return true;
  178. }
  179. // First, we will get the proper method to call on the event dispatcher, and then we
  180. // will attempt to fire a custom, object based event for the given event. If that
  181. // returns a result we can return that result, or we'll call the string events.
  182. $method = $halt ? 'until' : 'dispatch';
  183. $result = $this->filterModelEventResults(
  184. $this->fireCustomModelEvent($event, $method)
  185. );
  186. if ($result === false) {
  187. return false;
  188. }
  189. return ! empty($result) ? $result : static::$dispatcher->{$method}(
  190. "eloquent.{$event}: ".static::class, $this
  191. );
  192. }
  193. /**
  194. * Fire a custom model event for the given event.
  195. *
  196. * @param string $event
  197. * @param string $method
  198. * @return mixed|null
  199. */
  200. protected function fireCustomModelEvent($event, $method)
  201. {
  202. if (! isset($this->dispatchesEvents[$event])) {
  203. return;
  204. }
  205. $result = static::$dispatcher->$method(new $this->dispatchesEvents[$event]($this));
  206. if (! is_null($result)) {
  207. return $result;
  208. }
  209. }
  210. /**
  211. * Filter the model event results.
  212. *
  213. * @param mixed $result
  214. * @return mixed
  215. */
  216. protected function filterModelEventResults($result)
  217. {
  218. if (is_array($result)) {
  219. $result = array_filter($result, function ($response) {
  220. return ! is_null($response);
  221. });
  222. }
  223. return $result;
  224. }
  225. /**
  226. * Register a retrieved model event with the dispatcher.
  227. *
  228. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  229. * @return void
  230. */
  231. public static function retrieved($callback)
  232. {
  233. static::registerModelEvent('retrieved', $callback);
  234. }
  235. /**
  236. * Register a saving model event with the dispatcher.
  237. *
  238. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  239. * @return void
  240. */
  241. public static function saving($callback)
  242. {
  243. static::registerModelEvent('saving', $callback);
  244. }
  245. /**
  246. * Register a saved model event with the dispatcher.
  247. *
  248. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  249. * @return void
  250. */
  251. public static function saved($callback)
  252. {
  253. static::registerModelEvent('saved', $callback);
  254. }
  255. /**
  256. * Register an updating model event with the dispatcher.
  257. *
  258. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  259. * @return void
  260. */
  261. public static function updating($callback)
  262. {
  263. static::registerModelEvent('updating', $callback);
  264. }
  265. /**
  266. * Register an updated model event with the dispatcher.
  267. *
  268. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  269. * @return void
  270. */
  271. public static function updated($callback)
  272. {
  273. static::registerModelEvent('updated', $callback);
  274. }
  275. /**
  276. * Register a creating model event with the dispatcher.
  277. *
  278. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  279. * @return void
  280. */
  281. public static function creating($callback)
  282. {
  283. static::registerModelEvent('creating', $callback);
  284. }
  285. /**
  286. * Register a created model event with the dispatcher.
  287. *
  288. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  289. * @return void
  290. */
  291. public static function created($callback)
  292. {
  293. static::registerModelEvent('created', $callback);
  294. }
  295. /**
  296. * Register a replicating model event with the dispatcher.
  297. *
  298. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  299. * @return void
  300. */
  301. public static function replicating($callback)
  302. {
  303. static::registerModelEvent('replicating', $callback);
  304. }
  305. /**
  306. * Register a deleting model event with the dispatcher.
  307. *
  308. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  309. * @return void
  310. */
  311. public static function deleting($callback)
  312. {
  313. static::registerModelEvent('deleting', $callback);
  314. }
  315. /**
  316. * Register a deleted model event with the dispatcher.
  317. *
  318. * @param \Illuminate\Events\QueuedClosure|\Closure|string|array $callback
  319. * @return void
  320. */
  321. public static function deleted($callback)
  322. {
  323. static::registerModelEvent('deleted', $callback);
  324. }
  325. /**
  326. * Remove all the event listeners for the model.
  327. *
  328. * @return void
  329. */
  330. public static function flushEventListeners()
  331. {
  332. if (! isset(static::$dispatcher)) {
  333. return;
  334. }
  335. $instance = new static;
  336. foreach ($instance->getObservableEvents() as $event) {
  337. static::$dispatcher->forget("eloquent.{$event}: ".static::class);
  338. }
  339. foreach (array_values($instance->dispatchesEvents) as $event) {
  340. static::$dispatcher->forget($event);
  341. }
  342. }
  343. /**
  344. * Get the event map for the model.
  345. *
  346. * @return array
  347. */
  348. public function dispatchesEvents()
  349. {
  350. return $this->dispatchesEvents;
  351. }
  352. /**
  353. * Get the event dispatcher instance.
  354. *
  355. * @return \Illuminate\Contracts\Events\Dispatcher
  356. */
  357. public static function getEventDispatcher()
  358. {
  359. return static::$dispatcher;
  360. }
  361. /**
  362. * Set the event dispatcher instance.
  363. *
  364. * @param \Illuminate\Contracts\Events\Dispatcher $dispatcher
  365. * @return void
  366. */
  367. public static function setEventDispatcher(Dispatcher $dispatcher)
  368. {
  369. static::$dispatcher = $dispatcher;
  370. }
  371. /**
  372. * Unset the event dispatcher for models.
  373. *
  374. * @return void
  375. */
  376. public static function unsetEventDispatcher()
  377. {
  378. static::$dispatcher = null;
  379. }
  380. /**
  381. * Execute a callback without firing any model events for any model type.
  382. *
  383. * @param callable $callback
  384. * @return mixed
  385. */
  386. public static function withoutEvents(callable $callback)
  387. {
  388. $dispatcher = static::getEventDispatcher();
  389. if ($dispatcher) {
  390. static::setEventDispatcher(new NullDispatcher($dispatcher));
  391. }
  392. try {
  393. return $callback();
  394. } finally {
  395. if ($dispatcher) {
  396. static::setEventDispatcher($dispatcher);
  397. }
  398. }
  399. }
  400. }