|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Yiisoft\ActiveRecord\Event; |
| 6 | + |
| 7 | +use Psr\EventDispatcher\StoppableEventInterface; |
| 8 | +use Yiisoft\ActiveRecord\ActiveRecordInterface; |
| 9 | + |
| 10 | +/** |
| 11 | + * Base class for events in Active Record models. |
| 12 | + */ |
| 13 | +abstract class AbstractEvent implements StoppableEventInterface |
| 14 | +{ |
| 15 | + /** @var bool Whether the default action of the event should be prevented. */ |
| 16 | + private bool $isDefaultPrevented = false; |
| 17 | + /** @var bool Whether the propagation of the event should be stopped. */ |
| 18 | + private bool $isPropagationStopped = false; |
| 19 | + /** @var mixed The return value if the default action is prevented. */ |
| 20 | + private mixed $returnValue = null; |
| 21 | + |
| 22 | + /** |
| 23 | + * @param ActiveRecordInterface $model The target model associated with this event. |
| 24 | + */ |
| 25 | + public function __construct( |
| 26 | + public readonly ActiveRecordInterface $model, |
| 27 | + ) { |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Returns the value that will be returned by the method that triggered this event |
| 32 | + * if the {@see isDefaultPrevented() default action is prevented}. |
| 33 | + */ |
| 34 | + public function getReturnValue(): mixed |
| 35 | + { |
| 36 | + return $this->returnValue; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Checks if the default action associated with this event has been prevented. |
| 41 | + */ |
| 42 | + public function isDefaultPrevented(): bool |
| 43 | + { |
| 44 | + return $this->isDefaultPrevented; |
| 45 | + } |
| 46 | + |
| 47 | + public function isPropagationStopped(): bool |
| 48 | + { |
| 49 | + return $this->isPropagationStopped; |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * Prevents the default action associated with this event from being executed. |
| 54 | + * |
| 55 | + * @see returnValue() |
| 56 | + */ |
| 57 | + public function preventDefault(): void |
| 58 | + { |
| 59 | + $this->isDefaultPrevented = true; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Sets the return value which will be returned by the method that triggered this event |
| 64 | + * if the {@see isDefaultPrevented() default action is prevented}. |
| 65 | + * |
| 66 | + * @see preventDefault() |
| 67 | + */ |
| 68 | + public function returnValue(mixed $returnValue): void |
| 69 | + { |
| 70 | + $this->returnValue = $returnValue; |
| 71 | + } |
| 72 | + |
| 73 | + /** |
| 74 | + * Stops the propagation of the event to further listeners. |
| 75 | + * No further listeners will be notified after this method is called. |
| 76 | + */ |
| 77 | + public function stopPropagation(): void |
| 78 | + { |
| 79 | + $this->isPropagationStopped = true; |
| 80 | + } |
| 81 | +} |
0 commit comments