From 31f3e39c84ceea7fe8635416ccca83846e2d9a70 Mon Sep 17 00:00:00 2001 From: Rias Date: Thu, 22 Jan 2026 16:45:35 +0100 Subject: [PATCH 1/3] Remove unnecessary hasListener checks --- src/Address/Addresses.php | 41 +---- src/Auth/Auth.php | 43 ++--- src/Auth/UserProvider.php | 17 +- .../Concerns/ConfigurableComponent.php | 14 +- src/Component/Concerns/HasComponentEvents.php | 2 +- src/Component/Concerns/SavableComponent.php | 30 +-- src/Dashboard/Dashboard.php | 38 ++-- src/Database/Commands/MigrateCommand.php | 35 ++-- src/Database/Events/RegisterMigrators.php | 2 +- src/Database/Migrations/Install.php | 5 +- .../Queries/Concerns/CollectsCacheTags.php | 7 +- .../Queries/Concerns/HydratesElements.php | 33 +--- src/Edition.php | 5 +- src/Element/Concerns/Draftable.php | 9 +- src/Element/Drafts.php | 73 ++++---- src/Element/ElementSources.php | 31 ++-- src/Element/Revisions.php | 77 ++++---- src/Entry/Entries.php | 9 +- src/Entry/EntryTypes.php | 20 +- src/Field/Assets.php | 19 +- src/Field/BaseOptionsField.php | 12 +- src/Field/BaseRelationField.php | 15 +- src/Field/Field.php | 174 +++++++----------- src/Field/Fields.php | 65 ++----- src/Field/Link.php | 36 ++-- src/Field/Matrix.php | 28 ++- .../Actions/FireRunEvent.php | 5 +- .../Auth/AuthenticationController.php | 13 +- .../Auth/SetPasswordController.php | 8 +- src/Http/Controllers/Users/EditUserTrait.php | 8 +- .../Users/PermissionsController.php | 9 +- .../Controllers/Users/UsersController.php | 8 +- src/Plugin/Concerns/HasSettings.php | 12 +- src/Plugin/Plugins.php | 57 ++---- src/ProjectConfig/Data/ProjectConfigData.php | 5 +- src/ProjectConfig/ProjectConfig.php | 13 +- src/Route/Routes.php | 37 ++-- src/Section/Sections.php | 21 +-- src/Site/SiteGroups.php | 21 +-- src/Site/Sites.php | 60 ++---- src/Structure/Structures.php | 36 ++-- src/SystemMessage/SystemMessages.php | 8 +- src/Updates/Data/UpdateRelease.php | 12 +- src/User/UserGroups.php | 20 +- src/User/UserPermissions.php | 16 +- src/User/Users.php | 146 ++++++--------- src/Utility/Utilities.php | 8 +- src/Utility/Utilities/AssetIndexes.php | 19 +- src/Utility/Utilities/ClearCaches.php | 15 +- 49 files changed, 475 insertions(+), 922 deletions(-) diff --git a/src/Address/Addresses.php b/src/Address/Addresses.php index 3fa5294b07a..630f1242003 100644 --- a/src/Address/Addresses.php +++ b/src/Address/Addresses.php @@ -29,7 +29,6 @@ use CraftCms\Cms\ProjectConfig\ProjectConfig; use CraftCms\Cms\ProjectConfig\ProjectConfigHelper; use Illuminate\Container\Attributes\Singleton; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; use function CraftCms\Cms\t; @@ -74,13 +73,9 @@ public function getAddressFormatRepository(): AddressFormatRepository */ public function defineAddressSubdivisions(array $parents, array $options = []): array { - if (Event::hasListeners(DefineAddressSubdivisions::class)) { - Event::dispatch($event = new DefineAddressSubdivisions($parents, $options)); + event($event = new DefineAddressSubdivisions($parents, $options)); - return $event->subdivisions; - } - - return $options; + return $event->subdivisions; } /** @@ -91,13 +86,9 @@ public function getCountryList(?string $locale = null): array $locale ??= app()->getLocale(); $countries = $this->countryRepository->getList($locale); - if (Event::hasListeners(DefineAddressCountries::class)) { - Event::dispatch($event = new DefineAddressCountries($locale, $countries)); + event($event = new DefineAddressCountries($locale, $countries)); - return $event->countries; - } - - return $countries; + return $event->countries; } /** @@ -111,13 +102,9 @@ public function getUsedFields(string $countryCode): array { $fields = $this->addressFormatRepository->get($countryCode)->getUsedFields(); - if (Event::hasListeners(DefineAddressUsedFields::class)) { - Event::dispatch($event = new DefineAddressUsedFields($countryCode, $fields)); - - return $event->fields; - } + event($event = new DefineAddressUsedFields($countryCode, $fields)); - return $fields; + return $event->fields; } /** @@ -131,13 +118,9 @@ public function getUsedSubdivisionFields(string $countryCode): array { $fields = $this->addressFormatRepository->get($countryCode)->getUsedSubdivisionFields(); - if (Event::hasListeners(DefineAddressUsedSubdivisionFields::class)) { - Event::dispatch($event = new DefineAddressUsedSubdivisionFields($countryCode, $fields)); - - return $event->fields; - } + event($event = new DefineAddressUsedSubdivisionFields($countryCode, $fields)); - return $fields; + return $event->fields; } /** @@ -164,13 +147,9 @@ public function getFieldLabel(string $field, string $countryCode): string AddressField::FAMILY_NAME => t('Last Name'), }; - if (Event::hasListeners(DefineAddressFieldLabel::class)) { - Event::dispatch($event = new DefineAddressFieldLabel($countryCode, $field, $label)); - - return $event->label; - } + event($event = new DefineAddressFieldLabel($countryCode, $field, $label)); - return $label; + return $event->label; } /** diff --git a/src/Auth/Auth.php b/src/Auth/Auth.php index e37b40e5e35..64466d26bf5 100644 --- a/src/Auth/Auth.php +++ b/src/Auth/Auth.php @@ -25,7 +25,6 @@ use Illuminate\Contracts\Hashing\Hasher; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Cookie; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Session; use InvalidArgumentException; use RuntimeException; @@ -80,11 +79,9 @@ public function getAllMethods(?User $user = null): Collection RecoveryCodes::class, ]); - if (Event::hasListeners(RegisterAuthMethods::class)) { - Event::dispatch(new RegisterAuthMethods($methods)); - } + event($event = new RegisterAuthMethods($methods)); - $this->methods[$user->id] = $methods->map(function (string $class) use ($user) { + $this->methods[$user->id] = $event->methods->map(function (string $class) use ($user) { if (! is_subclass_of($class, AuthMethodInterface::class)) { throw new RuntimeException("$class must implement ".AuthMethodInterface::class); } @@ -237,20 +234,16 @@ public function is2faRequired(User $user): bool public function authenticate(User $user, #[SensitiveParameter] array $credentials): bool { - $this->authError = null; - - if (Event::hasListeners(Authenticating::class)) { - Event::dispatch($event = new Authenticating($credentials)); + event($event = new Authenticating($credentials)); - $this->authError = $event->authError; + $this->authError = $event->authError; - if (isset($this->authError)) { - return false; - } + if (isset($this->authError)) { + return false; + } - if (! $event->performAuthentication) { - return true; - } + if (! $event->performAuthentication) { + return true; } if (is_null($plain = $credentials['password'])) { @@ -288,20 +281,16 @@ public function authenticate(User $user, #[SensitiveParameter] array $credential public function authenticateWithPasskey(User $user, PublicKeyCredentialRequestOptions|array|string $requestOptions, string $response): bool { - $this->authError = null; + event($event = new Authenticating); - if (Event::hasListeners(Authenticating::class)) { - Event::dispatch($event = new Authenticating); + $this->authError = $event->authError; - $this->authError = $event->authError; - - if (isset($this->authError)) { - return false; - } + if (isset($this->authError)) { + return false; + } - if (! $event->performAuthentication) { - return true; - } + if (! $event->performAuthentication) { + return true; } // make sure the passkey exists and belongs to this user diff --git a/src/Auth/UserProvider.php b/src/Auth/UserProvider.php index 1c74cf13c7d..67d06b418a6 100644 --- a/src/Auth/UserProvider.php +++ b/src/Auth/UserProvider.php @@ -14,7 +14,6 @@ use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Hashing\Hasher as HasherContract; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use SensitiveParameter; #[Scoped] @@ -82,21 +81,13 @@ public function retrieveByCredentials(#[SensitiveParameter] array $credentials): $loginName = $credentials['loginName']; - $user = null; - if (Event::hasListeners(RetrievingLoginUser::class)) { - Event::dispatch($event = new RetrievingLoginUser($loginName)); - $user = $event->user; - } - - $user ??= $this->users->getUserByUsernameOrEmail($loginName); + event($event = new RetrievingLoginUser($loginName)); - if (Event::hasListeners(LoginUserRetrieved::class)) { - Event::dispatch($event = new LoginUserRetrieved($loginName, $user)); + $user = $event->user ?? $this->users->getUserByUsernameOrEmail($loginName); - return $event->user; - } + event($event = new LoginUserRetrieved($loginName, $user)); - return $user; + return $event->user; } /** diff --git a/src/Component/Concerns/ConfigurableComponent.php b/src/Component/Concerns/ConfigurableComponent.php index c5e506c5b8f..b304846d1c6 100644 --- a/src/Component/Concerns/ConfigurableComponent.php +++ b/src/Component/Concerns/ConfigurableComponent.php @@ -28,16 +28,12 @@ public function settingsAttributes(): array { $attributes = array_keys(Utils::getPublicProperties($this, fn (ReflectionProperty $property) => $property->class === static::class)); - if ($this->hasComponentListeners(self::EVENT_DEFINE_SETTINGS_ATTRIBUTES)) { - $this->dispatchComponentEvent(self::EVENT_DEFINE_SETTINGS_ATTRIBUTES, $event = new DefineSettingsAttributes( - component: $this, - attributes: $attributes, - )); + $this->dispatchComponentEvent(self::EVENT_DEFINE_SETTINGS_ATTRIBUTES, $event = new DefineSettingsAttributes( + component: $this, + attributes: $attributes, + )); - return $event->attributes; - } - - return $attributes; + return $event->attributes; } public static function onDefineSettingsAttributes(callable $callback): void diff --git a/src/Component/Concerns/HasComponentEvents.php b/src/Component/Concerns/HasComponentEvents.php index 4090b323909..931329668cf 100644 --- a/src/Component/Concerns/HasComponentEvents.php +++ b/src/Component/Concerns/HasComponentEvents.php @@ -37,7 +37,7 @@ public static function componentEventName(string $event, ?string $class = null): public function dispatchComponentEvent(string $event, mixed $payload): void { foreach (static::getClasses() as $class) { - Event::dispatch(self::componentEventName($event, $class), $payload); + event(self::componentEventName($event, $class), $payload); if (property_exists($payload, 'handled') && $payload->handled) { return; diff --git a/src/Component/Concerns/SavableComponent.php b/src/Component/Concerns/SavableComponent.php index 362d4878060..6e41bf7b5a4 100644 --- a/src/Component/Concerns/SavableComponent.php +++ b/src/Component/Concerns/SavableComponent.php @@ -60,11 +60,7 @@ public static function onBeforeSave(QueuedClosure|callable|array|string $callbac public function beforeSave(bool $isNew): bool { - if (! Event::hasListeners(self::componentEventName(self::EVENT_BEFORE_SAVE))) { - return true; - } - - Event::dispatch( + event( self::componentEventName(self::EVENT_BEFORE_SAVE), $event = new ComponentEvent($this, $isNew), ); @@ -82,11 +78,7 @@ public static function onAfterSave(QueuedClosure|callable|array|string $callback */ public function afterSave(bool $isNew): void { - if (! Event::hasListeners(self::componentEventName(self::EVENT_AFTER_SAVE))) { - return; - } - - Event::dispatch(self::componentEventName(self::EVENT_AFTER_SAVE), new ComponentEvent($this, $isNew)); + event(self::componentEventName(self::EVENT_AFTER_SAVE), new ComponentEvent($this, $isNew)); } public static function onBeforeDelete(QueuedClosure|callable|array|string $callback): void @@ -99,11 +91,7 @@ public static function onBeforeDelete(QueuedClosure|callable|array|string $callb */ public function beforeDelete(): bool { - if (! Event::hasListeners(self::componentEventName(self::EVENT_BEFORE_DELETE))) { - return true; - } - - Event::dispatch( + event( self::componentEventName(self::EVENT_BEFORE_DELETE), $event = new ComponentEvent($this), ); @@ -121,11 +109,7 @@ public static function onBeforeApplyDelete(QueuedClosure|callable|array|string $ */ public function beforeApplyDelete(): void { - if (! Event::hasListeners(self::componentEventName(self::EVENT_BEFORE_APPLY_DELETE))) { - return; - } - - Event::dispatch(self::componentEventName(self::EVENT_BEFORE_APPLY_DELETE), new ComponentEvent($this)); + event(self::componentEventName(self::EVENT_BEFORE_APPLY_DELETE), new ComponentEvent($this)); } public static function onAfterDelete(QueuedClosure|callable|array|string $callback): void @@ -138,10 +122,6 @@ public static function onAfterDelete(QueuedClosure|callable|array|string $callba */ public function afterDelete(): void { - if (! Event::hasListeners(self::componentEventName(self::EVENT_AFTER_DELETE))) { - return; - } - - Event::dispatch(self::componentEventName(self::EVENT_AFTER_DELETE), new ComponentEvent($this)); + event(self::componentEventName(self::EVENT_AFTER_DELETE), new ComponentEvent($this)); } } diff --git a/src/Dashboard/Dashboard.php b/src/Dashboard/Dashboard.php index 2a30593b228..a7632f8ca94 100644 --- a/src/Dashboard/Dashboard.php +++ b/src/Dashboard/Dashboard.php @@ -26,7 +26,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; use Illuminate\Validation\ValidationException; use Throwable; @@ -50,13 +49,9 @@ public function getAllWidgetTypes(): Collection UpdatesWidget::class, ]); - if (Event::hasListeners(RegisterWidgetTypes::class)) { - Event::dispatch($event = new RegisterWidgetTypes($widgetTypes)); + event($event = new RegisterWidgetTypes($widgetTypes)); - return $event->types; - } - - return $widgetTypes; + return $event->types; } /** @@ -140,16 +135,14 @@ public function saveWidget(WidgetInterface $widget, bool $runValidation = true): { $isNewWidget = ! $widget->id; - if (Event::hasListeners(WidgetSaving::class)) { - Event::dispatch($event = new WidgetSaving($widget, $isNewWidget)); + event($event = new WidgetSaving($widget, $isNewWidget)); - if (! $event->isValid) { - return false; - } - - $widget = $event->widget; + if (! $event->isValid) { + return false; } + $widget = $event->widget; + if (! $widget->beforeSave($isNewWidget)) { return false; } @@ -193,9 +186,7 @@ public function saveWidget(WidgetInterface $widget, bool $runValidation = true): throw $e; } - if (Event::hasListeners(WidgetSaved::class)) { - Event::dispatch(new WidgetSaved($widget, $isNewWidget)); - } + event(new WidgetSaved($widget, $isNewWidget)); return true; } @@ -221,13 +212,10 @@ public function deleteWidgetById(int $widgetId): bool */ public function deleteWidget(WidgetInterface $widget): bool { - if (Event::hasListeners(WidgetDeleting::class)) { - $event = new WidgetDeleting($widget); - Event::dispatch($event); + event($event = new WidgetDeleting($widget)); - if (! $event->isValid) { - return false; - } + if (! $event->isValid) { + return false; } if (! $widget->beforeDelete()) { @@ -247,9 +235,7 @@ public function deleteWidget(WidgetInterface $widget): bool throw $e; } - if (Event::hasListeners(WidgetDeleted::class)) { - Event::dispatch(new WidgetDeleted($widget)); - } + event(new WidgetDeleted($widget)); return true; } diff --git a/src/Database/Commands/MigrateCommand.php b/src/Database/Commands/MigrateCommand.php index 096092b914c..25d81af0bf4 100644 --- a/src/Database/Commands/MigrateCommand.php +++ b/src/Database/Commands/MigrateCommand.php @@ -15,7 +15,6 @@ use Illuminate\Contracts\Console\Isolatable; use Illuminate\Foundation\Console\DownCommand; use Illuminate\Foundation\Console\UpCommand; -use Illuminate\Support\Facades\Event; use Laravel\Prompts\Concerns\Colors; use Laravel\Prompts\Themes\Default\Concerns\DrawsBoxes; use Throwable; @@ -199,31 +198,29 @@ private function gatherMigrationsByTrack(array &$migrationsByTrack, array &$plug } } - if (Event::hasListeners(RegisterMigrators::class)) { - Event::dispatch($event = new RegisterMigrators([])); + event($event = new RegisterMigrators); - foreach ($event->migrators as $migrator) { - if (! $migrator instanceof Migrator) { - $this->components->warn($migrator::class.' is not an instance of '.Migrator::class); + foreach ($event->migrators as $migrator) { + if (! $migrator instanceof Migrator) { + $this->components->warn($migrator::class.' is not an instance of '.Migrator::class); - continue; - } + continue; + } - if (! $track = $migrator->getTrack()) { - $this->components->warn('A migrator was registered without a track.'); + if (! $track = $migrator->getTrack()) { + $this->components->warn('A migrator was registered without a track.'); - continue; - } + continue; + } - if ($this->option('track') && $this->option('track') !== $track) { - continue; - } + if ($this->option('track') && $this->option('track') !== $track) { + continue; + } - $this->migrators[$track] = $migrator; + $this->migrators[$track] = $migrator; - if (! empty($migrations = $migrator->getPendingMigrations())) { - $migrationsByTrack[$track] = $migrations; - } + if (! empty($migrations = $migrator->getPendingMigrations())) { + $migrationsByTrack[$track] = $migrations; } } } diff --git a/src/Database/Events/RegisterMigrators.php b/src/Database/Events/RegisterMigrators.php index e32b04e7011..241db1e32b7 100644 --- a/src/Database/Events/RegisterMigrators.php +++ b/src/Database/Events/RegisterMigrators.php @@ -8,6 +8,6 @@ final class RegisterMigrators { public function __construct( /** @var \CraftCms\Cms\Database\Migrator[] */ - public array $migrators, + public array $migrators = [], ) {} } diff --git a/src/Database/Migrations/Install.php b/src/Database/Migrations/Install.php index 2aba12120d4..a1ec728846d 100644 --- a/src/Database/Migrations/Install.php +++ b/src/Database/Migrations/Install.php @@ -36,7 +36,6 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Schema; use ReflectionClass; use Throwable; @@ -67,9 +66,7 @@ public function up(): void $this->components->task('Creating indexes', fn () => $this->createIndexes()); $this->components->task('Adding foreign keys', fn () => $this->addForeignKeys()); - if (Event::hasListeners(PostCreateTables::class)) { - Event::dispatch(new PostCreateTables); - } + event(new PostCreateTables); DB::afterCommit(function () { try { diff --git a/src/Database/Queries/Concerns/CollectsCacheTags.php b/src/Database/Queries/Concerns/CollectsCacheTags.php index 109dfd089d9..0483903da89 100644 --- a/src/Database/Queries/Concerns/CollectsCacheTags.php +++ b/src/Database/Queries/Concerns/CollectsCacheTags.php @@ -7,7 +7,6 @@ use Craft; use CraftCms\Cms\Database\Queries\Events\DefineCacheTags; use CraftCms\Cms\Support\Arr; -use Illuminate\Support\Facades\Event; /** * @internal @@ -67,11 +66,9 @@ public function getCacheTags(): array $queryTags = $this->cacheTags(); - if (Event::hasListeners(DefineCacheTags::class)) { - Event::dispatch($event = new DefineCacheTags($this, $queryTags)); + event($event = new DefineCacheTags($this, $queryTags)); - $queryTags = $event->tags; - } + $queryTags = $event->tags; if (! empty($queryTags)) { if ($this->drafts !== false) { diff --git a/src/Database/Queries/Concerns/HydratesElements.php b/src/Database/Queries/Concerns/HydratesElements.php index 9f6dbfefe75..5df3e276404 100644 --- a/src/Database/Queries/Concerns/HydratesElements.php +++ b/src/Database/Queries/Concerns/HydratesElements.php @@ -15,7 +15,6 @@ use CraftCms\Cms\Support\Json; use CraftCms\Cms\Support\Str; use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Event; use stdClass; /** @@ -88,13 +87,9 @@ public function hydrate(array $items): array ElementHelper::swapInProvisionalDrafts($elements); } - if (Event::hasListeners(ElementsHydrated::class)) { - Event::dispatch($event = new ElementsHydrated($elements, $items)); + event($event = new ElementsHydrated($elements, $items)); - return $event->elements; - } - - return $elements; + return $event->elements; } public function createElement(array $row): ElementInterface @@ -186,34 +181,20 @@ public function createElement(array $row): ElementInterface } } - $element = null; - - if (Event::hasListeners(HydratingElement::class)) { - Event::dispatch($event = new HydratingElement($row)); - - $row = $event->row; - - if (isset($event->element)) { - $element = $event->element; - } - } + event($event = new HydratingElement($row)); /** * When using addSelect() to select extra columns, they might appear * as `table.column`. We just want `column` */ - $row = collect($row) + $row = collect($event->row) ->mapWithKeys(fn (mixed $value, string $key) => [Str::after($key, '.') => $value]) ->all(); - $element ??= new $class($row); + $element = $event->element ?? new $class($row); - if (Event::hasListeners(ElementHydrated::class)) { - Event::dispatch($event = new ElementHydrated($element, $row)); - - return $event->element; - } + event($event = new ElementHydrated($element, $row)); - return $element; + return $event->element; } } diff --git a/src/Edition.php b/src/Edition.php index f9725bd2d43..47af573c743 100644 --- a/src/Edition.php +++ b/src/Edition.php @@ -13,7 +13,6 @@ use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Context; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Request; use InvalidArgumentException; @@ -102,9 +101,7 @@ public static function set(Edition|int $edition): void Context::addHidden(self::class, $edition); - if (Event::hasListeners(EditionChanged::class)) { - Event::dispatch(new EditionChanged($oldEdition, $edition)); - } + event(new EditionChanged($oldEdition, $edition)); } /** @internal */ diff --git a/src/Element/Concerns/Draftable.php b/src/Element/Concerns/Draftable.php index 14e83e52491..dd6685c7601 100644 --- a/src/Element/Concerns/Draftable.php +++ b/src/Element/Concerns/Draftable.php @@ -9,7 +9,6 @@ use CraftCms\Cms\Element\Events\AuthorizeCreateDrafts; use CraftCms\Cms\User\Elements\User as UserElement; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; /** @phpstan-ignore trait.unused */ trait Draftable @@ -129,13 +128,9 @@ public function handleDraftDelete(): void */ public function canCreateDrafts(UserElement $user): bool { - if (Event::hasListeners(AuthorizeCreateDrafts::class)) { - Event::dispatch($event = new AuthorizeCreateDrafts($this, $user)); + event($event = new AuthorizeCreateDrafts($this, $user)); - return $event->authorized; - } - - return false; + return $event->authorized; } /** diff --git a/src/Element/Drafts.php b/src/Element/Drafts.php index 45fc4c5b3cd..a1b74c87d62 100644 --- a/src/Element/Drafts.php +++ b/src/Element/Drafts.php @@ -23,7 +23,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; use Throwable; use Tpetry\QueryExpressions\Language\Alias; @@ -92,18 +91,16 @@ public function createDraft( $markAsSaved = Arr::pull($newAttributes, 'markAsSaved', true); - if (Event::hasListeners(CreatingDraft::class)) { - Event::dispatch($event = new CreatingDraft( - canonical: $canonical, - creatorId: $creatorId, - provisional: $provisional, - draftName: $name, - draftNotes: $notes, - )); - - $name = $event->draftName; - $notes = $event->draftNotes; - } + event($event = new CreatingDraft( + canonical: $canonical, + creatorId: $creatorId, + provisional: $provisional, + draftName: $name, + draftNotes: $notes, + )); + + $name = $event->draftName; + $notes = $event->draftNotes; if ($name === null || $name === '') { $name = $this->generateDraftName($canonical->id); @@ -149,16 +146,14 @@ public function createDraft( throw $e; } - if (Event::hasListeners(DraftCreated::class)) { - Event::dispatch(new DraftCreated( - canonical: $canonical, - creatorId: $creatorId, - provisional: $provisional, - draftName: $name, - draftNotes: $notes, - draft: $draft, - )); - } + event(new DraftCreated( + canonical: $canonical, + creatorId: $creatorId, + provisional: $provisional, + draftName: $name, + draftNotes: $notes, + draft: $draft, + )); return $draft; } @@ -241,15 +236,13 @@ public function applyDraft(ElementInterface $draft, array $newAttributes = []): } } - if (Event::hasListeners(ApplyingDraft::class)) { - Event::dispatch(new ApplyingDraft( - canonical: $canonical, - creatorId: $draft->draftCreatorId, - draftName: $draft->draftName, - draftNotes: $draft->draftNotes, - draft: $draft, - )); - } + event(new ApplyingDraft( + canonical: $canonical, + creatorId: $draft->draftCreatorId, + draftName: $draft->draftName, + draftNotes: $draft->draftNotes, + draft: $draft, + )); $elementsService = Craft::$app->getElements(); $draftNotes = $draft->draftNotes; @@ -293,15 +286,13 @@ public function applyDraft(ElementInterface $draft, array $newAttributes = []): throw $e; } - if (Event::hasListeners(DraftApplied::class)) { - Event::dispatch(new DraftApplied( - canonical: $newCanonical, - creatorId: $draft->draftCreatorId, - draftName: $draft->draftName, - draftNotes: $draft->draftNotes, - draft: $draft, - )); - } + event(new DraftApplied( + canonical: $newCanonical, + creatorId: $draft->draftCreatorId, + draftName: $draft->draftName, + draftNotes: $draft->draftNotes, + draft: $draft, + )); // if we were on another site when the applyDraft was triggered, // ensure we return the canonical element for the site we were on diff --git a/src/Element/ElementSources.php b/src/Element/ElementSources.php index 15ddda174fd..58c6d4d0486 100644 --- a/src/Element/ElementSources.php +++ b/src/Element/ElementSources.php @@ -26,7 +26,6 @@ use Illuminate\Container\Attributes\Singleton; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Event; use function CraftCms\Cms\t; @@ -490,15 +489,13 @@ public function getSourceSortOptions(string $elementType, string $sourceKey): Co $sortOptions = $this->getSortOptionsForFieldLayouts($fieldLayouts); - if (Event::hasListeners(DefineSourceSortOptions::class)) { - Event::dispatch($event = new DefineSourceSortOptions( - elementType: $elementType, - source: $sourceKey, - sortOptions: $sortOptions, - )); + event($event = new DefineSourceSortOptions( + elementType: $elementType, + source: $sourceKey, + sortOptions: $sortOptions, + )); - $sortOptions = $event->sortOptions; - } + $sortOptions = $event->sortOptions; // Combine duplicate attributes. If any attributes map to multiple sort // options and each option has a string orderBy value, cmobine them @@ -565,17 +562,13 @@ public function getSourceTableAttributes(string $elementType, string $sourceKey) $fieldLayouts = $this->getFieldLayoutsForSource($elementType, $sourceKey); $attributes = $this->getTableAttributesForFieldLayouts($fieldLayouts); - if (Event::hasListeners(DefineSourceTableAttributes::class)) { - Event::dispatch($event = new DefineSourceTableAttributes( - elementType: $elementType, - source: $sourceKey, - attributes: $attributes, - )); - - return $event->attributes; - } + event($event = new DefineSourceTableAttributes( + elementType: $elementType, + source: $sourceKey, + attributes: $attributes, + )); - return $attributes; + return $event->attributes; } /** diff --git a/src/Element/Revisions.php b/src/Element/Revisions.php index 13b912b9910..e6e6652f983 100644 --- a/src/Element/Revisions.php +++ b/src/Element/Revisions.php @@ -21,7 +21,6 @@ use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Throwable; use Tpetry\QueryExpressions\Language\Alias; use yii\base\InvalidArgumentException; @@ -99,24 +98,22 @@ public function createRevision( $creatorId = Auth::user()?->id; } - if (Event::hasListeners(CreatingRevision::class)) { - Event::dispatch($event = new CreatingRevision( - canonical: $canonical, - revisionNum: $num, - creatorId: $creatorId, - revisionNotes: $notes, - )); - - // only bail early if we have at least one revision - if ($event->handled && $lastRevisionInfo) { - return $lastRevisionInfo->id; - } + event($event = new CreatingRevision( + canonical: $canonical, + revisionNum: $num, + creatorId: $creatorId, + revisionNotes: $notes, + )); - $notes = $event->revisionNotes; - $creatorId = $event->creatorId; - $canonical = $event->canonical; + // only bail early if we have at least one revision + if ($event->handled && $lastRevisionInfo) { + return $lastRevisionInfo->id; } + $notes = $event->revisionNotes; + $creatorId = $event->creatorId; + $canonical = $event->canonical; + $elementsService = Craft::$app->getElements(); DB::beginTransaction(); @@ -151,15 +148,13 @@ public function createRevision( throw $e; } - if (Event::hasListeners(RevisionCreated::class)) { - Event::dispatch(new RevisionCreated( - canonical: $canonical, - revisionNum: $num, - creatorId: $creatorId, - revisionNotes: $notes, - revision: $revision, - )); - } + event(new RevisionCreated( + canonical: $canonical, + revisionNum: $num, + creatorId: $creatorId, + revisionNotes: $notes, + revision: $revision, + )); } finally { $mutex->release(); } @@ -191,15 +186,13 @@ public function revertToRevision(ElementInterface $revision, int $creatorId): El /** @var ElementInterface $revision */ $canonical = $revision->getCanonical(); - if (Event::hasListeners(RevertingToRevision::class)) { - Event::dispatch(new RevertingToRevision( - canonical: $canonical, - revisionNum: $revision->revisionNum, - creatorId: $creatorId, - revisionNotes: $revision->revisionNotes, - revision: $revision, - )); - } + event(new RevertingToRevision( + canonical: $canonical, + revisionNum: $revision->revisionNum, + creatorId: $creatorId, + revisionNotes: $revision->revisionNotes, + revision: $revision, + )); // "Duplicate" the revision with the source element’s ID and UID $newSource = Craft::$app->getElements()->updateCanonicalElement($revision, [ @@ -207,15 +200,13 @@ public function revertToRevision(ElementInterface $revision, int $creatorId): El 'revisionNotes' => t('Reverted content from revision {num}.', ['num' => $revision->revisionNum]), ]); - if (Event::hasListeners(RevertedToRevision::class)) { - Event::dispatch(new RevertedToRevision( - canonical: $canonical, - revisionNum: $revision->revisionNum, - creatorId: $creatorId, - revisionNotes: $revision->revisionNotes, - revision: $revision, - )); - } + event(new RevertedToRevision( + canonical: $canonical, + revisionNum: $revision->revisionNum, + creatorId: $creatorId, + revisionNotes: $revision->revisionNotes, + revision: $revision, + )); return $newSource; } diff --git a/src/Entry/Entries.php b/src/Entry/Entries.php index 21eb5c55a08..bd0e157dfe7 100644 --- a/src/Entry/Entries.php +++ b/src/Entry/Entries.php @@ -24,7 +24,6 @@ use Exception; use Illuminate\Container\Attributes\Singleton; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Throwable; use Tpetry\QueryExpressions\Language\Alias; @@ -147,9 +146,7 @@ public function refreshSingleEntries(): void public function moveEntryToSection(Entry $entry, Section $section): bool { // todo: what about revisions or drafts that might be of a type that's not compatible with the new section? - if (Event::hasListeners(MovingEntryToSection::class)) { - Event::dispatch(new MovingEntryToSection($entry, $section)); - } + event(new MovingEntryToSection($entry, $section)); // Make sure the element exists if (! $entry->id) { @@ -278,9 +275,7 @@ public function moveEntryToSection(Entry $entry, Section $section): bool } }); - if (Event::hasListeners(EntryMovedToSection::class)) { - Event::dispatch(new EntryMovedToSection($entry, $section)); - } + event(new EntryMovedToSection($entry, $section)); return true; } diff --git a/src/Entry/EntryTypes.php b/src/Entry/EntryTypes.php index 820c7765fee..77203f799c6 100644 --- a/src/Entry/EntryTypes.php +++ b/src/Entry/EntryTypes.php @@ -280,9 +280,7 @@ public function saveEntryType(EntryType $entryType): bool { $isNewEntryType = ! $entryType->id; - if (Event::hasListeners(SavingEntryType::class)) { - Event::dispatch(new SavingEntryType($entryType, $isNewEntryType)); - } + event(new SavingEntryType($entryType, $isNewEntryType)); $entryType->hasTitleField = $entryType->getFieldLayout()->isFieldIncluded('title'); @@ -423,9 +421,7 @@ public function handleChangedEntryType(ConfigEvent $event): void ])); } - if (Event::hasListeners(EntryTypeSaved::class)) { - Event::dispatch(new EntryTypeSaved($entryType, $isNewEntryType)); - } + event(new EntryTypeSaved($entryType, $isNewEntryType)); // Invalidate entry caches Craft::$app->getElements()->invalidateCachesForElementType(Entry::class); @@ -472,9 +468,7 @@ public function deleteEntryTypeById(int $entryTypeId): bool */ public function deleteEntryType(EntryType $entryType): bool { - if (Event::hasListeners(DeletingEntryType::class)) { - Event::dispatch(new DeletingEntryType($entryType)); - } + event(new DeletingEntryType($entryType)); $this->projectConfig->remove( path: ProjectConfig::PATH_ENTRY_TYPES.'.'.$entryType->uid, @@ -499,9 +493,7 @@ public function handleDeletedEntryType(ConfigEvent $event): void /** @var EntryType $entryType */ $entryType = $this->getEntryTypeById($entryTypeModel->id); - if (Event::hasListeners(ApplyingDeleteEntryType::class)) { - Event::dispatch(new ApplyingDeleteEntryType($entryType)); - } + event(new ApplyingDeleteEntryType($entryType)); DB::beginTransaction(); @@ -552,9 +544,7 @@ public function handleDeletedEntryType(ConfigEvent $event): void // Clear caches $this->refreshEntryTypes(); - if (Event::hasListeners(EntryTypeDeleted::class)) { - Event::dispatch(new EntryTypeDeleted($entryType)); - } + event(new EntryTypeDeleted($entryType)); // Invalidate entry caches Craft::$app->getElements()->invalidateCachesForElementType(Entry::class); diff --git a/src/Field/Assets.php b/src/Field/Assets.php index 8a68de57692..c3206faf1fd 100644 --- a/src/Field/Assets.php +++ b/src/Field/Assets.php @@ -899,20 +899,15 @@ private function _getUploadedFiles(ElementInterface $element): array } } - // Fire a 'locateUploadedFiles' event - if ($this->hasComponentListeners(self::EVENT_LOCATE_UPLOADED_FILES)) { - $event = new LocateUploadedFiles( - field: $this, - element: $element, - files: $files, - ); - - $this->dispatchComponentEvent(self::EVENT_LOCATE_UPLOADED_FILES, $event); + $event = new LocateUploadedFiles( + field: $this, + element: $element, + files: $files, + ); - return $event->files; - } + $this->dispatchComponentEvent(self::EVENT_LOCATE_UPLOADED_FILES, $event); - return $files; + return $event->files; } /** diff --git a/src/Field/BaseOptionsField.php b/src/Field/BaseOptionsField.php index 2bcf920dac2..8fa30b63d89 100644 --- a/src/Field/BaseOptionsField.php +++ b/src/Field/BaseOptionsField.php @@ -710,19 +710,17 @@ protected function translatedOptions(bool $encode = false, mixed $value = null, $options = $this->options(); $translatedOptions = []; - // Fire a 'defineOptions' event - if ($this->hasComponentListeners(self::EVENT_DEFINE_OPTIONS)) { + $this->dispatchComponentEvent( + self::EVENT_DEFINE_OPTIONS, $event = new DefineInputOptions( field: $this, options: $options, value: $value, element: $element, - ); - $this->dispatchComponentEvent(self::EVENT_DEFINE_OPTIONS, $event); - $options = $event->options; - } + ), + ); - foreach ($options as $option) { + foreach ($event->options as $option) { if (isset($option['optgroup'])) { $translatedOptions[] = [ 'optgroup' => t($option['optgroup'], category: 'site'), diff --git a/src/Field/BaseRelationField.php b/src/Field/BaseRelationField.php index c81a7ec9621..dd1f3a056e1 100644 --- a/src/Field/BaseRelationField.php +++ b/src/Field/BaseRelationField.php @@ -1650,17 +1650,12 @@ public function getInputSources(?ElementInterface $element = null): array|string */ public function getInputSelectionCriteria(): array { - // Fire a 'defineSelectionCriteria event - if ($this->hasComponentListeners(self::EVENT_DEFINE_SELECTION_CRITERIA)) { - $this->dispatchComponentEvent( - self::EVENT_DEFINE_SELECTION_CRITERIA, - $event = new DefineElementCriteria, - ); + $this->dispatchComponentEvent( + self::EVENT_DEFINE_SELECTION_CRITERIA, + $event = new DefineElementCriteria, + ); - return $event->criteria; - } - - return []; + return $event->criteria; } /** diff --git a/src/Field/Field.php b/src/Field/Field.php index f0724474a8c..d55376834d9 100644 --- a/src/Field/Field.php +++ b/src/Field/Field.php @@ -576,13 +576,9 @@ public function getActionMenuItems(): array { $items = $this->actionMenuItems(); - if ($this->hasComponentListeners(self::EVENT_DEFINE_ACTION_MENU_ITEMS)) { - $this->dispatchComponentEvent(self::EVENT_DEFINE_ACTION_MENU_ITEMS, $event = new DefineFieldActionMenuItems($this, $items)); + $this->dispatchComponentEvent(self::EVENT_DEFINE_ACTION_MENU_ITEMS, $event = new DefineFieldActionMenuItems($this, $items)); - return $event->items; - } - - return $items; + return $event->items; } protected function actionMenuItems(): array @@ -726,19 +722,15 @@ public function getInputHtml(mixed $value, ?ElementInterface $element): string { $html = $this->inputHtml($value, $element, false); - if ($this->hasComponentListeners(static::EVENT_DEFINE_INPUT_HTML)) { - $this->dispatchComponentEvent(static::EVENT_DEFINE_INPUT_HTML, $event = new DefineFieldHtml( - field: $this, - value: $value, - inline: false, - element: $element, - html: $html, - )); + $this->dispatchComponentEvent(static::EVENT_DEFINE_INPUT_HTML, $event = new DefineFieldHtml( + field: $this, + value: $value, + inline: false, + element: $element, + html: $html, + )); - return $event->html; - } - - return $html; + return $event->html; } /** @@ -748,19 +740,15 @@ public function getInlineInputHtml(mixed $value, ?ElementInterface $element): st { $html = $this->inputHtml($value, $element, true); - if ($this->hasComponentListeners(static::EVENT_DEFINE_INPUT_HTML)) { - $this->dispatchComponentEvent(static::EVENT_DEFINE_INPUT_HTML, $event = new DefineFieldHtml( - field: $this, - value: $value, - inline: true, - element: $element, - html: $html, - )); - - return $event->html; - } + $this->dispatchComponentEvent(static::EVENT_DEFINE_INPUT_HTML, $event = new DefineFieldHtml( + field: $this, + value: $value, + inline: true, + element: $element, + html: $html, + )); - return $html; + return $event->html; } /** @@ -806,16 +794,14 @@ public function isValueEmpty(mixed $value, ElementInterface $element): bool * {@inheritdoc} */ public function getSearchKeywords(mixed $value, ElementInterface $element): string { - if ($this->hasComponentListeners(self::EVENT_DEFINE_KEYWORDS)) { - $this->dispatchComponentEvent(self::EVENT_DEFINE_KEYWORDS, $event = new DefineFieldKeywords( - field: $this, - element: $element, - value: $value, - )); + $this->dispatchComponentEvent(self::EVENT_DEFINE_KEYWORDS, $event = new DefineFieldKeywords( + field: $this, + element: $element, + value: $value, + )); - if ($event->handled) { - return $event->keywords; - } + if ($event->handled) { + return $event->keywords; } return $this->searchKeywords($value, $element); @@ -917,10 +903,7 @@ public function canMergeFrom(FieldInterface $outgoingField, ?string &$reason): b */ public function afterMergeInto(FieldInterface $persistingField) { - // Fire an 'afterMergeInto' event - if ($this->hasComponentListeners(self::EVENT_AFTER_MERGE_INTO)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_MERGE_INTO, new FieldEvent($persistingField)); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_MERGE_INTO, new FieldEvent($persistingField)); } /** @@ -937,10 +920,7 @@ public function afterMergeFrom(FieldInterface $outgoingField) ]); } - // Fire an 'afterMergeFrom' event - if ($this->hasComponentListeners(self::EVENT_AFTER_MERGE_FROM)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_MERGE_FROM, new FieldEvent($outgoingField)); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_MERGE_FROM, new FieldEvent($outgoingField)); } /** {@inheritdoc} */ @@ -1157,88 +1137,68 @@ public function beforeSave(bool $isNew): bool $this->context = Fields::getFieldContext(); } - if ($this->hasComponentListeners(self::EVENT_BEFORE_SAVE)) { - $this->dispatchComponentEvent(self::EVENT_BEFORE_SAVE, $event = new ComponentEvent($this, $isNew)); + $this->dispatchComponentEvent(self::EVENT_BEFORE_SAVE, $event = new ComponentEvent($this, $isNew)); - return $event->isValid; - } - - return true; + return $event->isValid; } public function afterSave(bool $isNew): void { - if ($this->hasComponentListeners(self::EVENT_AFTER_SAVE)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_SAVE, new ComponentEvent($this, $isNew)); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_SAVE, new ComponentEvent($this, $isNew)); } /** * {@inheritdoc} */ public function beforeElementSave(ElementInterface $element, bool $isNew): bool { - if ($this->hasComponentListeners(self::EVENT_BEFORE_ELEMENT_SAVE)) { - $this->dispatchComponentEvent(self::EVENT_BEFORE_ELEMENT_SAVE, $event = new FieldElementEvent( - field: $this, - element: $element, - isNew: $isNew - )); + $this->dispatchComponentEvent(self::EVENT_BEFORE_ELEMENT_SAVE, $event = new FieldElementEvent( + field: $this, + element: $element, + isNew: $isNew + )); - return $event->isValid; - } - - return true; + return $event->isValid; } /** * {@inheritdoc} */ public function afterElementSave(ElementInterface $element, bool $isNew): void { - if ($this->hasComponentListeners(self::EVENT_AFTER_ELEMENT_SAVE)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_SAVE, new FieldElementEvent( - field: $this, - element: $element, - isNew: $isNew - )); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_SAVE, new FieldElementEvent( + field: $this, + element: $element, + isNew: $isNew + )); } /** {@inheritdoc} */ public function afterElementPropagate(ElementInterface $element, bool $isNew): void { - if ($this->hasComponentListeners(self::EVENT_AFTER_ELEMENT_PROPAGATE)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_PROPAGATE, new FieldElementEvent( - field: $this, - element: $element, - isNew: $isNew - )); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_PROPAGATE, new FieldElementEvent( + field: $this, + element: $element, + isNew: $isNew + )); } /** {@inheritdoc} */ public function beforeElementDelete(ElementInterface $element): bool { - if ($this->hasComponentListeners(self::EVENT_BEFORE_ELEMENT_DELETE)) { - $this->dispatchComponentEvent(self::EVENT_BEFORE_ELEMENT_DELETE, $event = new FieldElementEvent( - field: $this, - element: $element, - )); - - return $event->isValid; - } + $this->dispatchComponentEvent(self::EVENT_BEFORE_ELEMENT_DELETE, $event = new FieldElementEvent( + field: $this, + element: $element, + )); - return true; + return $event->isValid; } /** {@inheritdoc} */ public function afterElementDelete(ElementInterface $element): void { - if ($this->hasComponentListeners(self::EVENT_AFTER_ELEMENT_DELETE)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_DELETE, new FieldElementEvent( - field: $this, - element: $element, - )); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_DELETE, new FieldElementEvent( + field: $this, + element: $element, + )); } /** {@inheritdoc} */ @@ -1256,27 +1216,21 @@ public function afterElementDeleteForSite(ElementInterface $element): void /** {@inheritdoc} */ public function beforeElementRestore(ElementInterface $element): bool { - if ($this->hasComponentListeners(self::EVENT_BEFORE_ELEMENT_RESTORE)) { - $this->dispatchComponentEvent(self::EVENT_BEFORE_ELEMENT_RESTORE, $event = new FieldElementEvent( - field: $this, - element: $element, - )); - - return $event->isValid; - } + $this->dispatchComponentEvent(self::EVENT_BEFORE_ELEMENT_RESTORE, $event = new FieldElementEvent( + field: $this, + element: $element, + )); - return true; + return $event->isValid; } /** {@inheritdoc} */ public function afterElementRestore(ElementInterface $element): void { - if ($this->hasComponentListeners(self::EVENT_AFTER_ELEMENT_RESTORE)) { - $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_RESTORE, new FieldElementEvent( - field: $this, - element: $element, - )); - } + $this->dispatchComponentEvent(self::EVENT_AFTER_ELEMENT_RESTORE, new FieldElementEvent( + field: $this, + element: $element, + )); } /** diff --git a/src/Field/Fields.php b/src/Field/Fields.php index 9f03f7020a0..3fa25229a52 100644 --- a/src/Field/Fields.php +++ b/src/Field/Fields.php @@ -56,7 +56,6 @@ use Illuminate\Database\Query\Builder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Request; use Illuminate\Validation\ValidationException; @@ -138,13 +137,9 @@ public function getAllFieldTypes(): Collection UsersField::class, ]); - if (Event::hasListeners(RegisterFieldTypes::class)) { - Event::dispatch($event = new RegisterFieldTypes($fieldTypes)); + event($event = new RegisterFieldTypes($fieldTypes)); - return $event->types; - } - - return $fieldTypes; + return $event->types; } /** @@ -195,13 +190,9 @@ public function getCompatibleFieldTypes(FieldInterface $field, bool $includeCurr $types->add($field::class); } - if (Event::hasListeners(DefineCompatibleFieldTypes::class)) { - Event::dispatch($event = new DefineCompatibleFieldTypes($field, $types)); - - return $event->compatibleTypes; - } + event($event = new DefineCompatibleFieldTypes($field, $types)); - return $types; + return $event->compatibleTypes; } /** @@ -240,13 +231,9 @@ public function getNestedEntryFieldTypes(): Collection MatrixField::class, ]); - if (Event::hasListeners(RegisterNestedEntryFieldTypes::class)) { - Event::dispatch($event = new RegisterNestedEntryFieldTypes($fieldTypes)); + event($event = new RegisterNestedEntryFieldTypes($fieldTypes)); - return $event->types; - } - - return $fieldTypes; + return $event->types; } /** @@ -493,9 +480,7 @@ public function saveField(FieldInterface $field, bool $runValidation = true): bo $isNewField = $field->getIsNew(); - if (Event::hasListeners(FieldSaving::class)) { - Event::dispatch(new FieldSaving($field, $isNewField)); - } + event(new FieldSaving($field, $isNewField)); if (! $field->beforeSave($isNewField)) { return false; @@ -605,9 +590,7 @@ public function deleteFieldById(int $fieldId): bool */ public function deleteField(FieldInterface $field): bool { - if (Event::hasListeners(FieldDeleting::class)) { - Event::dispatch(new FieldDeleting($field)); - } + event(new FieldDeleting($field)); if (! $field->beforeDelete()) { return false; @@ -651,9 +634,7 @@ public function applyFieldDelete(string $fieldUid): void $field = $this->getFieldById($fieldRecord->id); - if (Event::hasListeners(ApplyingFieldDelete::class)) { - Event::dispatch(new ApplyingFieldDelete($field)); - } + event(new ApplyingFieldDelete($field)); DB::beginTransaction(); @@ -677,9 +658,7 @@ public function applyFieldDelete(string $fieldUid): void // Update the field version $this->updateFieldVersion(); - if (Event::hasListeners(FieldDeleted::class)) { - Event::dispatch(new FieldDeleted($field)); - } + event(new FieldDeleted($field)); // Invalidate all element caches Craft::$app->getElements()->invalidateAllCaches(); @@ -941,9 +920,7 @@ public function saveLayout(FieldLayout $layout, bool $runValidation = true): boo $isNewLayout = ! $layout->id; - if (Event::hasListeners(FieldLayoutSaving::class)) { - Event::dispatch(new FieldLayoutSaving($layout, $isNewLayout)); - } + event(new FieldLayoutSaving($layout, $isNewLayout)); if ($runValidation && ! $layout->validate()) { Log::info('Field layout not saved due to validation error.', [__METHOD__]); @@ -979,9 +956,7 @@ public function saveLayout(FieldLayout $layout, bool $runValidation = true): boo $layout->uid = $layoutModel->uid; - if (Event::hasListeners(FieldLayoutSaved::class)) { - Event::dispatch(new FieldLayoutSaved($layout, $isNewLayout)); - } + event(new FieldLayoutSaved($layout, $isNewLayout)); // Clear caches $this->_layouts = null; @@ -1028,15 +1003,11 @@ public function deleteLayoutById(array|int $layoutId): bool */ public function deleteLayout(FieldLayout $layout): bool { - if (Event::hasListeners(FieldLayoutDeleting::class)) { - Event::dispatch(new FieldLayoutDeleting($layout)); - } + event(new FieldLayoutDeleting($layout)); DB::table(Table::FIELDLAYOUTS)->softDelete($layout->id); - if (Event::hasListeners(FieldLayoutDeleted::class)) { - Event::dispatch(new FieldLayoutDeleted($layout)); - } + event(new FieldLayoutDeleted($layout)); // Clear caches $this->_layouts = null; @@ -1121,9 +1092,7 @@ public function applyFieldSave(string $fieldUid, array $data, string $context): // For control panel save requests, make sure we have all the custom data already saved on the object. $field = $this->_savingFields[$fieldUid] ?? null; - if (Event::hasListeners(ApplyingFieldSave::class)) { - Event::dispatch(new ApplyingFieldSave($oldField, $data)); - } + event(new ApplyingFieldSave($oldField, $data)); DB::beginTransaction(); @@ -1186,9 +1155,7 @@ public function applyFieldSave(string $fieldUid, array $data, string $context): $field->afterSave($isNewField); - if (Event::hasListeners(FieldSaved::class)) { - Event::dispatch(new FieldSaved($field, $isNewField)); - } + event(new FieldSaved($field, $isNewField)); // If we just dropped `searchable`, delete the field’s search indexes immediately. if ($deleteSearchIndexes) { diff --git a/src/Field/Link.php b/src/Field/Link.php index 22923ab071e..c1fd14904fe 100644 --- a/src/Field/Link.php +++ b/src/Field/Link.php @@ -39,6 +39,7 @@ use GraphQL\Type\Definition\Type; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Event; +use Override; use yii\base\InvalidArgumentException; use yii\db\Schema; @@ -56,7 +57,7 @@ final class Link extends Field implements CrossSiteCopyableFieldInterface, Inlin /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function displayName(): string { return t('Link'); @@ -65,7 +66,7 @@ public static function displayName(): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function icon(): string { return 'link'; @@ -74,7 +75,7 @@ public static function icon(): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function phpType(): string { return sprintf('\\%s|null', LinkData::class); @@ -83,7 +84,7 @@ public static function phpType(): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function dbType(): array { return [ @@ -118,13 +119,12 @@ private static function types(): array ]; // Fire a registerLinkTypes event - if (Event::hasListeners(RegisterLinkTypes::class)) { - Event::dispatch($event = new RegisterLinkTypes($types)); + event($event = new RegisterLinkTypes($types)); - return $event->types; - } + $types = $event->types; // URL *has* to be there + /** @var class-string[] $types */ $types[] = UrlType::class; self::$_types = array_combine( @@ -225,7 +225,7 @@ public function __construct($config = []) parent::__construct($config); } - #[\Override] + #[Override] public static function getRules(): array { return array_merge(parent::getRules(), [ @@ -452,7 +452,7 @@ private function settingsHtml(bool $readOnly): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public function normalizeValue(mixed $value, ?ElementInterface $element): ?LinkData { // if this was set due to propagateAll for a fresh element (as opposed to the translation method), @@ -548,7 +548,7 @@ public function normalizeValue(mixed $value, ?ElementInterface $element): ?LinkD /** * {@inheritdoc} */ - #[\Override] + #[Override] public function useFieldset(): bool { return true; @@ -557,7 +557,7 @@ public function useFieldset(): bool /** * {@inheritdoc} */ - #[\Override] + #[Override] protected function inputHtml(mixed $value, ?ElementInterface $element, bool $inline): string { $linkTypes = $this->getLinkTypes(); @@ -775,7 +775,7 @@ protected function inputHtml(mixed $value, ?ElementInterface $element, bool $inl /** * {@inheritdoc} */ - #[\Override] + #[Override] public function getElementValidationRules(): array { return [ @@ -817,7 +817,7 @@ function (ElementInterface $element) { /** * {@inheritdoc} */ - #[\Override] + #[Override] public function isValueEmpty(mixed $value, ElementInterface $element): bool { if (parent::isValueEmpty($value, $element)) { @@ -844,7 +844,7 @@ public function getElementConditionRuleType(): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public function getPreviewHtml(mixed $value, ElementInterface $element): string { /** @var LinkData|null $value */ @@ -854,7 +854,7 @@ public function getPreviewHtml(mixed $value, ElementInterface $element): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public function previewPlaceholderHtml(mixed $value, ?ElementInterface $element): string { if (! $value) { @@ -868,7 +868,7 @@ public function previewPlaceholderHtml(mixed $value, ?ElementInterface $element) /** * {@inheritdoc} */ - #[\Override] + #[Override] public function getContentGqlType(): Type|array { if (! $this->fullGraphqlData) { @@ -881,7 +881,7 @@ public function getContentGqlType(): Type|array /** * {@inheritdoc} */ - #[\Override] + #[Override] public function getContentGqlMutationArgumentType(): Type|array { if (! $this->fullGraphqlData) { diff --git a/src/Field/Matrix.php b/src/Field/Matrix.php index 8b34a45824a..ee291c7ef28 100644 --- a/src/Field/Matrix.php +++ b/src/Field/Matrix.php @@ -439,22 +439,18 @@ public function getEntryTypesForField(array $value, ?ElementInterface $element): { $entryTypes = $this->_entryTypes; - // Fire a 'defineEntryTypes' event - if ($this->hasComponentListeners(self::EVENT_DEFINE_ENTRY_TYPES)) { - $this->dispatchComponentEvent(self::EVENT_DEFINE_ENTRY_TYPES, $event = new DefineEntryTypesForField( - field: $this, - entryTypes: $entryTypes, - element: $element, - value: $value, - )); - $entryTypes = $event->entryTypes; - } - - if (empty($entryTypes)) { + $this->dispatchComponentEvent(self::EVENT_DEFINE_ENTRY_TYPES, $event = new DefineEntryTypesForField( + field: $this, + entryTypes: $entryTypes, + element: $element, + value: $value, + )); + + if (empty($event->entryTypes)) { throw new InvalidConfigException('At least one entry type is required.'); } - return array_values($entryTypes); + return array_values($event->entryTypes); } /** @@ -1003,7 +999,7 @@ private function copyAction(string $type, string $entrySelector): array } const getEntries = () => { - const entries = field.find($entrySelector); + const entries = field.find($entrySelector) const selectedEntries = entries.filter('.sel'); return (selectedEntries.length ? selectedEntries : entries).toArray(); }; @@ -1018,7 +1014,7 @@ private function copyAction(string $type, string $entrySelector): array revisionId: element.data('revisionId'), ownerId: element.data('ownerId'), siteId: element.data('siteId'), - }; + } })); }); @@ -1609,7 +1605,7 @@ public function getContentGqlType(): array /** * {@inheritdoc} */ - #[\Override] + #[Override] public function getEagerLoadingGqlConditions(): array { return [ diff --git a/src/GarbageCollection/Actions/FireRunEvent.php b/src/GarbageCollection/Actions/FireRunEvent.php index 2708599a797..09c065cf1c6 100644 --- a/src/GarbageCollection/Actions/FireRunEvent.php +++ b/src/GarbageCollection/Actions/FireRunEvent.php @@ -5,14 +5,11 @@ namespace CraftCms\Cms\GarbageCollection\Actions; use CraftCms\Cms\GarbageCollection\Events\RunningGarbageCollection; -use Illuminate\Support\Facades\Event; final class FireRunEvent extends GarbageCollectionAction { public function __invoke(): void { - if (Event::hasListeners(RunningGarbageCollection::class)) { - Event::dispatch(new RunningGarbageCollection($this->garbageCollection)); - } + event(new RunningGarbageCollection($this->garbageCollection)); } } diff --git a/src/Http/Controllers/Auth/AuthenticationController.php b/src/Http/Controllers/Auth/AuthenticationController.php index 2f6a9b40fdd..c5895d97189 100644 --- a/src/Http/Controllers/Auth/AuthenticationController.php +++ b/src/Http/Controllers/Auth/AuthenticationController.php @@ -20,7 +20,6 @@ use Illuminate\Auth\Events\Failed; use Illuminate\Contracts\View\View; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Password; use Illuminate\Support\Facades\URL; use Symfony\Component\HttpFoundation\Response; @@ -58,7 +57,7 @@ protected function handleLoginFailure(Request $request, ?AuthError $authError = { [$authError, $message] = $this->auth->getLoginFailureInfo($authError, $user); - Event::dispatch(new Failed( + event(new Failed( guard: 'craft', user: $user, credentials: $request->only('loginName', 'password'), @@ -101,9 +100,7 @@ protected function processTokenRequest(Request $request): Response|array auth('craft')->logout(); } - if (Event::hasListeners(VerifyingEmail::class)) { - Event::dispatch(new VerifyingEmail($user)); - } + event(new VerifyingEmail($user)); /** @var \Illuminate\Auth\Passwords\PasswordBroker $broker */ $broker = Password::broker('craft'); @@ -111,16 +108,14 @@ protected function processTokenRequest(Request $request): Response|array return $this->processInvalidToken($request, $user); } - if (Event::hasListeners(EmailVerified::class)) { - Event::dispatch(new EmailVerified($user)); - } + event(new EmailVerified($user)); return [$user, $request->input('id'), $request->input('code')]; } protected function processInvalidToken(Request $request, ?User $user = null): Response { - Event::dispatch(new InvalidUserToken($user)); + event(new InvalidUserToken($user)); if ($request->wantsJson()) { return $this->asFailure('InvalidVerificationCode'); diff --git a/src/Http/Controllers/Auth/SetPasswordController.php b/src/Http/Controllers/Auth/SetPasswordController.php index 1e5dbfc00a1..2576e8e447b 100644 --- a/src/Http/Controllers/Auth/SetPasswordController.php +++ b/src/Http/Controllers/Auth/SetPasswordController.php @@ -15,7 +15,6 @@ use CraftCms\Cms\User\Users; use Illuminate\Contracts\View\View; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Password as PasswordFacade; use Illuminate\Validation\Rules\Password; use RuntimeException; @@ -84,10 +83,9 @@ function (User $user, string $password) { $status = 'password.save_failed'; } - if (Event::hasListeners(SettingPassword::class)) { - Event::dispatch($event = new SettingPassword($user, $request->input('code'), $request->input('newPassword'), $status)); - $status = $event->status; - } + event($event = new SettingPassword($user, $request->input('code'), $request->input('newPassword'), $status)); + + $status = $event->status; if ($status === 'password.save_failed') { if ($request->wantsJson()) { diff --git a/src/Http/Controllers/Users/EditUserTrait.php b/src/Http/Controllers/Users/EditUserTrait.php index 65ac1b786da..0ed6e6d093f 100644 --- a/src/Http/Controllers/Users/EditUserTrait.php +++ b/src/Http/Controllers/Users/EditUserTrait.php @@ -13,7 +13,6 @@ use CraftCms\Cms\User\Events\DefineEditUserScreens; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Hash; use function CraftCms\Cms\t; @@ -81,10 +80,9 @@ protected function asEditUserScreen(User $user, string $screen): CpScreenRespons $currentUser = Auth::user(); - if (Event::hasListeners(DefineEditUserScreens::class)) { - Event::dispatch($event = new DefineEditUserScreens($currentUser, $user, $screens)); - $screens = $event->screens; - } + event($event = new DefineEditUserScreens($currentUser, $user, $screens)); + + $screens = $event->screens; if ($user->getIsCurrent() && $user->getHasPassword()) { $screens[self::SCREEN_PASSWORD] = ['label' => t('Password & Verification')]; diff --git a/src/Http/Controllers/Users/PermissionsController.php b/src/Http/Controllers/Users/PermissionsController.php index f1bc6e699cf..4f1c464aae9 100644 --- a/src/Http/Controllers/Users/PermissionsController.php +++ b/src/Http/Controllers/Users/PermissionsController.php @@ -20,7 +20,6 @@ use CraftCms\Cms\User\Events\AssigningGroupsAndPermissions; use CraftCms\Cms\User\Events\GroupsAndPermissionsAssigned; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Event; use Illuminate\Validation\Rule; use Symfony\Component\HttpFoundation\Response; use Throwable; @@ -85,17 +84,13 @@ public function store(Request $request): Response } if (Edition::get()->value >= Edition::Pro->value) { - if (Event::hasListeners(AssigningGroupsAndPermissions::class)) { - Event::dispatch(new AssigningGroupsAndPermissions($user)); - } + event(new AssigningGroupsAndPermissions($user)); // Assign user groups and permissions if the current user is allowed to do that $this->saveUserGroups($request, $user, $currentUser); $this->saveUserPermissions($request, $user, $currentUser); - if (Event::hasListeners(GroupsAndPermissionsAssigned::class)) { - Event::dispatch(new GroupsAndPermissionsAssigned($user)); - } + event(new GroupsAndPermissionsAssigned($user)); } if ( diff --git a/src/Http/Controllers/Users/UsersController.php b/src/Http/Controllers/Users/UsersController.php index c1890fef211..7dd434aacea 100644 --- a/src/Http/Controllers/Users/UsersController.php +++ b/src/Http/Controllers/Users/UsersController.php @@ -23,7 +23,6 @@ use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Event; use ReflectionClass; use ReflectionException; use Symfony\Component\HttpFoundation\Response; @@ -206,11 +205,8 @@ public function contentSummary(Request $request, Sections $sections): Response ]); })->filter(); - if (Event::hasListeners(DefineUserContentSummary::class)) { - Event::dispatch($event = new DefineUserContentSummary($userId, $summary)); - $summary = $event->contentSummary; - } + event($event = new DefineUserContentSummary($userId, $summary)); - return new JsonResponse($summary->all()); + return new JsonResponse($event->contentSummary->all()); } } diff --git a/src/Plugin/Concerns/HasSettings.php b/src/Plugin/Concerns/HasSettings.php index 003fd9bdbce..dd4ec826436 100644 --- a/src/Plugin/Concerns/HasSettings.php +++ b/src/Plugin/Concerns/HasSettings.php @@ -111,21 +111,15 @@ private function settingsResponse(bool $readOnly): Response /** {@inheritdoc} */ public function beforeSaveSettings(): bool { - if (Event::hasListeners(self::componentEventName(self::EVENT_BEFORE_SAVE_SETTINGS))) { - Event::dispatch(self::componentEventName(self::EVENT_BEFORE_SAVE_SETTINGS), $event = new ComponentEvent($this)); + event(self::componentEventName(self::EVENT_BEFORE_SAVE_SETTINGS), $event = new ComponentEvent($this)); - return $event->isValid; - } - - return true; + return $event->isValid; } /** {@inheritdoc} */ public function afterSaveSettings(): void { - if (Event::hasListeners(self::componentEventName(self::EVENT_AFTER_SAVE_SETTINGS))) { - Event::dispatch(self::componentEventName(self::EVENT_AFTER_SAVE_SETTINGS), new ComponentEvent($this)); - } + event(self::componentEventName(self::EVENT_AFTER_SAVE_SETTINGS), new ComponentEvent($this)); } /** diff --git a/src/Plugin/Plugins.php b/src/Plugin/Plugins.php index e605abfc2e8..3f48345f058 100644 --- a/src/Plugin/Plugins.php +++ b/src/Plugin/Plugins.php @@ -43,7 +43,6 @@ use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Vite; use InvalidArgumentException; @@ -160,10 +159,7 @@ public function loadPlugins(): void // Prevent this function from getting called twice. $this->loadingPlugins = true; - // Fire a 'beforeLoadPlugins' event - if (Event::hasListeners(LoadingPlugins::class)) { - Event::dispatch(new LoadingPlugins); - } + event(new LoadingPlugins); // Find all of the installed plugins $this->storedPluginInfo = DB::table(Table::PLUGINS) @@ -256,9 +252,7 @@ public function loadPlugins(): void $this->loadingPlugins = false; $this->pluginsLoaded = true; - if (Event::hasListeners(PluginsLoaded::class)) { - Event::dispatch(PluginsLoaded::class); - } + event(PluginsLoaded::class); } /** @@ -364,9 +358,7 @@ public function enablePlugin(string $handle): bool throw new InvalidPluginException($handle); } - if (Event::hasListeners(EnablingPlugin::class)) { - Event::dispatch(new EnablingPlugin($plugin)); - } + event(new EnablingPlugin($plugin)); // Enable the plugin in the project config app(ProjectConfig::class)->set( @@ -378,9 +370,7 @@ public function enablePlugin(string $handle): bool $this->storedPluginInfo[$handle]['enabled'] = true; $this->registerPlugin($plugin); - if (Event::hasListeners(PluginEnabled::class)) { - Event::dispatch(new PluginEnabled($plugin)); - } + event(new PluginEnabled($plugin)); return true; } @@ -407,9 +397,7 @@ public function disablePlugin(string $handle): bool throw new InvalidPluginException($handle); } - if (Event::hasListeners(DisablingPlugin::class)) { - Event::dispatch(new DisablingPlugin($plugin)); - } + event(new DisablingPlugin($plugin)); // Disable the plugin in the project config app(ProjectConfig::class)->set( @@ -421,9 +409,7 @@ public function disablePlugin(string $handle): bool $this->storedPluginInfo[$handle]['enabled'] = false; $this->unregisterPlugin($plugin); - if (Event::hasListeners(PluginDisabled::class)) { - Event::dispatch(new PluginDisabled($plugin)); - } + event(new PluginDisabled($plugin)); return true; } @@ -473,10 +459,7 @@ public function installPlugin(string $handle, ?string $edition = null): bool $plugin->edition = $edition; - // Fire a 'beforeInstallPlugin' event - if (Event::hasListeners(InstallingPlugin::class)) { - Event::dispatch(new InstallingPlugin($plugin)); - } + event(new InstallingPlugin($plugin)); DB::beginTransaction(); @@ -539,9 +522,7 @@ public function installPlugin(string $handle, ?string $edition = null): bool $this->storedPluginInfo[$handle] = $info; $this->registerPlugin($plugin); - if (Event::hasListeners(PluginInstalled::class)) { - Event::dispatch(new PluginInstalled($plugin)); - } + event(new PluginInstalled($plugin)); $projectConfig->readOnly = $readOnly; @@ -585,10 +566,7 @@ public function uninstallPlugin(string $handle, bool $force = false): bool throw new InvalidPluginException($handle); } - // Fire a 'beforeUninstallPlugin' event - if (Event::hasListeners(UninstallingPlugin::class)) { - Event::dispatch(new UninstallingPlugin($plugin)); - } + event(new UninstallingPlugin($plugin)); DB::beginTransaction(); try { @@ -630,10 +608,7 @@ public function uninstallPlugin(string $handle, bool $force = false): bool unset($this->storedPluginInfo[$handle]); - // Fire an 'afterUninstallPlugin' event - if (Event::hasListeners(PluginUninstalled::class)) { - Event::dispatch(new PluginUninstalled($plugin)); - } + event(new PluginUninstalled($plugin)); $projectConfig->readOnly = $readOnly; @@ -702,12 +677,10 @@ public function savePluginSettings(PluginInterface $plugin, array $settings): bo return false; } - if (Event::hasListeners(SavingPluginSettings::class)) { - Event::dispatch($event = new SavingPluginSettings($plugin)); + event($event = new SavingPluginSettings($plugin)); - if (! $event->isValid) { - return false; - } + if (! $event->isValid) { + return false; } if (! $plugin->beforeSaveSettings()) { @@ -724,9 +697,7 @@ public function savePluginSettings(PluginInterface $plugin, array $settings): bo $plugin->afterSaveSettings(); - if (Event::hasListeners(PluginSettingsSaved::class)) { - Event::dispatch(new PluginSettingsSaved($plugin)); - } + event(new PluginSettingsSaved($plugin)); return true; } diff --git a/src/ProjectConfig/Data/ProjectConfigData.php b/src/ProjectConfig/Data/ProjectConfigData.php index 3f17ac2b9ad..b74b5ee2afc 100644 --- a/src/ProjectConfig/Data/ProjectConfigData.php +++ b/src/ProjectConfig/Data/ProjectConfigData.php @@ -13,7 +13,6 @@ use CraftCms\Cms\ProjectConfig\ProjectConfig; use CraftCms\Cms\ProjectConfig\ProjectConfigHelper; use CraftCms\Cms\Support\Str; -use Illuminate\Support\Facades\Event; final class ProjectConfigData extends ReadOnlyProjectConfigData { @@ -55,7 +54,7 @@ public function commitChanges(mixed $oldValue, mixed $newValue, string $path, bo ); if ($valueChanged && ! $this->projectConfig->muteEvents) { - Event::dispatch(match (true) { + event(match (true) { $newValue === null && $oldValue !== null => new RemovingItem($path, $oldValue, $newValue), $oldValue === null && $newValue !== null => new AddingItem($path, $oldValue, $newValue), default => new UpdatingItem($path, $oldValue, $newValue), @@ -67,7 +66,7 @@ public function commitChanges(mixed $oldValue, mixed $newValue, string $path, bo } if ($valueChanged && ! $this->projectConfig->muteEvents) { - Event::dispatch(match (true) { + event(match (true) { $newValue === null && $oldValue !== null => new ItemRemoved($path, $oldValue, $newValue), $oldValue === null && $newValue !== null => new ItemAdded($path, $oldValue, $newValue), default => new ItemUpdated($path, $oldValue, $newValue), diff --git a/src/ProjectConfig/ProjectConfig.php b/src/ProjectConfig/ProjectConfig.php index 00abda3456f..f28a03b8ced 100644 --- a/src/ProjectConfig/ProjectConfig.php +++ b/src/ProjectConfig/ProjectConfig.php @@ -1136,16 +1136,13 @@ public function rebuild(): void $config[self::PATH_VOLUMES] = $this->_getVolumeData(); // Fire a 'rebuild' event - if (Event::hasListeners(RebuildConfig::class)) { - Event::dispatch($event = new RebuildConfig($config)); - $config = $event->config; - } + event($event = new RebuildConfig($config)); // Reset the component name map $this->_setInternal(self::PATH_META_NAMES, [], updateTimestamp: false, force: true); // Process the changes - foreach ($config as $path => $value) { + foreach ($event->config as $path => $value) { $this->_setInternal($path, $value, 'Project config rebuild', updateTimestamp: false, force: true); } @@ -1239,9 +1236,7 @@ private function _applyChanges( Log::info('Finalizing configuration parsing', [__METHOD__]); - if (Event::hasListeners(ChangesApplied::class)) { - Event::dispatch(new ChangesApplied); - } + event(new ChangesApplied); $this->updateParsedConfigTimesAfterRequest(); $this->isApplyingExternalChanges = false; @@ -1537,7 +1532,7 @@ public function writeYamlFiles(bool $force = false): void Cache::forget(self::FILE_ISSUES_CACHE_KEY); // Let plugins know about it - Event::dispatch(new YamlFilesWritten); + event(new YamlFilesWritten); $this->_updateYaml = false; } diff --git a/src/Route/Routes.php b/src/Route/Routes.php index a4cadcc8f85..32126536dc1 100644 --- a/src/Route/Routes.php +++ b/src/Route/Routes.php @@ -16,7 +16,6 @@ use CraftCms\Cms\Support\Str; use Illuminate\Container\Attributes\Singleton; use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Event; #[Singleton] final class Routes @@ -95,9 +94,7 @@ public function getProjectConfigRoutes(): Collection */ public function saveRoute(Route $route): string { - if (Event::hasListeners(SavingRoute::class)) { - Event::dispatch(new SavingRoute($route)); - } + event(new SavingRoute($route)); if ($route->uid !== null) { $sortOrder = $this->projectConfig->get( @@ -114,9 +111,7 @@ public function saveRoute(Route $route): string 'Save route', ); - if (Event::hasListeners(RouteSaved::class)) { - Event::dispatch(new RouteSaved($route)); - } + event(new RouteSaved($route)); $this->projectConfigRoutes = null; @@ -131,28 +126,24 @@ public function deleteRouteByUid(string $routeUid): bool return true; } - if (Event::hasListeners(DeletingRoute::class)) { - Event::dispatch(new DeletingRoute(new Route( - uriParts: $route['uriParts'], - template: $route['template'], - siteUid: $route['siteUid'], - uid: $routeUid, - ))); - } + event(new DeletingRoute(new Route( + uriParts: $route['uriParts'], + template: $route['template'], + siteUid: $route['siteUid'], + uid: $routeUid, + ))); $this->projectConfig->remove( ProjectConfig::PATH_ROUTES.'.'.$routeUid, 'Delete route', ); - if (Event::hasListeners(RouteDeleted::class)) { - Event::dispatch(new RouteDeleted(new Route( - uriParts: $route['uriParts'], - template: $route['template'], - siteUid: $route['siteUid'], - uid: $routeUid, - ))); - } + event(new RouteDeleted(new Route( + uriParts: $route['uriParts'], + template: $route['template'], + siteUid: $route['siteUid'], + uid: $routeUid, + ))); $this->projectConfigRoutes = null; diff --git a/src/Section/Sections.php b/src/Section/Sections.php index d734ac67ce2..5735ed3b871 100644 --- a/src/Section/Sections.php +++ b/src/Section/Sections.php @@ -49,7 +49,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Throwable; use Tpetry\QueryExpressions\Language\Alias; use yii\base\InvalidConfigException; @@ -428,9 +427,7 @@ public function saveSection(Section $section): bool { $isNewSection = ! $section->id; - if (Event::hasListeners(SavingSection::class)) { - Event::dispatch(new SavingSection($section, $isNewSection)); - } + event(new SavingSection($section, $isNewSection)); if ($isNewSection) { $section->uid ??= Str::uuid()->toString(); @@ -744,9 +741,7 @@ public function handleChangedSection(ConfigEvent $event): void $this->ensureSingleEntry($section, $siteSettingData); } - if (Event::hasListeners(SectionSaved::class)) { - Event::dispatch(new SectionSaved($section, $isNewSection)); - } + event(new SectionSaved($section, $isNewSection)); // Invalidate entry caches Craft::$app->getElements()->invalidateCachesForElementType(Entry::class); @@ -965,9 +960,7 @@ public function deleteSectionById(int $sectionId): bool */ public function deleteSection(Section $section): bool { - if (Event::hasListeners(DeletingSection::class)) { - Event::dispatch(new DeletingSection($section)); - } + event(new DeletingSection($section)); // Remove the section from the project config $this->projectConfig->remove( @@ -993,9 +986,7 @@ public function handleDeletedSection(ConfigEvent $event): void /** @var Section $section */ $section = $this->getSectionById($sectionModel->id); - if (Event::hasListeners(ApplyingSectionDelete::class)) { - Event::dispatch(new ApplyingSectionDelete($section)); - } + event(new ApplyingSectionDelete($section)); DB::beginTransaction(); try { @@ -1043,9 +1034,7 @@ public function handleDeletedSection(ConfigEvent $event): void // Clear caches $this->refreshSections(); - if (Event::hasListeners(SectionDeleted::class)) { - Event::dispatch(new SectionDeleted($section)); - } + event(new SectionDeleted($section)); // Invalidate entry caches Craft::$app->getElements()->invalidateCachesForElementType(Entry::class); diff --git a/src/Site/SiteGroups.php b/src/Site/SiteGroups.php index cea350d6027..ef2cd59997d 100644 --- a/src/Site/SiteGroups.php +++ b/src/Site/SiteGroups.php @@ -22,7 +22,6 @@ use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; #[Singleton] @@ -80,9 +79,7 @@ public function saveGroup(SiteGroup $group): bool { $isNewGroup = ! $group->id; - if (Event::hasListeners(SavingSiteGroup::class)) { - Event::dispatch(new SavingSiteGroup($group, $isNewGroup)); - } + event(new SavingSiteGroup($group, $isNewGroup)); if ($isNewGroup) { $group->uid = Str::uuid()->toString(); @@ -127,9 +124,7 @@ public function handleChangedGroup(ConfigEvent $event): void // Clear caches $this->refreshGroups(); - if (Event::hasListeners(SavedSiteGroup::class)) { - Event::dispatch(new SavedSiteGroup($this->getGroupById($groupModel->id), $isNewGroup)); - } + event(new SavedSiteGroup($this->getGroupById($groupModel->id), $isNewGroup)); } /** @@ -146,18 +141,14 @@ public function handleDeletedGroup(ConfigEvent $event): void $group = $this->getGroupById($groupModel->id); - if (Event::hasListeners(ApplyingSiteGroupDelete::class)) { - Event::dispatch(new ApplyingSiteGroupDelete($group)); - } + event(new ApplyingSiteGroupDelete($group)); $groupModel->delete(); // Clear caches $this->refreshGroups(); - if (Event::hasListeners(DeletedSiteGroup::class)) { - Event::dispatch(new DeletedSiteGroup($group)); - } + event(new DeletedSiteGroup($group)); } /** @@ -193,9 +184,7 @@ public function deleteGroup(SiteGroup $group): bool return false; } - if (Event::hasListeners(DeletingSiteGroup::class)) { - Event::dispatch(new DeletingSiteGroup($group)); - } + event(new DeletingSiteGroup($group)); $this->projectConfig->remove( path: ProjectConfig::PATH_SITE_GROUPS.'.'.$group->uid, diff --git a/src/Site/Sites.php b/src/Site/Sites.php index 016e23688c6..afff54f444c 100644 --- a/src/Site/Sites.php +++ b/src/Site/Sites.php @@ -38,7 +38,6 @@ use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use InvalidArgumentException; use Throwable; use Tpetry\QueryExpressions\Language\Alias; @@ -397,13 +396,11 @@ public function saveSite(Site $site): bool $primarySite = $this->allSitesById->isEmpty() ? null : $this->getPrimarySite(); - if (Event::hasListeners(SavingSite::class)) { - Event::dispatch(new SavingSite( - site: $site, - isNew: $isNewSite, - oldPrimarySiteId: $primarySite->id ?? null, - )); - } + event(new SavingSite( + site: $site, + isNew: $isNewSite, + oldPrimarySiteId: $primarySite->id ?? null, + )); if ($isNewSite) { $site->uid = Str::uuid()->toString(); @@ -525,13 +522,11 @@ public function handleChangedSite(ConfigEvent $event): void } } - if (Event::hasListeners(SiteSaved::class)) { - Event::dispatch(new SiteSaved( - site: $site, - isNew: $isNewSite, - oldPrimarySiteId: $oldPrimarySiteId, - )); - } + event(new SiteSaved( + site: $site, + isNew: $isNewSite, + oldPrimarySiteId: $oldPrimarySiteId, + )); // Invalidate all element caches Craft::$app->getElements()->invalidateAllCaches(); @@ -547,11 +542,7 @@ public function handleChangedSite(ConfigEvent $event): void */ public function reorderSites(array $siteIds): bool { - if (Event::hasListeners(ReorderingSites::class)) { - Event::dispatch(new ReorderingSites( - siteIds: $siteIds, - )); - } + event(new ReorderingSites(siteIds: $siteIds)); $uidsByIds = DB::table(Table::SITES)->uidsByIds($siteIds); @@ -567,11 +558,7 @@ public function reorderSites(array $siteIds): bool ); } - if (Event::hasListeners(SitesReordered::class)) { - Event::dispatch(new SitesReordered( - siteIds: $siteIds, - )); - } + event(new SitesReordered(siteIds: $siteIds)); return true; } @@ -613,15 +600,10 @@ public function deleteSite(Site $site, ?int $transferContentTo = null): bool throw new Exception('You cannot delete the primary site.'); } - if (Event::hasListeners(DeletingSite::class)) { - Event::dispatch($event = new DeletingSite( - site: $site, - transferContentTo: $transferContentTo, - )); + event($event = new DeletingSite(site: $site, transferContentTo: $transferContentTo)); - if (! $event->isValid) { - return false; - } + if (! $event->isValid) { + return false; } // TODO: Move this code into entries module, etc. @@ -756,9 +738,7 @@ public function handleDeletedSite(ConfigEvent $event): void /** @var Site $site */ $site = $this->getSiteById($siteRecord->id); - if (Event::hasListeners(ApplyingSiteDelete::class)) { - Event::dispatch(new ApplyingSiteDelete($site)); - } + event(new ApplyingSiteDelete($site)); DB::transaction(function () use ($siteRecord) { DB::table(Table::SITES)->softDelete($siteRecord->id); @@ -775,9 +755,7 @@ public function handleDeletedSite(ConfigEvent $event): void $this->setCurrentSite($this->primarySite); } - if (Event::hasListeners(SiteDeleted::class)) { - Event::dispatch(new SiteDeleted($site)); - } + event(new SiteDeleted($site)); // Invalidate all element caches Craft::$app->getElements()->invalidateAllCaches(); @@ -975,8 +953,6 @@ private function processNewPrimarySite(int $oldPrimarySiteId, int $newPrimarySit // Set the new primary site by forcing a reload from the DB. $this->refreshSites(); - if (Event::hasListeners(PrimarySiteChanged::class)) { - Event::dispatch(new PrimarySiteChanged($this->primarySite)); - } + event(new PrimarySiteChanged($this->primarySite)); } } diff --git a/src/Structure/Structures.php b/src/Structure/Structures.php index 7a389cc0f2a..cf2f2b55504 100644 --- a/src/Structure/Structures.php +++ b/src/Structure/Structures.php @@ -22,7 +22,6 @@ use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Throwable; use yii\base\Exception; @@ -422,20 +421,17 @@ private function doIt( $targetElementId = $targetElementModel->isRoot() ? null : $targetElementModel->elementId; - // Fire a 'beforeInsertElement' or 'beforeMoveElement' event - if (Event::hasListeners($beforeEvent)) { - Event::dispatch($event = new $beforeEvent( - element: $element, - structureId: $structureId, - targetElementId: $targetElementId, - action: $action, - )); + event($event = new $beforeEvent( + element: $element, + structureId: $structureId, + targetElementId: $targetElementId, + action: $action, + )); - if (! $event->isValid) { - $lock->release(); + if (! $event->isValid) { + $lock->release(); - return false; - } + return false; } // Tell the element about it @@ -483,14 +479,12 @@ private function doIt( // (see https://github.com/craftcms/cms/issues/14846) Craft::$app->getElements()->invalidateCachesForElementType($element::class); - if (Event::hasListeners($afterEvent)) { - Event::dispatch(new $afterEvent( - element: $element, - structureId: $structureId, - targetElementId: $targetElementId, - action: $action, - )); - } + event(new $afterEvent( + element: $element, + structureId: $structureId, + targetElementId: $targetElementId, + action: $action, + )); return true; } diff --git a/src/SystemMessage/SystemMessages.php b/src/SystemMessage/SystemMessages.php index ed15d99d7f5..c7b64f5b9cd 100644 --- a/src/SystemMessage/SystemMessages.php +++ b/src/SystemMessage/SystemMessages.php @@ -12,7 +12,6 @@ use Illuminate\Container\Attributes\Singleton; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; -use Illuminate\Support\Facades\Event; use Tpetry\QueryExpressions\Language\CaseGroup; use Tpetry\QueryExpressions\Language\CaseRule; use Tpetry\QueryExpressions\Operator\Comparison\Equal; @@ -70,13 +69,10 @@ public function getAllDefaultMessages(): Collection ]), ]); - if (Event::hasListeners(RegisterSystemMessages::class)) { - Event::dispatch($event = new RegisterSystemMessages($messages)); - $messages = $event->messages; - } + event($event = new RegisterSystemMessages($messages)); // Sort them all by key - $messages = $messages + $messages = $event->messages ->keyBy('key') ->sortBy('key'); diff --git a/src/Updates/Data/UpdateRelease.php b/src/Updates/Data/UpdateRelease.php index 3f67d0cac61..7d3790db1c5 100644 --- a/src/Updates/Data/UpdateRelease.php +++ b/src/Updates/Data/UpdateRelease.php @@ -5,8 +5,8 @@ namespace CraftCms\Cms\Updates\Data; use CraftCms\Cms\Updates\Events\CriticalUpdateReleased; +use DateTimeInterface; use Illuminate\Support\Facades\Date; -use Illuminate\Support\Facades\Event; /** * @internal @@ -15,7 +15,7 @@ { public function __construct( public string $version, - public ?\DateTimeInterface $date = null, + public ?DateTimeInterface $date = null, private bool $critical = false, public ?string $notes = null, ) {} @@ -26,12 +26,10 @@ public function isCritical(Update $update): bool return false; } - if (Event::hasListeners(CriticalUpdateReleased::class)) { - Event::dispatch($event = new CriticalUpdateReleased($update)); + event($event = new CriticalUpdateReleased($update)); - if ($event->isValid) { - return false; - } + if ($event->isValid) { + return false; } return true; diff --git a/src/User/UserGroups.php b/src/User/UserGroups.php index e1c1c2b0683..d337183b411 100644 --- a/src/User/UserGroups.php +++ b/src/User/UserGroups.php @@ -235,9 +235,7 @@ public function saveGroup(UserGroup $group): bool $isNewGroup = ! $group->id; - if (Event::hasListeners(SavingUserGroup::class)) { - Event::dispatch(new SavingUserGroup($group, $isNewGroup)); - } + event(new SavingUserGroup($group, $isNewGroup)); $group->uid ??= $isNewGroup ? Str::uuid()->toString() @@ -275,9 +273,7 @@ public function handleChangedUserGroup(ConfigEvent $event): void // Prevent permission information from being saved. Allowing it would prevent the appropriate event from firing. $event->newValue['permissions'] = $event->oldValue['permissions'] ?? []; - if (Event::hasListeners(UserGroupSaved::class)) { - Event::dispatch(new UserGroupSaved($this->getGroupById($groupModel->id), $isNewGroup)); - } + event(new UserGroupSaved($this->getGroupById($groupModel->id), $isNewGroup)); // Invalidate user caches Craft::$app->getElements()->invalidateCachesForElementType(User::class); @@ -297,15 +293,11 @@ public function handleDeletedUserGroup(ConfigEvent $event): void return; } - if (Event::hasListeners(ApplyingUserGroupDelete::class)) { - Event::dispatch(new ApplyingUserGroupDelete($group)); - } + event(new ApplyingUserGroupDelete($group)); DB::table(Table::USERGROUPS)->where('uid', $uid)->delete(); - if (Event::hasListeners(UserGroupDeleted::class)) { - Event::dispatch(new UserGroupDeleted($group)); - } + event(new UserGroupDeleted($group)); // Invalidate user caches Craft::$app->getElements()->invalidateCachesForElementType(User::class); @@ -328,9 +320,7 @@ public function deleteGroup(UserGroup $group): bool { Edition::require(Edition::Pro); - if (Event::hasListeners(DeletingUserGroup::class)) { - Event::dispatch(new DeletingUserGroup($group)); - } + event(new DeletingUserGroup($group)); $this->projectConfig->remove( ProjectConfig::PATH_USER_GROUPS.'.'.$group->uid, diff --git a/src/User/UserPermissions.php b/src/User/UserPermissions.php index 6f842895c78..0423b48b540 100644 --- a/src/User/UserPermissions.php +++ b/src/User/UserPermissions.php @@ -37,7 +37,6 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use RuntimeException; use Tpetry\QueryExpressions\Language\Alias; @@ -104,12 +103,9 @@ public function getAllPermissions(): Collection $this->volumePermissions($this->allPermissions); $this->utilityPermissions($this->allPermissions); - if (Event::hasListeners(RegisterUserPermissions::class)) { - Event::dispatch($event = new RegisterUserPermissions($this->allPermissions)); - $this->allPermissions = $event->permissions; - } + event($event = new RegisterUserPermissions($this->allPermissions)); - return $this->allPermissions; + return $event->permissions; } /** @@ -210,9 +206,7 @@ public function saveGroupPermissions(int $groupId, array $permissions): bool message: "Update permissions for user group “{$group->handle}”", ); - if (Event::hasListeners(UserGroupPermissionsSaved::class)) { - Event::dispatch(new UserGroupPermissionsSaved($groupId, $permissions)); - } + event(new UserGroupPermissionsSaved($groupId, $permissions)); return true; } @@ -328,9 +322,7 @@ public function saveUserPermissions(int $userId, array $permissions): bool $this->permissionsByUserId ??= collect(); $this->permissionsByUserId[$userId] = $groupPermissions->merge($permissions)->unique(); - if (Event::hasListeners(UserPermissionsSaved::class)) { - Event::dispatch(new UserPermissionsSaved($userId, $permissions)); - } + event(new UserPermissionsSaved($userId, $permissions)); return true; } diff --git a/src/User/Users.php b/src/User/Users.php index 8dd9ed37abd..9470059d484 100644 --- a/src/User/Users.php +++ b/src/User/Users.php @@ -343,13 +343,10 @@ public function saveUserPhoto( $assetsService = Craft::$app->getAssets(); $photoId = $user->photoId; - if (Event::hasListeners(SavingUserPhoto::class)) { - Event::dispatch($event = new SavingUserPhoto($user, $photoId)); - $photoId = $event->photoId; - } + event($event = new SavingUserPhoto($user, $photoId)); // If the photo exists, just replace the file. - if ($photoId && ($photo = Craft::$app->getAssets()->getAssetById($photoId)) !== null) { + if ($event->photoId && ($photo = Craft::$app->getAssets()->getAssetById($event->photoId)) !== null) { $assetsService->replaceAssetFile($photo, $fileLocation, $filename, $mimeType); } else { $volume = $this->userPhotoVolume(); @@ -372,9 +369,7 @@ public function saveUserPhoto( $elementsService->saveElement($user, false); } - if (Event::hasListeners(UserPhotoSaved::class)) { - Event::dispatch(new UserPhotoSaved($user, $photo->id)); - } + event(new UserPhotoSaved($user, $photo->id)); } /** @@ -453,18 +448,14 @@ public function deleteUserPhoto(User $user): bool { $photoId = $user->photoId; - if (Event::hasListeners(DeletingUserPhoto::class)) { - Event::dispatch(new DeletingUserPhoto($user, $photoId)); - } + event(new DeletingUserPhoto($user, $photoId)); $result = Craft::$app->getElements()->deleteElementById($photoId, Asset::class); if ($result) { $user->setPhoto(); - if (Event::hasListeners(UserPhotoDeleted::class)) { - Event::dispatch(new UserPhotoDeleted($user, $photoId)); - } + event(new UserPhotoDeleted($user, $photoId)); } return $result; @@ -551,8 +542,8 @@ public function handleInvalidLogin(User $user): void // Update the User element too $user->lastInvalidLoginDate = $now; - if (! $alreadyLocked && $user->locked && Event::hasListeners(UserLocked::class)) { - Event::dispatch(new UserLocked($user)); + if (! $alreadyLocked && $user->locked) { + event(new UserLocked($user)); } if ($indexAttributesChanged) { @@ -569,11 +560,10 @@ public function handleInvalidLogin(User $user): void */ public function activateUser(User $user): void { - if (Event::hasListeners(ActivatingUser::class)) { - Event::dispatch($event = new ActivatingUser($user)); - if (! $event->isValid) { - throw new InvalidElementException($user); - } + event($event = new ActivatingUser($user)); + + if (! $event->isValid) { + throw new InvalidElementException($user); } $originalUser = clone $user; @@ -621,9 +611,7 @@ public function activateUser(User $user): void throw $e; } - if (Event::hasListeners(UserActivated::class)) { - Event::dispatch(new UserActivated($user)); - } + event(new UserActivated($user)); if ($indexAttributesChanged) { $this->invalidateIndexCaches(); @@ -640,11 +628,10 @@ public function activateUser(User $user): void */ public function deactivateUser(User $user): void { - if (Event::hasListeners(DeactivatingUser::class)) { - Event::dispatch($event = new DeactivatingUser($user)); - if (! $event->isValid) { - throw new InvalidElementException($user); - } + event($event = new DeactivatingUser($user)); + + if (! $event->isValid) { + throw new InvalidElementException($user); } DB::beginTransaction(); @@ -676,9 +663,7 @@ public function deactivateUser(User $user): void throw $e; } - if (Event::hasListeners(UserDeactivated::class)) { - Event::dispatch(new UserDeactivated($user)); - } + event(new UserDeactivated($user)); if ($indexAttributesChanged) { $this->invalidateIndexCaches(); @@ -730,11 +715,10 @@ public function verifyEmailForUser(User $user): void */ public function unlockUser(User $user): void { - if (Event::hasListeners(UnlockingUser::class)) { - Event::dispatch($event = new UnlockingUser($user)); - if (! $event->isValid) { - throw new InvalidElementException($user); - } + event($event = new UnlockingUser($user)); + + if (! $event->isValid) { + throw new InvalidElementException($user); } DB::beginTransaction(); @@ -759,9 +743,7 @@ public function unlockUser(User $user): void $user->invalidLoginCount = null; $user->lockoutDate = null; - if (Event::hasListeners(UserUnlocked::class)) { - Event::dispatch($event = new UserUnlocked($user)); - } + event(new UserUnlocked($user)); if ($indexAttributesChanged) { $this->invalidateIndexCaches(); @@ -777,11 +759,10 @@ public function unlockUser(User $user): void */ public function suspendUser(User $user): void { - if (Event::hasListeners(SuspendingUser::class)) { - Event::dispatch($event = new SuspendingUser($user)); - if (! $event->isValid) { - throw new InvalidElementException($user); - } + event($event = new SuspendingUser($user)); + + if (! $event->isValid) { + throw new InvalidElementException($user); } $userModel = UserModel::findOrFail($user->id); @@ -796,9 +777,7 @@ public function suspendUser(User $user): void ->where('user_id', $user->id) ->delete(); - if (Event::hasListeners(UserSuspended::class)) { - Event::dispatch(new UserSuspended($user)); - } + event(new UserSuspended($user)); if ($indexAttributesChanged) { $this->invalidateIndexCaches(); @@ -814,11 +793,10 @@ public function suspendUser(User $user): void */ public function unsuspendUser(User $user): void { - if (Event::hasListeners(UnsuspendingUser::class)) { - Event::dispatch($event = new UnsuspendingUser($user)); - if (! $event->isValid) { - throw new InvalidElementException($user); - } + event($event = new UnsuspendingUser($user)); + + if (! $event->isValid) { + throw new InvalidElementException($user); } DB::beginTransaction(); @@ -840,9 +818,7 @@ public function unsuspendUser(User $user): void // Update the User model too $user->suspended = false; - if (Event::hasListeners(UserUnsuspended::class)) { - Event::dispatch($event = new UserUnsuspended($user)); - } + event(new UserUnsuspended($user)); if ($indexAttributesChanged) { $this->invalidateIndexCaches(); @@ -1011,21 +987,20 @@ public function assignUserToGroups(int $userId, array $groupIds): bool $newGroupIds = array_keys($newGroupIds); - if (Event::hasListeners(AssigningUserToGroups::class)) { - Event::dispatch($event = new AssigningUserToGroups( - userId: $userId, - groupIds: $groupIds, - removedGroupIds: $removedGroupIds, - newGroupIds: $newGroupIds, - )); + event($event = new AssigningUserToGroups( + userId: $userId, + groupIds: $groupIds, + removedGroupIds: $removedGroupIds, + newGroupIds: $newGroupIds, + )); - if (! $event->isValid) { - return false; - } - $removedGroupIds = $event->removedGroupIds; - $newGroupIds = $event->newGroupIds; + if (! $event->isValid) { + return false; } + $removedGroupIds = $event->removedGroupIds; + $newGroupIds = $event->newGroupIds; + // Make sure the event hasn't left us with nothing to do if (empty($removedGroupIds) && empty($newGroupIds)) { return true; @@ -1058,14 +1033,12 @@ public function assignUserToGroups(int $userId, array $groupIds): bool throw $e; } - if (Event::hasListeners(UserAssignedToGroups::class)) { - Event::dispatch(new UserAssignedToGroups( - userId: $userId, - groupIds: $groupIds, - removedGroupIds: $removedGroupIds, - newGroupIds: $newGroupIds, - )); - } + event(new UserAssignedToGroups( + userId: $userId, + groupIds: $groupIds, + removedGroupIds: $removedGroupIds, + newGroupIds: $newGroupIds, + )); $this->invalidateIndexCaches(); @@ -1089,13 +1062,9 @@ public function getDefaultUserGroups(User $user): array } } - if (Event::hasListeners(DefineDefaultUserGroups::class)) { - Event::dispatch($event = new DefineDefaultUserGroups($user, $groups)); + event($event = new DefineDefaultUserGroups($user, $groups)); - return $event->userGroups; - } - - return $groups; + return $event->userGroups; } /** @@ -1114,11 +1083,10 @@ public function assignUserToDefaultGroup(User $user): bool return false; } - if (Event::hasListeners(AssigningUserToDefaultGroups::class)) { - Event::dispatch($event = new AssigningUserToDefaultGroups($user, $groups)); - if (! $event->isValid) { - return false; - } + event($event = new AssigningUserToDefaultGroups($user, $groups)); + + if (! $event->isValid) { + return false; } $groupIds = Arr::pluck($groups, 'id'); @@ -1127,9 +1095,7 @@ public function assignUserToDefaultGroup(User $user): bool return false; } - if (Event::hasListeners(UserAssignedToDefaultGroups::class)) { - Event::dispatch(new UserAssignedToDefaultGroups($user, $groups)); - } + event(new UserAssignedToDefaultGroups($user, $groups)); return true; } diff --git a/src/Utility/Utilities.php b/src/Utility/Utilities.php index 830b7126d22..314ace2002c 100644 --- a/src/Utility/Utilities.php +++ b/src/Utility/Utilities.php @@ -24,7 +24,6 @@ use Illuminate\Container\Attributes\Singleton; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Event; /** * The Utilities service provides APIs for managing utilities. @@ -75,14 +74,11 @@ public function getAllUtilityTypes(): Collection Migrations::class, ); - if (Event::hasListeners(RegisterUtilities::class)) { - Event::dispatch($event = new RegisterUtilities($utilityTypes)); - $utilityTypes = $event->types; - } + event($event = new RegisterUtilities($utilityTypes)); $disabledUtilities = array_flip($this->generalConfig->disabledUtilities); - return $utilityTypes + return $event->types /** @var class-string $class */ ->filter(fn (string $class) => ! isset($disabledUtilities[$class::id()]) && $class::isSelectable()); } diff --git a/src/Utility/Utilities/AssetIndexes.php b/src/Utility/Utilities/AssetIndexes.php index 6d310983366..755618359ba 100644 --- a/src/Utility/Utilities/AssetIndexes.php +++ b/src/Utility/Utilities/AssetIndexes.php @@ -13,7 +13,7 @@ use CraftCms\Cms\Translation\Locale; use CraftCms\Cms\Utility\Events\ListVolumes; use CraftCms\Cms\Utility\Utility; -use Illuminate\Support\Facades\Event; +use Override; use function CraftCms\Cms\t; @@ -25,7 +25,7 @@ final class AssetIndexes extends Utility /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function displayName(): string { return t('Asset Indexes'); @@ -34,7 +34,7 @@ public static function displayName(): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function id(): string { return 'asset-indexes'; @@ -43,7 +43,7 @@ public static function id(): string /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function icon(): string { return 'image'; @@ -58,20 +58,15 @@ public static function volumes(): array { $volumes = Craft::$app->getVolumes()->getAllVolumes(); - if (Event::hasListeners(ListVolumes::class)) { - $event = new ListVolumes($volumes); - Event::dispatch($event); + event($event = new ListVolumes($volumes)); - return $event->volumes; - } - - return $volumes; + return $event->volumes; } /** * {@inheritdoc} */ - #[\Override] + #[Override] public static function contentHtml(): string { $volumeOptions = []; diff --git a/src/Utility/Utilities/ClearCaches.php b/src/Utility/Utilities/ClearCaches.php index ef94966b4fa..492f5b62d95 100644 --- a/src/Utility/Utilities/ClearCaches.php +++ b/src/Utility/Utilities/ClearCaches.php @@ -17,7 +17,6 @@ use Exception; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; -use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\File; use Override; @@ -204,12 +203,9 @@ public static function cacheOptions(): array ], ]; - if (Event::hasListeners(RegisterCacheOptions::class)) { - Event::dispatch($event = new RegisterCacheOptions($options)); - $options = $event->options; - } + event($event = new RegisterCacheOptions($options)); - return Arr::sort($options, 'label'); + return Arr::sort($event->options, 'label'); } /** @@ -231,11 +227,8 @@ public static function tagOptions(): array ]; } - if (Event::hasListeners(RegisterTagOptions::class)) { - Event::dispatch($event = new RegisterTagOptions($options)); - $options = $event->options; - } + event($event = new RegisterTagOptions($options)); - return Arr::sort($options, 'label'); + return Arr::sort($event->options, 'label'); } } From fbaad867ac6575cd6284a12df8d05898c46e9828 Mon Sep 17 00:00:00 2001 From: Rias Date: Thu, 22 Jan 2026 16:56:40 +0100 Subject: [PATCH 2/3] Fix collection not being the same object --- tests/User/UserPermissionsTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/User/UserPermissionsTest.php b/tests/User/UserPermissionsTest.php index 37774cc8a6b..ce3e3a7303c 100644 --- a/tests/User/UserPermissionsTest.php +++ b/tests/User/UserPermissionsTest.php @@ -51,16 +51,16 @@ actingAs($admin); - expect($this->userPermissions->getAllPermissions()) - ->toEqualCanonicalizing($this->userPermissions->getAssignablePermissions()); + expect($this->userPermissions->getAllPermissions()->toArray()) + ->toEqualCanonicalizing($this->userPermissions->getAssignablePermissions()->toArray()); $user = \CraftCms\Cms\User\Models\User::factory()->create(); actingAs($user->asElement()); - expect($this->userPermissions->getAllPermissions()) + expect($this->userPermissions->getAllPermissions()->toArray()) ->not() - ->toEqualCanonicalizing($this->userPermissions->getAssignablePermissions()); + ->toEqualCanonicalizing($this->userPermissions->getAssignablePermissions()->toArray()); }); test('getPermissionsByGroupId & doesGroupHavePermission', function () { From 68342603b78dfbf7650016ebb4974983cc955123 Mon Sep 17 00:00:00 2001 From: Rias Date: Thu, 22 Jan 2026 17:03:45 +0100 Subject: [PATCH 3/3] Fix another test --- src/Updates/Data/UpdateRelease.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Updates/Data/UpdateRelease.php b/src/Updates/Data/UpdateRelease.php index 7d3790db1c5..fbbe600c947 100644 --- a/src/Updates/Data/UpdateRelease.php +++ b/src/Updates/Data/UpdateRelease.php @@ -28,11 +28,7 @@ public function isCritical(Update $update): bool event($event = new CriticalUpdateReleased($update)); - if ($event->isValid) { - return false; - } - - return true; + return $event->isValid; } public static function fromArray(array $data): self