Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | namespace LdapRecord\Models\Concerns; |
| 4 | |
| 5 | use Closure; |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 6 | use LdapRecord\Events\NullDispatcher; |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 7 | use LdapRecord\Models\Events\Event; |
| 8 | |
| 9 | trait HasEvents |
| 10 | { |
| 11 | /** |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 12 | * Execute the callback without raising any events. |
| 13 | * |
| 14 | * @param Closure $callback |
| 15 | * |
| 16 | * @return mixed |
| 17 | */ |
| 18 | protected static function withoutEvents(Closure $callback) |
| 19 | { |
| 20 | $container = static::getConnectionContainer(); |
| 21 | |
| 22 | $dispatcher = $container->getEventDispatcher(); |
| 23 | |
| 24 | if ($dispatcher) { |
| 25 | $container->setEventDispatcher( |
| 26 | new NullDispatcher($dispatcher) |
| 27 | ); |
| 28 | } |
| 29 | |
| 30 | try { |
| 31 | return $callback(); |
| 32 | } finally { |
| 33 | if ($dispatcher) { |
| 34 | $container->setEventDispatcher($dispatcher); |
| 35 | } |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | /** |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 40 | * Fires the specified model event. |
| 41 | * |
| 42 | * @param Event $event |
| 43 | * |
| 44 | * @return mixed |
| 45 | */ |
| 46 | protected function fireModelEvent(Event $event) |
| 47 | { |
| 48 | return static::getConnectionContainer()->getEventDispatcher()->fire($event); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Listens to a model event. |
| 53 | * |
| 54 | * @param string $event |
| 55 | * @param Closure $listener |
| 56 | * |
| 57 | * @return mixed |
| 58 | */ |
| 59 | protected function listenForModelEvent($event, Closure $listener) |
| 60 | { |
| 61 | return static::getConnectionContainer()->getEventDispatcher()->listen($event, $listener); |
| 62 | } |
| 63 | } |