diff --git a/src/Models/Attributes/DispatchesOn.php b/src/Models/Attributes/DispatchesOn.php new file mode 100644 index 0000000..e75c574 --- /dev/null +++ b/src/Models/Attributes/DispatchesOn.php @@ -0,0 +1,20 @@ +|null */ + private static ?array $classAttributes = []; public function initializeVirtue(): void { @@ -26,6 +28,7 @@ public function initializeVirtue(): void $this->applyFillable(); $this->applyHidden(); $this->applyCasts(); + $this->handleEvents(); self::handleRelationsKeys($this); } @@ -119,6 +122,29 @@ private function applyCasts(): void } } + private function handleEvents(): void + { + $dispatchesAttributes = $this->resolveMultipleAttributes(DispatchesOn::class); + if ($dispatchesAttributes->isEmpty()) { + return; + } + + $eventsArray = []; + foreach ($dispatchesAttributes as $dispatchesAttribute) { + /** @var DispatchesOn $attribute */ + $attribute = $dispatchesAttribute->newInstance(); + if (! in_array($attribute->event, $this->getObservableEvents())) { + continue; + } + + $eventsArray[$attribute->event] = $attribute->class; + } + + if ($eventsArray !== []) { + $this->dispatchesEvents = $eventsArray; + } + } + /** * @param class-string $attributeClass */ @@ -139,11 +165,12 @@ private function resolveMultipleAttributes(string $attributeClass): Collection private function classAttributes(): Collection { - if (is_null($this->classAttributes)) { + $class = static::class; + if (! array_key_exists($class, self::$classAttributes) || is_null(self::$classAttributes[$class])) { $reflectionClass = new ReflectionClass(static::class); - $this->classAttributes = Collection::make($reflectionClass->getAttributes()); + self::$classAttributes[$class] = Collection::make($reflectionClass->getAttributes()); } - return $this->classAttributes; + return self::$classAttributes[$class]; } } diff --git a/tests/Datasets/UserCreated.php b/tests/Datasets/UserCreated.php new file mode 100644 index 0000000..3f953c5 --- /dev/null +++ b/tests/Datasets/UserCreated.php @@ -0,0 +1,19 @@ + 10, + 'name' => fake()->name, + 'email' => fake()->unique()->safeEmail, + 'password' => 's3Cr3t@!!!', + ]); + Event::assertDispatched(UserCreated::class); + + $user->name = fake()->name; + $user->save(); + Event::assertDispatched(UserUpdated::class); + + $user->delete(); + Event::assertDispatched(UserDeleted::class); +});