diff --git a/composer.json b/composer.json index 2156be92b..e5eca9e50 100644 --- a/composer.json +++ b/composer.json @@ -155,6 +155,7 @@ "ext-ftp": "*" }, "replace": { + "hypervel/activity-log": "self.version", "hypervel/ai": "self.version", "hypervel/api-client": "self.version", "hypervel/attributes": "self.version", @@ -249,12 +250,14 @@ "aws/aws-sdk-php": "<3.369.1", "intervention/image": "<4.2 || >=5.0", "league/flysystem-ftp": "<3.13", - "league/flysystem-sftp-v3": "<3.13" + "league/flysystem-sftp-v3": "<3.13", + "spatie/laravel-activitylog": "*" }, "minimum-stability": "stable", "prefer-stable": true, "autoload": { "psr-4": { + "Hypervel\\ActivityLog\\": "src/activity-log/src/", "Hypervel\\Ai\\": "src/ai/src/", "Hypervel\\ApiClient\\": "src/api-client/src/", "Hypervel\\Auth\\": "src/auth/src/", @@ -350,6 +353,7 @@ "Hypervel\\Workbench\\": "src/workbench/src/" }, "files": [ + "src/activity-log/src/helpers.php", "src/ai/src/functions.php", "src/coordinator/src/functions.php", "src/coroutine/src/functions.php", @@ -430,6 +434,7 @@ "Socialite": "Hypervel\\Socialite\\Socialite" }, "providers": [ + "Hypervel\\ActivityLog\\ActivityLogServiceProvider", "Hypervel\\Ai\\AiServiceProvider", "Hypervel\\Auth\\AuthServiceProvider", "Hypervel\\Auth\\Passwords\\PasswordResetServiceProvider", diff --git a/src/activity-log/LICENSE.md b/src/activity-log/LICENSE.md new file mode 100644 index 000000000..4b2c31a2d --- /dev/null +++ b/src/activity-log/LICENSE.md @@ -0,0 +1,25 @@ +The MIT License (MIT) + +Copyright (c) Spatie bvba + +Copyright (c) SonicStack + +Copyright (c) Hypervel + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/src/activity-log/README.md b/src/activity-log/README.md new file mode 100644 index 000000000..e5537e5a4 --- /dev/null +++ b/src/activity-log/README.md @@ -0,0 +1,25 @@ +Activity Log for Hypervel +=== + +Documentation: https://hypervel.org/docs/activity-log + +## Differences From Spatie Laravel Activity Log + +- Public names use `ActivityLog` and `activity-log` casing. The global + `activity()` helper is retained. +- `activity(null)` selects the configured default. Empty string and `"0"` are + distinct log names. `useLog(null)` and `inLog(null)` explicitly set a null name. +- Automatic model logging uses the event's in-memory snapshot without another + subject query. `refreshBeforeLogging()` provides an explicit, + transaction-only refresh for database-generated values. +- Dotted relation attributes retain the configured key even when traversal + resolves a snake-case, camel-case, or dynamic-relation alias. +- Optional buffering is coroutine-scoped, transaction-aware, and flushed in + bounded batches at Hypervel lifecycle boundaries. +- `setLogStatus()` is replaced by `enableLogging()`, `disableLogging()`, and + `withoutLogging()`. Tests reset callbacks through `flushState()` rather than + the upstream test-only `clearBeforeLoggingCallbacks()` alias. +- This package cannot be installed alongside `spatie/laravel-activitylog` + because both packages provide `activity()` and use the same default table. + +Ported from: https://github.com/spatie/laravel-activitylog diff --git a/src/activity-log/composer.json b/src/activity-log/composer.json new file mode 100644 index 000000000..e5baeeb6b --- /dev/null +++ b/src/activity-log/composer.json @@ -0,0 +1,72 @@ +{ + "name": "hypervel/activity-log", + "type": "library", + "description": "Coroutine-safe activity logging for Hypervel applications.", + "license": "MIT", + "keywords": [ + "php", + "swoole", + "activity-log", + "hypervel" + ], + "authors": [ + { + "name": "Albert Chen", + "email": "albert@hypervel.org" + }, + { + "name": "Raj Siva-Rajah", + "homepage": "https://github.com/binaryfire" + } + ], + "support": { + "issues": "https://github.com/hypervel/components/issues", + "source": "https://github.com/hypervel/components" + }, + "autoload": { + "psr-4": { + "Hypervel\\ActivityLog\\": "src/" + }, + "files": [ + "src/helpers.php" + ] + }, + "require": { + "php": "^8.4", + "hypervel/attributes": "^0.4", + "hypervel/auth": "^0.4", + "hypervel/collections": "^0.4", + "hypervel/conditionable": "^0.4", + "hypervel/config": "^0.4", + "hypervel/console": "^0.4", + "hypervel/container": "^0.4", + "hypervel/context": "^0.4", + "hypervel/contracts": "^0.4", + "hypervel/coroutine": "^0.4", + "hypervel/database": "^0.4", + "hypervel/events": "^0.4", + "hypervel/foundation": "^0.4", + "hypervel/macroable": "^0.4", + "hypervel/queue": "^0.4", + "hypervel/support": "^0.4", + "laravel/serializable-closure": "^2.0.11", + "nesbot/carbon": "^3.13.1", + "symfony/console": "^8.1.10" + }, + "conflict": { + "spatie/laravel-activitylog": "*" + }, + "config": { + "sort-packages": true + }, + "extra": { + "branch-alias": { + "dev-main": "0.4-dev" + }, + "hypervel": { + "providers": [ + "Hypervel\\ActivityLog\\ActivityLogServiceProvider" + ] + } + } +} diff --git a/src/activity-log/config/activity-log.php b/src/activity-log/config/activity-log.php new file mode 100644 index 000000000..a8ab22bd6 --- /dev/null +++ b/src/activity-log/config/activity-log.php @@ -0,0 +1,89 @@ + (bool) env('ACTIVITY_LOG_ENABLED', true), + + /* + * When the clean command is executed, all activities older than + * the number of days specified here will be deleted. + */ + 'clean_after_days' => 365, + + /* + * The clean command deletes old activities in batches of this size. + */ + 'clean_batch_size' => (int) env('ACTIVITY_LOG_CLEAN_BATCH_SIZE', 1000), + + /* + * Enable cleanup to delete activities using the retention and batch size + * above. Otherwise, activities remain until you run activity-log:clean. + */ + 'cleanup' => [ + 'enabled' => (bool) env('ACTIVITY_LOG_CLEANUP_ENABLED', false), + 'schedule' => env('ACTIVITY_LOG_CLEANUP_SCHEDULE', '9 4 * * *'), + ], + + /* + * If no log name is passed to the activity() helper + * we use this default log name. + */ + 'default_log_name' => 'default', + + /* + * You can specify an auth driver here that gets user models. + * If this is null we'll use the current Hypervel auth driver. + */ + 'default_auth_driver' => null, + + /* + * If set to true, the subject relationship on activities + * will include soft deleted models. + */ + 'include_soft_deleted_subjects' => false, + + /* + * This model will be used to log activity. + * It should implement the activity contract and extend Hypervel's + * Eloquent model. + */ + 'activity_model' => Activity::class, + + /* + * These attributes will be excluded from logging for all models. + * Model-specific exclusions via logExcept() are merged with these. + */ + 'default_except_attributes' => [], + + /* + * When enabled, activities are buffered in memory and inserted in bounded + * batches at Hypervel lifecycle boundaries. This can significantly reduce + * the number of database queries when many activities are logged during a + * single request or job. + * + * Only enable this if your application logs a high volume of activities + * per request or job. The returned in-memory activity never receives the + * ID generated by the later bulk insert. + */ + 'buffer' => [ + 'enabled' => (bool) env('ACTIVITY_LOG_BUFFER_ENABLED', false), + 'batch_size' => (int) env('ACTIVITY_LOG_BUFFER_BATCH_SIZE', 500), + ], + + /* + * These action classes can be overridden to customize how activities + * are logged and cleaned. Your custom classes must extend the originals. + */ + 'actions' => [ + 'log_activity' => LogActivityAction::class, + 'clean_log' => CleanActivityLogAction::class, + ], +]; diff --git a/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php b/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php new file mode 100644 index 000000000..47a2b152d --- /dev/null +++ b/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php @@ -0,0 +1,44 @@ +id(); + $table->string('log_name')->nullable(); + $table->text('description'); + $table->nullableMorphs('subject', 'activity_log_subject'); + $table->string('event')->nullable(); + $table->nullableMorphs('causer', 'activity_log_causer'); + $table->jsonb('attribute_changes')->nullable(); + $table->jsonb('properties')->nullable(); + $table->timestamps(); + + $table->index( + ['created_at', 'id'], + 'activity_log_created_at_id_index', + ); + $table->index( + ['log_name', 'created_at', 'id'], + 'activity_log_name_created_at_id_index', + ); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('activity_log'); + } +}; diff --git a/src/activity-log/src/Actions/CleanActivityLogAction.php b/src/activity-log/src/Actions/CleanActivityLogAction.php new file mode 100644 index 000000000..3d0f895d0 --- /dev/null +++ b/src/activity-log/src/Actions/CleanActivityLogAction.php @@ -0,0 +1,116 @@ +getCutOffDate($maxAgeInDays); + + return $this->deleteOldActivities($cutOffDate, $logName); + } + + /** + * Get the activity cutoff date. + */ + protected function getCutOffDate(int $maxAgeInDays): string + { + $activity = $this->configuration->activityModelInstance(); + + /** @var string $cutOffDate */ + $cutOffDate = $activity->fromDateTime( + CarbonImmutable::now()->subDays($maxAgeInDays), + ); + + return $cutOffDate; + } + + /** + * Delete old activities in bounded batches. + */ + protected function deleteOldActivities(string $cutOffDate, ?string $logName): int + { + $activity = $this->configuration->activityModelInstance(); + $createdAtColumn = $activity->getCreatedAtColumn() + ?? throw InvalidConfiguration::activityModelDoesNotHaveCreatedAtColumn( + $activity::class, + ); + $key = $activity->getKeyName() + ?? throw InvalidConfiguration::activityModelDoesNotHavePrimaryKey($activity::class); + $batchSize = $this->configuration->cleanBatchSize(); + + $deleted = 0; + + while (true) { + $ids = $this->newEligibleQuery( + $activity, + $createdAtColumn, + $cutOffDate, + $logName, + ) + ->useWritePdo() + ->orderBy($createdAtColumn) + ->orderBy($key) + ->limit($batchSize) + ->pluck($key); + + if ($ids->isEmpty()) { + break; + } + + $deleted += $this->newEligibleQuery( + $activity, + $createdAtColumn, + $cutOffDate, + $logName, + ) + ->whereKey($ids->all()) + ->delete(); + } + + return $deleted; + } + + /** + * Create a fresh query for activities eligible for deletion. + * + * @return Builder + */ + private function newEligibleQuery( + Model $activity, + string $createdAtColumn, + string $cutOffDate, + ?string $logName, + ): Builder { + $query = $activity->newQuery() + ->where($createdAtColumn, '<', $cutOffDate); + + if ($logName !== null) { + $query->where('log_name', $logName); + } + + return $query; + } +} diff --git a/src/activity-log/src/Actions/LogActivityAction.php b/src/activity-log/src/Actions/LogActivityAction.php new file mode 100644 index 000000000..f7cb70669 --- /dev/null +++ b/src/activity-log/src/Actions/LogActivityAction.php @@ -0,0 +1,178 @@ + */ + protected static array $beforeLoggingCallbacks = []; + + public function __construct( + protected ActivityLogConfiguration $configuration, + protected Container $container, + ) { + } + + /** + * Register a callback to run before an activity is persisted. + * + * The callback persists in a static property for the worker lifetime + * and affects every subsequent request. + * + * @param Closure(ActivityContract&Model): void $callback + */ + #[BootOnly] + public static function beforeLogging(Closure $callback): void + { + static::$beforeLoggingCallbacks[] = $callback; + } + + // REMOVED: clearBeforeLoggingCallbacks() duplicated package test cleanup; + // flushState() is the single reset for this worker-lifetime registry. + + /** + * Prepare and persist an activity. + */ + public function execute(ActivityContract&Model $activity, string $description): ActivityContract&Model + { + $activity->setAttribute( + 'description', + $this->resolveDescription($activity, $description), + ); + + $this->transformChanges($activity); + + $this->beforeActivityLogged($activity); + + foreach (static::$beforeLoggingCallbacks as $callback) { + $callback($activity); + } + + $this->save($activity); + + return $activity; + } + + /** + * Resolve placeholders in the activity description. + */ + protected function resolveDescription(ActivityContract&Model $activity, string $description): string + { + $activityDescription = $activity->getAttribute('description'); + + return $this->replacePlaceholders( + $activityDescription === null ? $description : (string) $activityDescription, + $activity, + ); + } + + /** + * Transform activity changes before persistence. + */ + protected function transformChanges(ActivityContract&Model $activity): void + { + } + + /** + * Invoke the subject's activity hook when available. + */ + protected function beforeActivityLogged(ActivityContract&Model $activity): void + { + $subject = $activity->getRelationValue('subject'); + + if (! $subject instanceof Model) { + return; + } + + if (! method_exists($subject, 'beforeActivityLogged')) { + return; + } + + $subject->beforeActivityLogged( + $activity, + $activity->getAttribute('event') ?? '', + ); + } + + /** + * Persist or buffer the activity. + */ + protected function save(ActivityContract&Model $activity): void + { + if ($this->shouldBuffer()) { + $this->container->make(ActivityBuffer::class)->add($activity); + + return; + } + + if (! $activity->save()) { + throw CouldNotLogActivity::activityCouldNotBePersisted(); + } + } + + /** + * Determine whether activities should be buffered. + */ + protected function shouldBuffer(): bool + { + return $this->configuration->bufferEnabled(); + } + + /** + * Replace supported placeholders in a description. + */ + protected function replacePlaceholders(string $description, ActivityContract&Model $activity): string + { + /** @var string $resolved */ + $resolved = preg_replace_callback(self::PLACEHOLDER_PATTERN, function (array $matches) use ($activity): string { + $match = $matches[0]; + + $attribute = Str::before(Str::after($match, ':'), '.'); + + if (! in_array($attribute, ['subject', 'causer', 'properties'], true)) { + return $match; + } + + $propertyName = substr($match, strpos($match, '.') + 1); + + $attributeValue = $activity->getAttribute($attribute); + + if ($attributeValue === null) { + return $match; + } + + $value = data_get($attributeValue, $propertyName, $match); + + $value = enum_value($value); + + return is_scalar($value) || $value instanceof Stringable ? (string) $value : $match; + }, $description); + + return $resolved; + } + + /** + * Flush all static state. + */ + public static function flushState(): void + { + static::$beforeLoggingCallbacks = []; + } +} diff --git a/src/activity-log/src/ActivityLogManager.php b/src/activity-log/src/ActivityLogManager.php new file mode 100644 index 000000000..7394e911f --- /dev/null +++ b/src/activity-log/src/ActivityLogManager.php @@ -0,0 +1,135 @@ +container->make(ActivityLogger::class); + + return $logName === null ? $logger : $logger->useLog($logName); + } + + /** + * Register a callback to run before an activity is persisted. + * + * The callback persists for the worker lifetime and affects every + * subsequent request. + * + * @param Closure(ActivityContract&Model): void $callback + */ + #[BootOnly] + public static function beforeLogging(Closure $callback): void + { + LogActivityAction::beforeLogging($callback); + } + + /** + * Register a macro on activity loggers. + * + * The macro persists for the worker lifetime and affects every subsequent + * request. + */ + #[BootOnly] + public static function macro(string $name, callable|object $macro): void + { + ActivityLogger::macro($name, $macro); + } + + /** + * Mix an object into activity loggers. + * + * The macros persist for the worker lifetime and affect every subsequent + * request. + * + * @throws ReflectionException + */ + #[BootOnly] + public static function mixin(object $mixin, bool $replace = true): void + { + ActivityLogger::mixin($mixin, $replace); + } + + /** + * Determine whether an activity logger macro is registered. + */ + public static function hasMacro(string $name): bool + { + return ActivityLogger::hasMacro($name); + } + + /** + * Flush activity logger macros. + * + * Clearing worker-wide macros while requests are active can make concurrent + * coroutines resolve different methods. + */ + #[BootOrTestsOnly] + public static function flushMacros(): void + { + ActivityLogger::flushMacros(); + } + + /** + * Set the default causer or run a callback with one. + * + * @template TResult + * + * @param null|Closure(): TResult $callback + * @return ($callback is null ? $this : TResult) + */ + public function defaultCauser(Model|int|string|null $causer, ?Closure $callback = null): mixed + { + $resolver = $this->container->make(CauserResolver::class); + + if ($callback !== null) { + return $resolver->withCauser($causer, $callback); + } + + $resolver->setCauser($causer); + + return $this; + } + + /** + * Forward a fluent root call to a fresh activity logger. + */ + public function __call(string $method, array $parameters): mixed + { + return $this->forwardCallTo($this->logger(), $method, $parameters); + } +} diff --git a/src/activity-log/src/ActivityLogServiceProvider.php b/src/activity-log/src/ActivityLogServiceProvider.php new file mode 100644 index 000000000..edbc2a6a5 --- /dev/null +++ b/src/activity-log/src/ActivityLogServiceProvider.php @@ -0,0 +1,99 @@ +mergeConfigFrom( + dirname(__DIR__) . '/config/activity-log.php', + 'activity-log', + ); + + $this->app->bind(ActivityLogger::class); + $this->app->scoped(CauserResolver::class); + $this->app->scoped(ActivityLogStatus::class); + $this->app->scoped(ActivityBuffer::class); + } + + /** + * Bootstrap activity log services. + */ + public function boot(Dispatcher $events, Repository $config): void + { + $this->callAfterResolving(Schedule::class, static function (Schedule $schedule) use ($config): void { + if ($config->boolean('activity-log.cleanup.enabled')) { + $schedule->command(CleanActivityLogCommand::class, ['--force'])->cron($config->string('activity-log.cleanup.schedule')) + ->onOneServer()->withoutOverlapping()->runInBackground(); + } + }); + + $this->registerActivityBufferFlushing($events); + + if ($this->app->runningInConsole()) { + $this->commands([ + CleanActivityLogCommand::class, + ]); + + $this->publishes([ + dirname(__DIR__) . '/config/activity-log.php' => config_path( + 'activity-log.php', + ), + ], 'activity-log-config'); + + $this->publishesMigrations([ + dirname(__DIR__) + . '/database/publish/2026_08_04_000000_create_activity_log_table.php' => database_path( + 'migrations/2026_08_04_000000_create_activity_log_table.php', + ), + ], 'activity-log-migrations'); + } + } + + /** + * Register activity buffer lifecycle boundaries. + */ + protected function registerActivityBufferFlushing(Dispatcher $events): void + { + $this->app->terminating(static function (): void { + ActivityBuffer::finalizeCurrent(); + }); + + $events->observe( + JobAttempted::class, + static function (string $_event, array $payload): void { + /** @var JobAttempted $attempt */ + $attempt = $payload[0]; + + // Sync jobs share their caller's coroutine and buffer, so the + // enclosing HTTP or console boundary owns the flush. + if ($attempt->job instanceof SyncJob) { + return; + } + + ActivityBuffer::finalizeCurrent(); + }, + ); + + // ActivityBuffer registers its coroutine-exit fallback lazily after it + // first owns work; process shutdown is not a valid scoped boundary. + } +} diff --git a/src/activity-log/src/Commands/CleanActivityLogCommand.php b/src/activity-log/src/Commands/CleanActivityLogCommand.php new file mode 100644 index 000000000..78dc51087 --- /dev/null +++ b/src/activity-log/src/Commands/CleanActivityLogCommand.php @@ -0,0 +1,76 @@ +confirmToProceed()) { + return self::FAILURE; + } + + $this->comment('Cleaning activity log...'); + + $days = $this->option('days'); + + try { + $maxAgeInDays = $days === null + ? $this->configuration->cleanAfterDays() + : (is_int($days) || is_string($days) + ? filter_var($days, FILTER_VALIDATE_INT) + : false); + } catch (InvalidArgumentException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + if ($maxAgeInDays === false || $maxAgeInDays < 1) { + $this->error('The days option must be a positive integer.'); + + return self::FAILURE; + } + + /** @var null|string $logName */ + $logName = $this->argument('log'); + + $amountDeleted = $this->configuration->cleanActivityLogAction()->execute( + $maxAgeInDays, + $logName, + ); + + $this->info("Deleted {$amountDeleted} record(s) from the activity log."); + + $this->comment('All done!'); + + return self::SUCCESS; + } +} diff --git a/src/activity-log/src/Contracts/Activity.php b/src/activity-log/src/Contracts/Activity.php new file mode 100644 index 000000000..932597409 --- /dev/null +++ b/src/activity-log/src/Contracts/Activity.php @@ -0,0 +1,25 @@ +'; + + return new self( + "Buffered activity [{$activityClass}] targets connection [{$actualConnection}] " + . "and table [{$actualTable}], but this buffer owns connection [{$expectedConnection}] " + . "and table [{$expectedTable}].", + ); + } +} diff --git a/src/activity-log/src/Facades/ActivityLog.php b/src/activity-log/src/Facades/ActivityLog.php new file mode 100644 index 000000000..4bf46b7ac --- /dev/null +++ b/src/activity-log/src/Facades/ActivityLog.php @@ -0,0 +1,57 @@ +|\Hypervel\Support\Collection $changes) + * @method static \Hypervel\ActivityLog\Support\ActivityLogger withProperties(array|\Hypervel\Support\Collection $properties) + * @method static \Hypervel\ActivityLog\Support\ActivityLogger withProperty(string $key, mixed $value) + * + * @see \Hypervel\ActivityLog\ActivityLogManager + * + * @mixin ActivityLogManager + */ +class ActivityLog extends Facade +{ + /** + * Preserve the manager and logger's callback, intersection and conditional types through the mixin. + * + * @return list + */ + protected static function ignoredFacadeDocumenterMethods(): array + { + return ['beforeLogging', 'defaultCauser', 'log', 'tap', 'unless', 'when', 'withoutLogging']; + } + + /** + * Get the registered name of the component. + */ + protected static function getFacadeAccessor(): string + { + return ActivityLogManager::class; + } +} diff --git a/src/activity-log/src/Models/Activity.php b/src/activity-log/src/Models/Activity.php new file mode 100644 index 000000000..cd73aeec5 --- /dev/null +++ b/src/activity-log/src/Models/Activity.php @@ -0,0 +1,141 @@ + $attribute_changes + * @property null|Collection $properties + * @property null|CarbonInterface $created_at + * @property null|CarbonInterface $updated_at + * @property-read null|Model $causer + * @property-read null|Model $subject + */ +#[Table('activity_log')] +#[Unguarded] +class Activity extends Model implements ActivityContract +{ + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'attribute_changes' => 'collection', + 'properties' => 'collection', + ]; + } + + /** + * Get the subject of the activity. + * + * @return MorphTo + */ + public function subject(): MorphTo + { + $relation = $this->morphTo(); + + if (Container::getInstance() + ->make(ActivityLogConfiguration::class) + ->includeSoftDeletedSubjects()) { + $relation->getQuery()->withoutGlobalScope(SoftDeletingScope::class); + } + + return $relation; + } + + /** + * Get the causer of the activity. + * + * @return MorphTo + */ + public function causer(): MorphTo + { + return $this->morphTo(); + } + + /** + * Get an activity property. + */ + public function getProperty(string $propertyName, mixed $defaultValue = null): mixed + { + return Arr::get($this->properties ?? [], $propertyName, $defaultValue); + } + + /** + * Scope activities to the given log names. + * + * @param array|BackedEnum|string ...$logNames + */ + #[Scope] + protected function inLog(Builder $query, BackedEnum|string|array ...$logNames): void + { + $names = []; + + foreach ($logNames as $value) { + foreach (is_array($value) ? $value : [$value] as $name) { + $names[] = $name instanceof BackedEnum ? (string) $name->value : $name; + } + } + + $query->whereIn('log_name', $names); + } + + /** + * Scope activities to the given causer. + */ + #[Scope] + protected function causedBy(Builder $query, Model $causer): void + { + $query + ->where('causer_type', $causer->getMorphClass()) + ->where('causer_id', $causer->getKey()); + } + + /** + * Scope activities to the given subject. + */ + #[Scope] + protected function forSubject(Builder $query, Model $subject): void + { + $query + ->where('subject_type', $subject->getMorphClass()) + ->where('subject_id', $subject->getKey()); + } + + /** + * Scope activities to the given event. + */ + #[Scope] + protected function forEvent(Builder $query, string|ActivityEvent $event): void + { + $query->where('event', $event instanceof ActivityEvent ? $event->value : $event); + } +} diff --git a/src/activity-log/src/Models/Concerns/CausesActivity.php b/src/activity-log/src/Models/Concerns/CausesActivity.php new file mode 100644 index 000000000..35194cf0b --- /dev/null +++ b/src/activity-log/src/Models/Concerns/CausesActivity.php @@ -0,0 +1,34 @@ + + */ + public function activitiesAsCauser(): MorphMany + { + $activityModel = Container::getInstance() + ->make(ActivityLogConfiguration::class) + ->activityModel(); + + return $this->morphMany( + $activityModel, + 'causer', + ); + } +} diff --git a/src/activity-log/src/Models/Concerns/HasActivity.php b/src/activity-log/src/Models/Concerns/HasActivity.php new file mode 100644 index 000000000..8d7e4085c --- /dev/null +++ b/src/activity-log/src/Models/Concerns/HasActivity.php @@ -0,0 +1,28 @@ + + */ + public function activities(): MorphMany + { + return $this->activitiesAsSubject(); + } +} diff --git a/src/activity-log/src/Models/Concerns/LogsActivity.php b/src/activity-log/src/Models/Concerns/LogsActivity.php new file mode 100644 index 000000000..393e32200 --- /dev/null +++ b/src/activity-log/src/Models/Concerns/LogsActivity.php @@ -0,0 +1,656 @@ + Attributes selected once for the current model event. */ + protected ?array $activityLogAttributes = null; + + public bool $enableLoggingModelsEvents = true; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + + /** + * Resolve the active activity logging options. + */ + protected function resolvedActivityLogOptions(): LogOptions + { + return $this->activityLogOptions ?? $this->getActivityLogOptions(); + } + + /** + * Boot the activity logging concern. + */ + protected static function bootLogsActivity(): void + { + static::eventsToBeRecorded()->each(function (string $eventName): void { + static::$eventName(function (Model $model) use ($eventName): void { + /** @var Model&self $model */ + $model->activityLogOptions = $model->getActivityLogOptions(); + + try { + if (! $model->shouldLogEvent($eventName)) { + return; + } + + $description = $model->getDescriptionForEvent($eventName); + + if ($description === '') { + return; + } + + $changes = $model->buildChanges($eventName); + + if ($model->shouldSkipEmptyLog($changes)) { + return; + } + + Container::getInstance() + ->make(ActivityLogger::class) + ->useLog($model->getLogNameToUse()) + ->event($eventName) + ->performedOn($model) + ->withChanges($changes) + ->log($description); + } finally { + $model->activityLogOptions = null; + } + }); + }); + } + + /** + * Disable activity logging for this model instance. + */ + public function disableLogging(): self + { + $this->enableLoggingModelsEvents = false; + + return $this; + } + + /** + * Enable activity logging for this model instance. + */ + public function enableLogging(): self + { + $this->enableLoggingModelsEvents = true; + + return $this; + } + + /** + * Get activities for which this model is the subject. + * + * @return MorphMany + */ + public function activitiesAsSubject(): MorphMany + { + $activityModel = Container::getInstance() + ->make(ActivityLogConfiguration::class) + ->activityModel(); + + return $this->morphMany($activityModel, 'subject'); + } + + /** + * Get the activity description for an event. + */ + public function getDescriptionForEvent(string $eventName): string + { + $description = $this->resolvedActivityLogOptions()->descriptionForEvent; + + return $description === null ? $eventName : $description($eventName); + } + + /** + * Get the log name for this model. + */ + public function getLogNameToUse(): ?string + { + return $this->resolvedActivityLogOptions()->logName + ?? Container::getInstance() + ->make(ActivityLogConfiguration::class) + ->defaultLogName(); + } + + /** + * Get the model events that should be recorded. + * + * @return Collection + */ + protected static function eventsToBeRecorded(): Collection + { + $reject = collect(static::$doNotRecordEvents ?? []); + + if (isset(static::$recordEvents)) { + return collect(static::$recordEvents) + ->reject(fn (string $eventName): bool => $reject->contains($eventName)); + } + + $events = collect([ + ActivityEvent::Created->value, + ActivityEvent::Updated->value, + ActivityEvent::Deleted->value, + ]); + + if (collect(class_uses_recursive(static::class))->contains(SoftDeletes::class)) { + $events->push(ActivityEvent::Restored->value); + } + + return $events->reject(fn (string $eventName): bool => $reject->contains($eventName)); + } + + /** + * Determine whether the given model event should be logged. + */ + protected function shouldLogEvent(string $eventName): bool + { + if (! $this->enableLoggingModelsEvents) { + return false; + } + + if (Container::getInstance()->make(ActivityLogStatus::class)->disabled()) { + return false; + } + + if (! in_array( + $eventName, + [ActivityEvent::Created->value, ActivityEvent::Updated->value], + true, + )) { + return true; + } + + if ($this->isRestoring()) { + return false; + } + + return $this->hasChangedAttributesBeyondIgnored(); + } + + /** + * Determine whether the model is being restored. + */ + protected function isRestoring(): bool + { + return method_exists($this, 'isBeingRestored') && $this->isBeingRestored(); + } + + /** + * Determine whether meaningful attributes changed. + */ + protected function hasChangedAttributesBeyondIgnored(): bool + { + // Created fires before Eloquent has changes; updated fires after they are synced. + $changes = $this->getChanges() ?: $this->attributes; + $meaningfulChanges = array_diff_key( + $changes, + array_flip($this->resolvedActivityLogOptions()->dontLogIfAttributesChangedOnly), + ); + + return $meaningfulChanges !== []; + } + + /** + * Get the attributes that should be logged. + * + * @return list + */ + public function attributesToBeLogged(): array + { + $restoreOptions = $this->activityLogOptions === null; + + if ($restoreOptions) { + $this->activityLogOptions = $this->getActivityLogOptions(); + } + + try { + return collect() + ->merge($this->fillableAttributes()) + ->merge($this->unguardedAttributes()) + ->merge($this->explicitAttributes()) + ->diff($this->excludedAttributes()) + ->unique() + ->values() + ->all(); + } finally { + if ($restoreOptions) { + $this->activityLogOptions = null; + } + } + } + + /** + * Get fillable attributes selected for logging. + * + * @return list + */ + protected function fillableAttributes(): array + { + if (! $this->resolvedActivityLogOptions()->logFillable) { + return []; + } + + return $this->getFillable(); + } + + /** + * Get unguarded attributes selected for logging. + * + * @return list + */ + protected function unguardedAttributes(): array + { + if (! $this->resolvedActivityLogOptions()->logUnguarded) { + return []; + } + + if (static::isUnguarded()) { + return array_keys($this->attributes); + } + + if (in_array('*', $this->getGuarded(), true)) { + return []; + } + + return array_values(array_diff(array_keys($this->attributes), $this->getGuarded())); + } + + /** + * Get explicitly selected attributes. + * + * @return list + */ + protected function explicitAttributes(): array + { + $attributes = $this->resolvedActivityLogOptions()->logAttributes; + + if ($attributes === []) { + return []; + } + + $explicit = array_values(array_diff($attributes, ['*'])); + + if (in_array('*', $attributes, true)) { + $explicit = array_merge($explicit, array_keys($this->attributes)); + } + + return $explicit; + } + + /** + * Get attributes excluded from logging. + * + * @return list + */ + protected function excludedAttributes(): array + { + return array_merge( + $this->resolvedActivityLogOptions()->logExceptAttributes, + Container::getInstance() + ->make(ActivityLogConfiguration::class) + ->defaultExceptAttributes(), + ); + } + + /** + * Build the changes for an activity event. + * + * @return array> + */ + protected function buildChanges(string $processingEvent): array + { + $attributes = $this->attributesToBeLogged(); + $shouldRefresh = $this->shouldRefreshBeforeLogging($processingEvent); + + $options = $this->resolvedActivityLogOptions(); + $oldRawAttributes = $this->isUpdatedEvent($processingEvent) + ? $this->getRawOriginal() + : null; + + $this->activityLogAttributes = $attributes; + + try { + $current = $this->resolveModelForLogging($processingEvent); + } finally { + $this->activityLogAttributes = null; + } + + if ($current !== $this) { + // A snapshot override may return an application-owned model. + $current = clone $current; + $current->activityLogOptions = $options; + $attributes = $current->attributesToBeLogged(); + } + + if ($processingEvent === ActivityEvent::Restored->value && ! $shouldRefresh && $options->attributeRawValues !== []) { + // finishSave may already have merged cached casts over the bytes written during restore. + $current = clone $current; + $current->attributes = array_replace( + $current->attributes, + array_intersect_key($this->getChanges(), array_flip($options->attributeRawValues)), + ); + } + + $current->activityLogAttributes = $attributes; + try { + $properties = ['attributes' => static::extractChanges($current)]; + } finally { + $current->activityLogAttributes = null; + } + + if ($oldRawAttributes !== null) { + // The clone inherits the live model's current cast caches. Syncing + // would merge those values over this exact pre-update raw snapshot. + $old = $this->withoutRelations()->setRawAttributes($oldRawAttributes); + $old->activityLogOptions = $options; + $old->activityLogAttributes = $attributes; + $oldAttributes = static::extractChanges($old); + $nullProperties = array_fill_keys(array_keys($properties['attributes']), null); + $properties['old'] = array_merge($nullProperties, $oldAttributes); + } + + if ($attributes === [] && $properties['attributes'] === [] && ($properties['old'] ?? []) === []) { + return []; + } + + if ($options->logOnlyDirty && isset($properties['old'])) { + $filtered = ChangeDetector::filterDirty($properties['attributes'], $properties['old']); + $properties['attributes'] = $filtered['attributes']; + $properties['old'] = $filtered['old']; + } + + if ($this->isDeletedEvent($processingEvent)) { + $properties['old'] = $properties['attributes']; + unset($properties['attributes']); + } + + return $properties; + } + + /** + * Resolve the current model snapshot for logging. + */ + protected function resolveModelForLogging(string $processingEvent): static + { + if ($processingEvent === ActivityEvent::Retrieved->value) { + return $this; + } + + if ($this->shouldRefreshBeforeLogging($processingEvent)) { + // The write transaction keeps another writer from changing the row + // between this model's persistence statement and its refresh. + if ($this->getConnection()->transactionLevel() === 0) { + throw CouldNotLogActivity::refreshBeforeLoggingRequiresTransaction($this); + } + + $subject = $this; + + /** @var null|static $current */ + $current = static::withoutEvents(static fn (): ?Model => $subject->fresh()); + + return $current ?? throw CouldNotLogActivity::subjectCouldNotBeRefreshed($this); + } + + $attributes = $this->activityLogAttributes ?? $this->attributesToBeLogged(); + + foreach ($attributes as $attribute) { + if (Str::contains($attribute, '.')) { + // Direct values already represent this event exactly, but a live + // model may hold relations loaded before the persistence event. + return $this->withoutRelations(); + } + } + + return $this; + } + + /** + * Determine whether the event should refresh its current snapshot. + */ + protected function shouldRefreshBeforeLogging(string $processingEvent): bool + { + return $this->resolvedActivityLogOptions()->refreshBeforeLogging + && in_array( + $processingEvent, + [ + ActivityEvent::Created->value, + ActivityEvent::Updated->value, + ActivityEvent::Restored->value, + ], + true, + ); + } + + /** + * Determine whether an empty change set should be skipped. + * + * @param array> $changes + */ + protected function shouldSkipEmptyLog(array $changes): bool + { + if ($this->resolvedActivityLogOptions()->logEmptyChanges) { + return false; + } + + if (($changes['attributes'] ?? []) !== []) { + return false; + } + + return ($changes['old'] ?? []) === []; + } + + /** + * Determine whether an event is an update. + */ + protected function isUpdatedEvent(string $processingEvent): bool + { + return $processingEvent === ActivityEvent::Updated->value; + } + + /** + * Determine whether an event is a deletion. + */ + protected function isDeletedEvent(string $processingEvent): bool + { + return $processingEvent === ActivityEvent::Deleted->value; + } + + /** + * Extract selected changes from a model. + * + * @return array + */ + public static function extractChanges(Model $model): array + { + /** @var Model&self $model */ + $options = $model->resolvedActivityLogOptions(); + + return static::extractChangesForAttributes( + $model, + $model->activityLogAttributes ?? $model->attributesToBeLogged(), + $options, + ); + } + + /** + * Extract selected model attributes. + * + * @param list $attributes + * @return array + */ + protected static function extractChangesForAttributes( + Model $model, + array $attributes, + LogOptions $options, + ): array { + if ($attributes === []) { + return []; + } + + $rawValues = []; + + foreach ($options->attributeRawValues as $attribute) { + if (array_key_exists($attribute, $model->attributes)) { + $rawValues[$attribute] = $model->attributes[$attribute]; + } + } + + // Normalize cached mutable casts without changing the event model. Raw + // selections retain persisted bytes even when their setter is nondeterministic. + $model = clone $model; + $normalizedAttributes = array_replace($model->getAttributes(), $rawValues); + // A projected-out column has no known value in this snapshot. Give it a + // null value on the clone so strict mode still runs accessors and casts normally. + if ($model::preventsAccessingMissingAttributes()) { + foreach ($attributes as $attribute) { + if (! str_contains($attribute, '.')) { + $key = Str::before($attribute, '->'); + if (! array_key_exists($key, $normalizedAttributes) + && ! $model->hasGetMutator($key) + && ! $model->hasAttributeGetMutator($key) + && ! $model->relationLoaded($key) + && ! $model->isRelation($key)) { + $normalizedAttributes[$key] = null; + } + } + } + } + $model->setRawAttributes($normalizedAttributes); + + $changes = []; + $selected = null; + $jsonRoots = []; + + foreach ($attributes as $attribute) { + if (Str::contains($attribute, '.')) { + $related = ChangeDetector::resolveRelatedModel($model, $attribute); + $changes[$attribute] = $related === null + ? null + : static::readAttributeForLogging($related, Str::afterLast($attribute, '.')); + + continue; + } + + if (Str::contains($attribute, '->')) { + $selected ??= array_flip($attributes); + $ancestor = $attribute; + + while (($separator = strrpos($ancestor, '->')) !== false) { + $ancestor = substr($ancestor, 0, $separator); + + if (isset($selected[$ancestor])) { + continue 2; + } + } + + [$root, $path] = explode('->', $attribute, 2); + $jsonRoots[$root] ??= ChangeDetector::jsonPathRoot(static::readAttributeForLogging($model, $root)); + + data_set( + $changes, + str_replace('->', '.', $attribute), + data_get($jsonRoots[$root], str_replace('->', '.', $path)), + ); + + continue; + } + + $changes += static::resolveAttributeValue($model, $attribute, $options); + } + + return $changes; + } + + /** + * Resolve one model attribute value. + * + * @return array + */ + protected static function resolveAttributeValue( + Model $model, + string $attribute, + LogOptions $options, + ): array { + if (in_array($attribute, $options->attributeRawValues, true)) { + return [$attribute => $model->getAttributeFromArray($attribute)]; + } + + return [$attribute => static::readAttributeForLogging($model, $attribute)]; + } + + /** + * Read a selected model attribute in the form recorded in an activity. + */ + protected static function readAttributeForLogging(Model $model, string $attribute): mixed + { + $value = $model->getAttribute($attribute); + + return $value === null ? null : static::formatAttributeValue($model, $attribute, $value); + } + + /** + * Format one model attribute value for storage. + */ + protected static function formatAttributeValue( + Model $model, + string $attribute, + mixed $value, + ): mixed { + if ($model->hasCast($attribute)) { + $cast = $model->getCasts()[$attribute]; + + if ($value instanceof UnitEnum && $model->isEnumCastable($attribute)) { + return $model->getStorableEnumValue($cast, $value); + } + + if ($value instanceof DateTimeInterface + && ($model->isCustomDateTimeCast($cast) || $model->isImmutableCustomDateTimeCast($cast))) { + return $model->asDateTime($value)->format(explode(':', $cast, 2)[1]); + } + + if ($model->isClassSerializable($attribute) && ! $model->hasAnyGetMutator($attribute)) { + return $model->serializeClassCastableAttribute($attribute, $value); + } + } + + if ($model->isDateAttribute($attribute) + && ($value instanceof DateTimeInterface || ! $model->hasAnyGetMutator($attribute))) { + return $model->serializeDate($model->asDateTime($value)); + } + + return $value; + } +} diff --git a/src/activity-log/src/Support/ActivityBuffer.php b/src/activity-log/src/Support/ActivityBuffer.php new file mode 100644 index 000000000..44e047fc6 --- /dev/null +++ b/src/activity-log/src/Support/ActivityBuffer.php @@ -0,0 +1,394 @@ +> */ + protected array $pending = []; + + /** @var array> */ + protected array $staged = []; + + protected (ActivityContract&Model)|null $activity = null; + + protected ?Connection $connection = null; + + protected Builder $insertQuery; + + protected bool $pendingNeedsSorting = false; + + protected ?string $connectionName = null; + + protected ?string $table = null; + + protected ?int $batchSize = null; + + protected int $nextSequence = 0; + + protected bool $lifecycleRegistered = false; + + public function __construct( + protected ActivityLogConfiguration $configuration, + ) { + } + + /** + * Add an activity to the buffer. + */ + public function add(ActivityContract&Model $activity): void + { + $this->ensurePersistenceTargetWasNotChanged($activity); + // Resolve the insert on the original target even if the default connection changes before flush. + $this->insertQuery ??= $this->activityModel()->newQuery()->toBase(); + + $record = $this->prepareForInsert($activity); + $sequence = $this->nextSequence++; + $connection = $this->activityConnection(); + + if ($connection->hasApplicableTransaction()) { + $connection->afterRollBack(function () use ($sequence): void { + unset($this->staged[$sequence]); + }); + + $this->staged[$sequence] = $record; + $this->registerLifecycle(); + + $connection->afterCommit(function () use ($sequence): void { + $record = $this->staged[$sequence]; + unset($this->staged[$sequence]); + + $this->enqueue($sequence, $record); + }); + + return; + } + + $this->enqueue($sequence, $record); + } + + /** + * Flush every eligible buffered activity. + */ + public function flush(): void + { + if (! $this->hasPending()) { + return; + } + + $this->ensureActivityConnectionIsNotTransacting(); + $this->drainPending(); + } + + /** + * Determine whether the buffer has any work. + */ + public function hasPending(): bool + { + return $this->pending !== [] || $this->staged !== []; + } + + /** + * Determine whether buffered work can be flushed now. + */ + public function canFlush(): bool + { + if ($this->pending === [] || $this->activityConnection()->hasApplicableTransaction()) { + return false; + } + + $this->orderPending(); + $firstStaged = array_key_first($this->staged); + + return $firstStaged === null || array_key_first($this->pending) < $firstStaged; + } + + /** + * Get the number of buffered activities. + */ + public function count(): int + { + return count($this->pending) + count($this->staged); + } + + /** + * Get the buffer owned by the current coroutine. + */ + public static function current(): ?self + { + $current = CoroutineContext::get(self::CONTEXT_KEY); + + return $current instanceof self ? $current : null; + } + + /** + * Finalize the current scope's activity buffer. + */ + public static function finalizeCurrent(): void + { + self::current()?->flush(); + } + + /** + * Enqueue a transaction-resolved record. + * + * @param array $record + */ + protected function enqueue(int $sequence, array $record): void + { + if ($this->pending !== [] && $sequence < array_key_last($this->pending)) { + $this->pendingNeedsSorting = true; + } + $this->pending[$sequence] = $record; + $this->registerLifecycle(); + + $connection = $this->activityConnection(); + if ($connection->transactionLevel() > 0) { + try { + $this->drainPending(); + } finally { + // An earlier staged row or failed batch can leave this row in memory past rollback. + $manager = $connection->getTransactionManager(); + if (isset($this->pending[$sequence]) && $manager instanceof TestingTransactionsManager) { + $wrapper = $manager->wrappingTransactionFor($this->activityConnectionName()); + $wrapper?->addCallbackForRollback(function () use ($sequence): void { + unset($this->pending[$sequence]); + }); + } + } + } elseif ($this->staged === [] && count($this->pending) >= $this->batchSize()) { + $this->flushBatch(); + } + } + + /** + * Drain every transaction-resolved activity. + */ + protected function drainPending(): void + { + while ($this->canFlush()) { + $this->flushBatch(); + } + } + + /** + * Restore call order after transaction callbacks promoted rows out of sequence. + */ + protected function orderPending(): void + { + if ($this->pendingNeedsSorting) { + ksort($this->pending); + $this->pendingNeedsSorting = false; + } + } + + /** + * Flush one bounded batch preceding the earliest unresolved activity. + */ + protected function flushBatch(): void + { + $this->orderPending(); + $firstStaged = array_key_first($this->staged); + $records = []; + + // Claim before writing: transaction callbacks and events may re-enter + // the buffer, and must never observe or insert this in-flight batch. + foreach (array_slice($this->pending, 0, $this->batchSize(), preserve_keys: true) as $sequence => $record) { + if ($firstStaged !== null && $sequence >= $firstStaged) { + break; + } + + $records[] = $record; + unset($this->pending[$sequence]); + } + + $this->activityConnection()->transaction(function () use ($records): void { + foreach ($this->groupConsecutiveByColumns($records) as $group) { + if (! (clone $this->insertQuery)->insert($group)) { + throw CouldNotLogActivity::activityCouldNotBePersisted(); + } + } + }); + } + + /** + * Group adjacent records that have the same columns. + * + * @param list> $records + * @return Generator>> + */ + protected function groupConsecutiveByColumns(array $records): Generator + { + /** @var null|list $columns */ + $columns = null; + $group = []; + + foreach ($records as $record) { + $recordColumns = array_keys($record); + + if ($columns !== null && $recordColumns !== $columns) { + yield $group; + $group = []; + } + + $columns = $recordColumns; + $group[] = $record; + } + + if ($group !== []) { + yield $group; + } + } + + /** + * Prepare an activity for bulk insertion. + * + * @return array + */ + protected function prepareForInsert(ActivityContract&Model $activity): array + { + // Identity must remain visible on the returned model, while buffer-owned + // timestamps below belong only to the row prepared for bulk insertion. + if ($activity->usesUniqueIds()) { + $activity->setUniqueIds(); + } + + $activity = clone $activity; + if ($activity->usesTimestamps()) { + $activity->updateTimestamps(); + } + + $attributes = []; + + foreach ($activity->getDatabaseAttributesForInsert() as $key => $value) { + if ($value instanceof Collection) { + $attributes[$key] = $value->toJson(); + } elseif ($value instanceof DateTimeInterface) { + $attributes[$key] = $activity->fromDateTime($value); + } else { + $attributes[$key] = $value; + } + } + + ksort($attributes); + + return $attributes; + } + + /** + * Register this buffer with its lifecycle boundaries. + */ + protected function registerLifecycle(): void + { + if ($this->lifecycleRegistered) { + return; + } + + CoroutineContext::set(self::CONTEXT_KEY, $this); + + // The activity connection must already be borrowed. Swoole runs defers + // in reverse order, so finalization must precede pool release. + if (Coroutine::inCoroutine()) { + Coroutine::defer(static function (): void { + self::finalizeCurrent(); + }); + } + + $this->lifecycleRegistered = true; + } + + /** + * Get the configured activity model. + */ + protected function activityModel(): ActivityContract&Model + { + return $this->activity ??= $this->configuration->activityModelInstance(); + } + + /** + * Get the activity database connection. + */ + protected function activityConnection(): Connection + { + return $this->connection ??= $this->activityModel()->getConnection(); + } + + /** + * Get the activity database connection name. + */ + protected function activityConnectionName(): string + { + if ($this->connectionName !== null) { + return $this->connectionName; + } + + return $this->connectionName = $this->activityConnection()->getNameWithReadWriteType() + ?? throw new RuntimeException('The activity log database connection has not been named.'); + } + + /** + * Get the activity table name. + */ + protected function activityTable(): string + { + return $this->table ??= $this->activityModel()->getTable(); + } + + /** + * Get the configured insert batch size. + */ + protected function batchSize(): int + { + return $this->batchSize ??= $this->configuration->bufferBatchSize(); + } + + /** + * Ensure the activity still targets the configured connection and table. + */ + protected function ensurePersistenceTargetWasNotChanged(ActivityContract&Model $activity): void + { + $expectedConnection = $this->activityConnectionName(); + $expectedTable = $this->activityTable(); + $actualConnection = $activity->getConnection()->getNameWithReadWriteType(); + $actualTable = $activity->getTable(); + + if ($actualTable !== $expectedTable || $actualConnection !== $expectedConnection) { + throw InvalidConfiguration::activityBufferTargetChanged( + $activity::class, + $expectedConnection, + $expectedTable, + $actualConnection, + $actualTable, + ); + } + } + + /** + * Ensure the activity transaction has completed before flushing. + */ + protected function ensureActivityConnectionIsNotTransacting(): void + { + if ($this->activityConnection()->hasApplicableTransaction()) { + throw CouldNotLogActivity::activityBufferCannotBeFlushedDuringTransaction(); + } + } +} diff --git a/src/activity-log/src/Support/ActivityLogConfiguration.php b/src/activity-log/src/Support/ActivityLogConfiguration.php new file mode 100644 index 000000000..cef4fadbc --- /dev/null +++ b/src/activity-log/src/Support/ActivityLogConfiguration.php @@ -0,0 +1,242 @@ + */ + protected ?string $activityModelClass = null; + + /** @var null|class-string */ + protected ?string $logActivityActionClass = null; + + /** @var null|class-string */ + protected ?string $cleanActivityLogActionClass = null; + + public function __construct( + protected Repository $config, + protected Container $container, + ) { + } + + /** + * Get the configured activity model class. + * + * @return class-string + */ + public function activityModel(): string + { + if ($this->activityModelClass !== null) { + return $this->activityModelClass; + } + + $className = $this->config->string('activity-log.activity_model'); + + if (! is_a($className, ActivityContract::class, true) + || ! is_a($className, Model::class, true)) { + throw InvalidConfiguration::modelIsNotValid($className); + } + + $reflection = new ReflectionClass($className); + + if (! $reflection->isInstantiable() + || ($reflection->getConstructor()?->getNumberOfRequiredParameters() ?? 0) > 0) { + throw InvalidConfiguration::modelIsNotValid($className); + } + + return $this->activityModelClass = $className; + } + + /** + * Create an instance of the configured activity model. + */ + public function activityModelInstance(): ActivityContract&Model + { + $className = $this->activityModel(); + + return new $className; + } + + /** + * Resolve a fresh log activity action. + */ + public function logActivityAction(): LogActivityAction + { + $className = $this->logActivityActionClass ??= $this->validatedActionClass( + 'activity-log.actions.log_activity', + LogActivityAction::class, + ); + + return $this->resolveAction($className, LogActivityAction::class); + } + + /** + * Resolve a fresh clean activity log action. + */ + public function cleanActivityLogAction(): CleanActivityLogAction + { + $className = $this->cleanActivityLogActionClass ??= $this->validatedActionClass( + 'activity-log.actions.clean_log', + CleanActivityLogAction::class, + ); + + return $this->resolveAction($className, CleanActivityLogAction::class); + } + + /** + * Determine whether activity logging is enabled. + */ + public function enabled(): bool + { + return $this->config->boolean('activity-log.enabled'); + } + + /** + * Get the configured activity retention period. + */ + public function cleanAfterDays(): int + { + return $this->positiveInteger('activity-log.clean_after_days'); + } + + /** + * Get the configured cleanup batch size. + */ + public function cleanBatchSize(): int + { + return $this->positiveInteger('activity-log.clean_batch_size'); + } + + /** + * Get the default activity log name. + */ + public function defaultLogName(): ?string + { + return $this->config->nullableString('activity-log.default_log_name'); + } + + /** + * Get the default authentication driver. + */ + public function defaultAuthDriver(): ?string + { + return $this->config->nullableString('activity-log.default_auth_driver'); + } + + /** + * Determine whether soft-deleted subjects are included. + */ + public function includeSoftDeletedSubjects(): bool + { + return $this->config->boolean('activity-log.include_soft_deleted_subjects'); + } + + /** + * Get attributes excluded from every activity log. + * + * @return list + */ + public function defaultExceptAttributes(): array + { + $attributes = $this->config->array('activity-log.default_except_attributes'); + + if (! array_is_list($attributes) + || ! array_all($attributes, static fn (mixed $attribute): bool => is_string($attribute))) { + throw new InvalidArgumentException( + 'Configuration value for key [activity-log.default_except_attributes] must be a list of strings.', + ); + } + + return $attributes; + } + + /** + * Determine whether activity buffering is enabled. + */ + public function bufferEnabled(): bool + { + return $this->config->boolean('activity-log.buffer.enabled'); + } + + /** + * Get the configured activity buffer batch size. + */ + public function bufferBatchSize(): int + { + return $this->positiveInteger('activity-log.buffer.batch_size'); + } + + /** + * Get a positive integer configuration value. + */ + protected function positiveInteger(string $key): int + { + $value = $this->config->integer($key); + + if ($value < 1) { + throw new InvalidArgumentException( + "Configuration value for key [{$key}] must be at least 1.", + ); + } + + return $value; + } + + /** + * Validate a configured action class. + * + * @template TAction of object + * + * @param class-string $expectedBaseClass + * @return class-string + */ + protected function validatedActionClass(string $configKey, string $expectedBaseClass): string + { + $className = $this->config->string($configKey); + + if (! is_a($className, $expectedBaseClass, true) + || ! (new ReflectionClass($className))->isInstantiable()) { + throw InvalidConfiguration::actionIsNotValid($className, $expectedBaseClass); + } + + return $className; + } + + /** + * Resolve a configured action. + * + * @template TAction of object + * + * @param class-string $className + * @param class-string $expectedBaseClass + * @return TAction + */ + protected function resolveAction(string $className, string $expectedBaseClass): object + { + $resolved = $this->container->bound($className) + ? $this->container->make($className) + : $this->container->build($className); + + if (! $resolved instanceof $expectedBaseClass) { + throw InvalidConfiguration::actionBindingIsNotValid( + $className, + $expectedBaseClass, + $resolved, + ); + } + + return $resolved; + } +} diff --git a/src/activity-log/src/Support/ActivityLogStatus.php b/src/activity-log/src/Support/ActivityLogStatus.php new file mode 100644 index 000000000..8900d9401 --- /dev/null +++ b/src/activity-log/src/Support/ActivityLogStatus.php @@ -0,0 +1,39 @@ +enabled = $configuration->enabled(); + } + + /** + * Enable activity logging. + */ + public function enable(): bool + { + return $this->enabled = true; + } + + /** + * Disable activity logging. + */ + public function disable(): bool + { + return $this->enabled = false; + } + + /** + * Determine whether activity logging is disabled. + */ + public function disabled(): bool + { + return ! $this->enabled; + } +} diff --git a/src/activity-log/src/Support/ActivityLogger.php b/src/activity-log/src/Support/ActivityLogger.php new file mode 100644 index 000000000..bc9d14954 --- /dev/null +++ b/src/activity-log/src/Support/ActivityLogger.php @@ -0,0 +1,321 @@ +logName = $this->defaultLogName = $configuration->defaultLogName(); + } + + // REMOVED: setLogStatus() repaired the upstream pending proxy's constructor + // wiring; this fresh builder receives its scoped status directly. + + /** + * Set the activity subject. + */ + public function performedOn(Model $model): static + { + $this->getActivity()->subject()->associate($model); + + return $this; + } + + /** + * Set the activity subject. + */ + public function on(Model $model): static + { + return $this->performedOn($model); + } + + /** + * Set the activity causer. + */ + public function causedBy(Model|int|string|null $modelOrId): static + { + if ($modelOrId === null) { + return $this; + } + + $model = $this->causerResolver->resolve($modelOrId); + + $this->getActivity()->causer()->associate($model); + $this->causerResolved = true; + + return $this; + } + + /** + * Set the activity causer. + */ + public function by(Model|int|string|null $modelOrId): static + { + return $this->causedBy($modelOrId); + } + + /** + * Remove the activity causer. + */ + public function causedByAnonymous(): static + { + $this->getActivity()->causer()->dissociate(); + $this->causerResolved = true; + + return $this; + } + + /** + * Remove the activity causer. + */ + public function byAnonymous(): static + { + return $this->causedByAnonymous(); + } + + /** + * Set the activity event. + */ + public function event(string|ActivityEvent $event): static + { + return $this->setEvent($event); + } + + /** + * Set the activity event. + */ + public function setEvent(string|ActivityEvent $event): static + { + $this->getActivity()->setAttribute( + 'event', + $event instanceof ActivityEvent ? $event->value : $event, + ); + + return $this; + } + + /** + * Set the activity changes. + * + * @param array|Collection $changes + */ + public function withChanges(array|Collection $changes): static + { + $this->getActivity()->setAttribute('attribute_changes', collect($changes)); + + return $this; + } + + /** + * Set the activity properties. + * + * @param array|Collection $properties + */ + public function withProperties(array|Collection $properties): static + { + $this->getActivity()->setAttribute('properties', collect($properties)); + + return $this; + } + + /** + * Set one activity property. + */ + public function withProperty(string $key, mixed $value): static + { + $activity = $this->getActivity(); + $properties = $activity->getAttribute('properties'); + + $properties[$key] = $value; + $activity->setAttribute('properties', $properties); + + return $this; + } + + /** + * Set the activity creation date. + */ + public function createdAt(DateTimeInterface $dateTime): static + { + $activity = $this->getActivity(); + $createdAtColumn = $activity->getCreatedAtColumn() + ?? throw InvalidConfiguration::activityModelDoesNotHaveCreatedAtColumn( + $activity::class, + ); + + $activity->setAttribute($createdAtColumn, Date::instance($dateTime)); + + return $this; + } + + /** + * Set the activity log name. + */ + public function useLog(BackedEnum|string|null $logName): static + { + $this->logName = $logName instanceof BackedEnum ? (string) $logName->value : $logName; + $this->activity?->setAttribute('log_name', $this->logName); + + return $this; + } + + /** + * Set the activity log name. + */ + public function inLog(BackedEnum|string|null $logName): static + { + return $this->useLog($logName); + } + + /** + * Modify the pending activity. + * + * @param callable(ActivityContract&Model, null|string): void $callback + */ + public function tap(callable $callback, ?string $eventName = null): static + { + $this->useDefaultCauserIfNoneWasGiven(); + call_user_func($callback, $this->getActivity(), $eventName); + + return $this; + } + + /** + * Enable activity logging for the current scope. + */ + public function enableLogging(): static + { + $this->logStatus->enable(); + + return $this; + } + + /** + * Disable activity logging for the current scope. + */ + public function disableLogging(): static + { + $this->logStatus->disable(); + + return $this; + } + + /** + * Persist the pending activity. + */ + public function log(string $description): (ActivityContract&Model)|null + { + try { + if ($this->logStatus->disabled()) { + return null; + } + + $this->useDefaultCauserIfNoneWasGiven(); + + return $this->configuration->logActivityAction()->execute( + $this->getActivity(), + $description, + ); + } finally { + $this->reset(); + } + } + + /** + * Run a callback with activity logging disabled. + * + * @template TResult + * + * @param Closure(): TResult $callback + * @return TResult + */ + public function withoutLogging(Closure $callback): mixed + { + $wasDisabled = $this->logStatus->disabled(); + $this->logStatus->disable(); + + try { + return $callback(); + } finally { + if ($wasDisabled) { + $this->logStatus->disable(); + } else { + $this->logStatus->enable(); + } + } + } + + /** + * Get the pending activity. + */ + protected function getActivity(): ActivityContract&Model + { + if ($this->activity === null) { + $activity = $this->configuration->activityModelInstance(); + $activity->setAttribute('log_name', $this->logName); + $activity->setAttribute('attribute_changes', collect()); + $activity->setAttribute('properties', collect()); + + $this->activity = $activity; + } + + return $this->activity; + } + + /** + * Associate the default causer when no explicit decision was made. + */ + protected function useDefaultCauserIfNoneWasGiven(): void + { + if ($this->causerResolved || $this->getActivity()->getAttribute('causer_id') !== null) { + return; + } + + $causer = $this->causerResolver->resolve(); + + if ($causer !== null) { + $this->getActivity()->causer()->associate($causer); + } + + $this->causerResolved = true; + } + + /** + * Reset the one-shot builder. + */ + protected function reset(): void + { + $this->activity = null; + $this->causerResolved = false; + $this->logName = $this->defaultLogName; + } +} diff --git a/src/activity-log/src/Support/CauserResolver.php b/src/activity-log/src/Support/CauserResolver.php new file mode 100644 index 000000000..623d3401b --- /dev/null +++ b/src/activity-log/src/Support/CauserResolver.php @@ -0,0 +1,193 @@ +authDriver = $configuration->defaultAuthDriver(); + } + + /** + * Resolve an activity causer. + */ + public function resolve(Model|int|string|null $subject = null): ?Model + { + if ($this->causerOverride !== null) { + return $this->causerOverride; + } + + if ($subject instanceof Model && $this->resolverOverride === null) { + return $this->getCauser($subject); + } + + // Hydrating an auth user can itself log a retrieved event. A copied + // coroutine context belongs to a different lookup, so compare owners. + $owner = Coroutine::id(); + if (CoroutineContext::get(self::RESOLVING_CONTEXT_KEY) === $owner) { + return $subject === null ? null : $this->resolveCauser($subject); + } + + CoroutineContext::set(self::RESOLVING_CONTEXT_KEY, $owner); + try { + return $this->resolveCauser($subject); + } finally { + CoroutineContext::forget(self::RESOLVING_CONTEXT_KEY); + } + } + + /** + * Resolve the causer through the configured resolver or authentication guard. + */ + protected function resolveCauser(Model|int|string|null $subject): ?Model + { + if ($this->resolverOverride !== null) { + $causer = ($this->resolverOverride)($subject); + + if (! $this->isResolvable($causer)) { + throw CouldNotLogActivity::invalidCauserResolverResult($causer); + } + + if ($causer instanceof Model || $causer === null) { + return $causer; + } + + return $this->resolveUsingId($causer); + } + + return $this->getCauser($subject); + } + + /** + * Resolve a causer by its authentication identifier. + */ + protected function resolveUsingId(int|string $subject): Model + { + $guard = $this->authManager->guard($this->authDriver); + + if (! method_exists($guard, 'getProvider')) { + throw CouldNotLogActivity::couldNotDetermineUser($subject); + } + + $provider = $guard->getProvider(); + $model = $provider instanceof UserProvider + ? $provider->retrieveById($subject) + : null; + + if (! $model instanceof Model) { + throw CouldNotLogActivity::couldNotDetermineUser($subject); + } + + return $model; + } + + /** + * Resolve the given causer input. + */ + protected function getCauser(Model|int|string|null $subject = null): ?Model + { + if ($subject instanceof Model) { + return $subject; + } + + if ($subject === null) { + return $this->getDefaultCauser(); + } + + return $this->resolveUsingId($subject); + } + + /** + * Override causer resolution for the current scope. + * + * @param Closure(null|int|Model|string):(null|int|Model|string) $callback + */ + public function resolveUsing(Closure $callback): static + { + $this->resolverOverride = $callback; + + return $this; + } + + /** + * Override the default causer for the current scope. + */ + public function setCauser(Model|int|string|null $causer): static + { + $this->causerOverride = $causer === null + ? null + : $this->getCauser($causer); + + return $this; + } + + /** + * Run a callback with a specific default causer. + * + * @template TResult + * + * @param Closure(): TResult $callback + * @return TResult + */ + public function withCauser(Model|int|string|null $causer, Closure $callback): mixed + { + $previousCauser = $this->causerOverride; + $this->causerOverride = $causer === null + ? null + : $this->getCauser($causer); + + try { + return $callback(); + } finally { + $this->causerOverride = $previousCauser; + } + } + + /** + * Determine whether a resolver result can identify a causer. + */ + protected function isResolvable(mixed $causer): bool + { + return $causer instanceof Model + || is_int($causer) + || is_string($causer) + || $causer === null; + } + + /** + * Get the current authenticated causer. + */ + protected function getDefaultCauser(): ?Model + { + $guard = $this->authDriver ?? $this->authManager->getDefaultDriver(); + $causer = $this->authManager->guard($guard)->user(); + + if ($causer !== null && ! $causer instanceof Model) { + throw CouldNotLogActivity::invalidAuthenticatedCauser($guard, $causer); + } + + return $causer; + } +} diff --git a/src/activity-log/src/Support/ChangeDetector.php b/src/activity-log/src/Support/ChangeDetector.php new file mode 100644 index 000000000..d7ad15965 --- /dev/null +++ b/src/activity-log/src/Support/ChangeDetector.php @@ -0,0 +1,204 @@ + + */ + public static function resolveRelatedAttribute(Model $model, string $attribute): array + { + $related = static::resolveRelatedModel($model, $attribute); + + return [$attribute => $related?->getAttribute(Str::afterLast($attribute, '.'))]; + } + + /** + * Find the model that owns the leaf of a dotted attribute. + * + * @internal + */ + public static function resolveRelatedModel(Model $model, string $attribute): ?Model + { + $segments = explode('.', $attribute); + array_pop($segments); + + $relatedModel = $model; + + foreach ($segments as $segment) { + $relationName = static::resolveRelationName($relatedModel, $segment); + + if (method_exists(Model::class, $relationName) || ! $relatedModel->isRelation($relationName)) { + throw new InvalidArgumentException( + "Activity log attribute [{$attribute}] references undefined relation [" + . $relatedModel::class . "::{$relationName}].", + ); + } + + if (! $relatedModel->relationLoaded($relationName)) { + try { + $relation = Relation::withConstraintsForNestedRelation(fn () => $relatedModel->{$relationName}()); + $missingMorphType = $relation instanceof MorphTo + && $relation->eagerLoadingPlaceholder + && $relation->getParentKey() !== null; + } catch (MissingAttributeException $exception) { + if (! $relatedModel::preventsAccessingMissingAttributes()) { + throw $exception; + } + + // A partial snapshot can lack the key needed to build this relation. + $relatedModel->setRelation($relationName, null); + + return null; + } + + if (! $relation instanceof Relation) { + throw new InvalidArgumentException( + "Activity log attribute [{$attribute}] references [" + . $relatedModel::class . "::{$relationName}], which does not return an Eloquent relation.", + ); + } + + $relatedModel->setRelation($relationName, $missingMorphType ? null : $relation->getResults()); + } + $related = $relatedModel->getRelation($relationName); + + if ($related === null) { + return null; + } + + if (! $related instanceof Model) { + throw new InvalidArgumentException( + "Activity log attribute [{$attribute}] must traverse singular Eloquent relations; [" + . get_debug_type($related) . '] returned by [' + . $relatedModel::class . "::{$relationName}].", + ); + } + + $relatedModel = $related; + } + + return $relatedModel; + } + + /** + * Resolve the actual relationship method name. + */ + public static function resolveRelationName(Model $model, string $relation): string + { + return array_find( + [$relation, Str::snake($relation), Str::camel($relation)], + fn (string $method): bool => method_exists($model, $method) + || $model->relationResolver($model::class, $method) !== null, + ) ?? $relation; + } + + /** + * Resolve an attribute within a JSON value. + */ + public static function resolveJsonAttribute(Model $model, string $attribute): mixed + { + $path = explode('->', $attribute); + $modelAttribute = array_shift($path); + + return data_get( + static::jsonPathRoot($model->getAttribute($modelAttribute)), + implode('.', $path), + ); + } + + /** + * Get the fields exposed by a JSON path's root value. + * + * @internal + * @return array + */ + public static function jsonPathRoot(mixed $value): array + { + if (is_array($value)) { + return $value; + } + + return $value instanceof Collection ? $value->jsonSerialize() : collect($value)->all(); + } + + /** + * Retain only changed attributes and their old values. + * + * @param array $newAttributes + * @param array $oldAttributes + * @return array{attributes: array, old: array} + */ + public static function filterDirty(array $newAttributes, array $oldAttributes): array + { + $changed = array_udiff_assoc( + $newAttributes, + $oldAttributes, + fn (mixed $new, mixed $old): int => static::compareValues($new, $old), + ); + + $old = collect($oldAttributes) + ->only(array_keys($changed)) + ->all(); + + return ['attributes' => $changed, 'old' => $old]; + } + + /** + * Compare two activity attribute values. + */ + protected static function compareValues(mixed $new, mixed $old): int + { + if ($new === $old) { + return 0; + } + + if ($new === null || $old === null) { + return 1; + } + + if ($old instanceof DateInterval) { + return CarbonInterval::make($old)->equalTo($new) ? 0 : 1; + } + + if ($new instanceof DateInterval) { + return CarbonInterval::make($new)->equalTo($old) ? 0 : 1; + } + + if (is_array($new) && is_array($old)) { + if (array_keys($new) !== array_keys($old)) { + return 1; + } + + foreach ($new as $key => $value) { + if (static::compareValues($value, $old[$key]) !== 0) { + return 1; + } + } + + return 0; + } + + if (is_object($new) && is_object($old)) { + return json_encode($new, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION) + === json_encode($old, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION) ? 0 : 1; + } + + return 1; + } +} diff --git a/src/activity-log/src/Support/LogOptions.php b/src/activity-log/src/Support/LogOptions.php new file mode 100644 index 000000000..1ba4f5b71 --- /dev/null +++ b/src/activity-log/src/Support/LogOptions.php @@ -0,0 +1,228 @@ + */ + public array $logAttributes = []; + + /** @var list */ + public array $logExceptAttributes = []; + + /** @var list */ + public array $dontLogIfAttributesChangedOnly = []; + + /** @var list */ + public array $attributeRawValues = []; + + public bool $refreshBeforeLogging = false; + + /** @var null|Closure(string): string */ + public ?Closure $descriptionForEvent = null; + + /** + * Start configuring model with the default options. + */ + public static function defaults(): self + { + return new self; + } + + /** + * Log all attributes on the model. + */ + public function logAll(): self + { + return $this->logOnly(['*']); + } + + /** + * Log all attributes that are not listed in $guarded. + */ + public function logUnguarded(): self + { + $this->logUnguarded = true; + + return $this; + } + + /** + * Log changes to all the $fillable attributes of the model. + */ + public function logFillable(): self + { + $this->logFillable = true; + + return $this; + } + + /** + * Stop logging $fillable attributes of the model. + */ + public function dontLogFillable(): self + { + $this->logFillable = false; + + return $this; + } + + /** + * Log only changes that actually changed after the update. + */ + public function logOnlyDirty(): self + { + $this->logOnlyDirty = true; + + return $this; + } + + /** + * Only log changes to these specific attributes. + * + * @param list $attributes + */ + public function logOnly(array $attributes): self + { + $this->logAttributes = $attributes; + + return $this; + } + + /** + * Exclude these attributes from being logged. + * + * @param list $attributes + */ + public function logExcept(array $attributes): self + { + $this->logExceptAttributes = $attributes; + + return $this; + } + + /** + * Don't trigger an activity if only these attributes changed. + * + * @param list $attributes + */ + public function dontLogIfAttributesChangedOnly(array $attributes): self + { + $this->dontLogIfAttributesChangedOnly = $attributes; + + return $this; + } + + /** + * Don't store empty logs. Empty logs can occur when you're tracking + * specific attributes but none of them actually changed. + */ + public function dontLogEmptyChanges(): self + { + $this->logEmptyChanges = false; + + return $this; + } + + /** + * Allow storing empty logs. + */ + public function logEmptyChanges(): self + { + $this->logEmptyChanges = true; + + return $this; + } + + /** + * Customize log name. + */ + public function useLogName(BackedEnum|string|null $logName): self + { + $this->logName = $logName instanceof BackedEnum ? (string) $logName->value : $logName; + + return $this; + } + + /** + * Customize log description using callback. + * + * @param Closure(string): string $callback + */ + public function setDescriptionForEvent(Closure $callback): self + { + $this->descriptionForEvent = $callback; + + return $this; + } + + /** + * Exclude these attributes from casting. + * + * @param list $attributes + */ + public function useAttributeRawValues(array $attributes): self + { + $this->attributeRawValues = $attributes; + + return $this; + } + + /** + * Refresh persisted values before logging. + */ + public function refreshBeforeLogging(): self + { + $this->refreshBeforeLogging = true; + + return $this; + } + + /** + * Serialize the activity log options. + * + * @return array + */ + public function __serialize(): array + { + $data = get_object_vars($this); + + if ($this->descriptionForEvent !== null) { + $data['descriptionForEvent'] = new SerializableClosure($this->descriptionForEvent); + } + + return $data; + } + + /** + * Restore serialized activity log options. + * + * @param array $data + */ + public function __unserialize(array $data): void + { + foreach ($data as $key => $value) { + if ($key === 'descriptionForEvent' && $value instanceof SerializableClosure) { + $value = $value->getClosure(); + } + + $this->{$key} = $value; + } + } +} diff --git a/src/activity-log/src/helpers.php b/src/activity-log/src/helpers.php new file mode 100644 index 000000000..09caf665c --- /dev/null +++ b/src/activity-log/src/helpers.php @@ -0,0 +1,16 @@ +logger($logName); + } +} diff --git a/src/database/src/Eloquent/Concerns/HasAttributes.php b/src/database/src/Eloquent/Concerns/HasAttributes.php index 031676433..14ae9d5a3 100644 --- a/src/database/src/Eloquent/Concerns/HasAttributes.php +++ b/src/database/src/Eloquent/Concerns/HasAttributes.php @@ -2085,6 +2085,17 @@ protected function getAttributesForInsert(): array return $this->getAttributes(); } + /** + * Prepare the model's insert attributes for database binding. + * + * @internal + * @return array + */ + public function getDatabaseAttributesForInsert(): array + { + return $this->prepareBinaryAttributesForDatabase($this->getAttributesForInsert()); + } + /** * Determine whether the given attribute uses the binary cast. */ diff --git a/src/database/src/Eloquent/Concerns/HasRelationships.php b/src/database/src/Eloquent/Concerns/HasRelationships.php index 7f42a13fc..ec68b5f2b 100644 --- a/src/database/src/Eloquent/Concerns/HasRelationships.php +++ b/src/database/src/Eloquent/Concerns/HasRelationships.php @@ -391,6 +391,19 @@ public function morphTo(?string $name = null, ?string $type = null, ?string $id : $this->morphInstanceTo($class, $name, $type, $id, $ownerKey); } + /** + * Report a missing morph type unless a known null foreign key already rules out a target. + * + * @internal + */ + public function ensureMorphTypeIsLoaded(string $type, string $foreignKey): void + { + if (! array_key_exists($type, $this->attributes) + && (! array_key_exists($foreignKey, $this->attributes) || $this->attributes[$foreignKey] !== null)) { + $this->throwMissingAttributeExceptionIfApplicable($type); + } + } + /** * Define a polymorphic, inverse one-to-one or many relationship. * @@ -398,15 +411,19 @@ public function morphTo(?string $name = null, ?string $type = null, ?string $id */ protected function morphEagerTo(string $name, string $type, string $id, ?string $ownerKey): MorphTo { + $query = $this->newQuery()->setEagerLoads([]); + $make = fn () => $this->newMorphTo($query, $this, $id, $ownerKey, $type, $name); + + if (Relation::shouldAddConstraints()) { + // The query is on this model's table until eager loading supplies a target type. + $query->whereRaw('0 = 1'); + $relation = Relation::noConstraintsForRelation($make); + } else { + $relation = $make(); + } + // @phpstan-ignore return.type (MorphTo vs MorphTo - template covariance) - return $this->newMorphTo( - $this->newQuery()->setEagerLoads([]), - $this, - $id, - $ownerKey, - $type, - $name - ); + return $relation->asEagerLoadingPlaceholder(); } /** diff --git a/src/database/src/Eloquent/Model.php b/src/database/src/Eloquent/Model.php index d0cc9d27e..0abacee1d 100644 --- a/src/database/src/Eloquent/Model.php +++ b/src/database/src/Eloquent/Model.php @@ -1824,9 +1824,7 @@ protected function performInsert(Builder $query): bool // If the model has an incrementing key, we can use the "insertGetId" method on // the query builder, which will give us back the final inserted ID for this // table from the database. Not all tables have to be incrementing though. - $attributes = $this->prepareBinaryAttributesForDatabase( - $this->getAttributesForInsert() - ); + $attributes = $this->getDatabaseAttributesForInsert(); if ($this->getIncrementing()) { $this->insertAndSetId($query, $attributes); @@ -1879,9 +1877,7 @@ protected function performInsertOrIgnore(Builder $query, array|string|null $uniq $this->updateTimestamps(); } - $attributes = $this->prepareBinaryAttributesForDatabase( - $this->getAttributesForInsert() - ); + $attributes = $this->getDatabaseAttributesForInsert(); if ($attributes === []) { throw new LogicException('Cannot use saveOrIgnore on a model without attributes.'); diff --git a/src/database/src/Eloquent/Relations/MorphTo.php b/src/database/src/Eloquent/Relations/MorphTo.php index 41b0fd0c9..c181a1819 100644 --- a/src/database/src/Eloquent/Relations/MorphTo.php +++ b/src/database/src/Eloquent/Relations/MorphTo.php @@ -38,6 +38,9 @@ class MorphTo extends BelongsTo */ protected bool $ownerKeyInferred = false; + /** @internal */ + public private(set) bool $eagerLoadingPlaceholder = false; + /** * The models whose relations are being eager loaded. * @@ -83,6 +86,33 @@ public function __construct(Builder $query, Model $parent, string $foreignKey, ? parent::__construct($query, $parent, $foreignKey, $ownerKey, $relation); } + /** + * Mark the source-model query built before a morph target is known. + * + * @internal + * @return $this + */ + public function asEagerLoadingPlaceholder(): static + { + $this->eagerLoadingPlaceholder = true; + + return $this; + } + + #[Override] + public function getResults() + { + if (! $this->eagerLoadingPlaceholder) { + return parent::getResults(); + } + + if ($this->parent::preventsAccessingMissingAttributes()) { + $this->parent->ensureMorphTypeIsLoaded($this->morphType, $this->foreignKey); + } + + return $this->getDefaultFor($this->parent); + } + #[Override] public function addEagerConstraints(array $models): void { @@ -277,7 +307,7 @@ public function dissociate(): Model #[Override] public function touch(): void { - if (! is_null($this->getParentKey())) { + if (! $this->eagerLoadingPlaceholder && ! is_null($this->getParentKey())) { parent::touch(); } } diff --git a/src/database/src/Eloquent/SoftDeletes.php b/src/database/src/Eloquent/SoftDeletes.php index 1e2b6ed0e..a6a916abd 100644 --- a/src/database/src/Eloquent/SoftDeletes.php +++ b/src/database/src/Eloquent/SoftDeletes.php @@ -22,6 +22,8 @@ trait SoftDeletes */ protected bool $forceDeleting = false; + protected bool $beingRestored = false; + /** * Boot the soft deleting trait for a model. */ @@ -172,7 +174,14 @@ public function restore(): bool // totally finished. Then we will return the result of the save call. $this->exists = true; - $result = $this->save(); + $previous = $this->beingRestored; + $this->beingRestored = true; + + try { + $result = $this->save(); + } finally { + $this->beingRestored = $previous; + } if ($result) { $this->fireModelEvent('restored', false); @@ -181,6 +190,14 @@ public function restore(): bool return $result; } + /** + * Determine whether the model is being saved by restore(). + */ + public function isBeingRestored(): bool + { + return $this->beingRestored; + } + /** * Restore a soft-deleted model instance without raising any events. */ diff --git a/src/docs/activity-log.md b/src/docs/activity-log.md new file mode 100644 index 000000000..2463ae4e7 --- /dev/null +++ b/src/docs/activity-log.md @@ -0,0 +1,788 @@ +# Activity Log + +- [Introduction](#introduction) +- [Installation](#installation) + - [Morph Key Type](#morph-key-type) +- [Configuration](#configuration) +- [Logging Activity](#logging-activity) + - [Subjects and Causers](#subjects-and-causers) + - [Properties and Changes](#properties-and-changes) + - [Events, Dates, and Log Names](#events-dates-and-log-names) + - [Placeholders](#placeholders) + - [Conditional Logging](#conditional-logging) +- [Logging Model Events](#logging-model-events) + - [Selecting Attributes](#selecting-attributes) + - [Dirty and Empty Changes](#dirty-and-empty-changes) + - [Casts, Raw Values, and JSON Paths](#casts-raw-values-and-json-paths) + - [Related Attributes](#related-attributes) + - [Recorded Events](#recorded-events) + - [Descriptions and Log Names](#descriptions-and-log-names) + - [Refreshing Database Values](#refreshing-database-values) + - [Disabling Model Logging](#disabling-model-logging) +- [Querying Activity](#querying-activity) +- [Scoped Causers and Logging Status](#scoped-causers-and-logging-status) +- [Callbacks and Macros](#callbacks-and-macros) + - [Request Batch UUIDs](#request-batch-uuids) +- [Buffering](#buffering) + - [Transactions](#transactions) + - [Flush Boundaries](#flush-boundaries) + - [Failures and Delivery Guarantees](#failures-and-delivery-guarantees) +- [Cleaning the Log](#cleaning-the-log) +- [Customizing Storage and Actions](#customizing-storage-and-actions) +- [High-Volume Applications](#high-volume-applications) +- [Migrating From Spatie](#migrating-from-spatie) +- [Security](#security) +- [Testing](#testing) +- [Credits](#credits) + + +## Introduction + +Hypervel Activity Log makes it easy to record application activity and Eloquent model events in a queryable database table. The package follows the familiar Spatie Laravel Activity Log API while adapting runtime state and optional buffering for Hypervel's coroutine-based workers. + +The package uses `ActivityLog` and `activity-log` casing. You may use the global `activity()` helper to record an activity with a single fluent call. + + +## Installation + +Install the package through Composer: + +```shell +composer require hypervel/activity-log +``` + +Hypervel automatically discovers the package's service provider. Publish the configuration and migration, then run migrations: + +```shell +php artisan vendor:publish --tag=activity-log-config +php artisan vendor:publish --tag=activity-log-migrations +php artisan migrate +``` + +The migration is publish-only so your application can adjust its table, indexes, morph keys, or tenant columns before running it. + +Do not install this package alongside `spatie/laravel-activitylog`. Both packages define `activity()` and use `activity_log` by default, so Composer load order would decide which helper runs. + + +### Morph Key Type + +The published migration uses `nullableMorphs()` for subjects and causers. It follows Hypervel's application-wide morph key type: integer by default, or UUID/ULID when configured at boot. + +```php +use Hypervel\Database\Schema\Builder as SchemaBuilder; + +public function boot(): void +{ + SchemaBuilder::morphUsingUuids(); +} +``` + +Use `morphUsingUlids()` for ULIDs. Set the type before running the activity migration, and make sure it matches the keys used by every possible subject and causer. Changing the type after the table exists requires an application migration. + + +## Configuration + +The published `config/activity-log.php` contains these settings: + +| Key | Default | Purpose | +| --- | --- | --- | +| `enabled` | `true` | Initial logging status for each request or job scope | +| `clean_after_days` | `365` | Default retention used by `activity-log:clean` | +| `clean_batch_size` | `1000` | Maximum rows selected and deleted per cleanup batch | +| `cleanup.enabled` | `false` | Schedule the cleanup command | +| `cleanup.schedule` | `9 4 * * *` | Cron expression for scheduled cleanup | +| `default_log_name` | `default` | Log name used when `activity()` receives `null` | +| `default_auth_driver` | `null` | Guard used to resolve the authenticated causer; `null` uses the current guard | +| `include_soft_deleted_subjects` | `false` | Include soft-deleted subjects without removing other global scopes | +| `activity_model` | package `Activity` model | Model used for reads and writes | +| `default_except_attributes` | `[]` | Attributes excluded from automatic logging for every model | +| `buffer.enabled` | `false` | Enable coroutine-scoped bulk buffering | +| `buffer.batch_size` | `500` | Maximum activity rows handled by each buffered batch | +| `actions.log_activity` | package action | Logging pipeline action | +| `actions.clean_log` | package action | Retention action | + +The package configuration reads the following environment variables. + +```dotenv +ACTIVITY_LOG_ENABLED=true +ACTIVITY_LOG_CLEAN_BATCH_SIZE=1000 +ACTIVITY_LOG_CLEANUP_ENABLED=false +ACTIVITY_LOG_CLEANUP_SCHEDULE="9 4 * * *" +ACTIVITY_LOG_BUFFER_ENABLED=false +ACTIVITY_LOG_BUFFER_BATCH_SIZE=500 +``` + +Hypervel merges package configuration at the top level. Therefore, if your application defines its own `cleanup`, `buffer`, or `actions` group, it should include every value from that group. A custom `buffer` group must contain both `enabled` and `batch_size`, while a custom `actions` group must contain both action classes. + +> [!NOTE] +> Configuration is shared by every request in a worker, and configured model and action classes are cached for the worker lifetime. Restart the server and any other long-running processes that use these settings after changing configuration. For request-specific causers or logging status, use the [scoped runtime APIs](#scoped-causers-and-logging-status) instead of changing configuration during a request. + + +## Logging Activity + +The helper creates a fresh logger for each root call: + +```php +$activity = activity('billing') + ->performedOn($invoice) + ->causedBy($user) + ->event('paid') + ->withProperties(['gateway' => 'stripe']) + ->log('Invoice :subject.number was paid by :causer.name'); +``` + +The `log` method returns the activity model, or `null` when logging is disabled. Without buffering, the model has already been saved when it is returned. When buffering is enabled, it will be inserted at one of the package's [flush boundaries](#flush-boundaries). + +Each logger chain records one activity. Once `log()` has been called, the logger resets whether logging succeeds, fails, or is skipped. Reusing that logger starts the next chain with the configured default log name. + +The `ActivityLog` facade exposes the same fluent methods. `ActivityLog::logger()` returns a fresh logger when you need to hold more than one chain at once. + + +### Subjects and Causers + +Use `performedOn()` or `on()` to associate a subject. Use `causedBy()` or `by()` with an Eloquent model or authenticated identifier: + +```php +activity() + ->on($invoice) + ->by($user) + ->log('Invoice updated'); +``` + +When no explicit causer is supplied, the current authenticated Eloquent user is resolved lazily just before `tap()` or `log()`. Passing `null` to `causedBy()` is a no-op and still allows that default. Use `causedByAnonymous()` or `byAnonymous()` to make an explicit anonymous decision: + +```php +activity()->causedByAnonymous()->log('Automated cleanup completed'); +``` + +Anonymous logging clears both morph columns and any already loaded causer relation. + + +### Properties and Changes + +Add arbitrary JSON properties with `withProperties()` or `withProperty()`: + +```php +activity() + ->withProperties([ + 'request_id' => $requestId, + 'ip' => $request->ip(), + ]) + ->withProperty('channel', 'api') + ->log('Request accepted'); +``` + +`withChanges()` sets the activity's `attribute_changes` payload directly: + +```php +activity() + ->withChanges([ + 'attributes' => ['status' => 'paid'], + 'old' => ['status' => 'pending'], + ]) + ->log('Invoice status changed'); +``` + +Read nested properties through `getProperty()`: + +```php +$requestId = $activity->getProperty('request.id'); +$fallback = $activity->getProperty('missing', 'unknown'); +``` + + +### Events, Dates, and Log Names + +Set an event with `event()` or `setEvent()`, and override the timestamp with `createdAt()`: + +```php +use Hypervel\ActivityLog\Enums\ActivityEvent; + +activity() + ->event(ActivityEvent::Updated) + ->createdAt($occurredAt) + ->log('Imported activity'); +``` + +The `createdAt()` method uses the activity model's configured created-at column. It cannot be used when that model does not define one. + +Use `activity('security')`, `useLog()`, or `inLog()` to select a log. These methods, `LogOptions::useLogName()`, and the `inLog` query scope also accept backed enums. Their backing values are stored as strings. Passing `null` to `activity()` selects `default_log_name`; empty string and `"0"` are valid, distinct log names. Calling `useLog(null)` or `inLog(null)` explicitly sets the pending activity's log name to `null`. + + +### Placeholders + +Descriptions can reference dotted values under `subject`, `causer`, and `properties`: + +```php +activity() + ->performedOn($invoice) + ->causedBy($user) + ->withProperty('gateway', 'stripe') + ->log(':causer.name paid :subject.number through :properties.gateway'); +``` + +Scalar and stringable values expand in descriptions. Enums expand to their backing value or case name. For a missing value, null, an array, or an object without a string representation, the placeholder stays in the description. + +Use `tap()` when the pending activity needs a change that is not covered by the fluent methods: + +```php +activity() + ->tap(function ($activity): void { + $activity->setAttribute('event', 'approved'); + }) + ->log('Invoice approved'); +``` + +The default causer has already been associated when the tap runs. + + +### Conditional Logging + +Activity loggers use Hypervel's `Conditionable` concern: + +```php +activity() + ->when($invoice->wasPaid(), fn ($logger) => $logger->event('paid')) + ->unless($request->user(), fn ($logger) => $logger->causedByAnonymous()) + ->log('Invoice processed'); +``` + + +## Logging Model Events + +Add `LogsActivity` to a model and return its options: + +```php +use Hypervel\Database\Eloquent\Model; +use Hypervel\ActivityLog\Models\Concerns\LogsActivity; +use Hypervel\ActivityLog\Support\LogOptions; + +class Invoice extends Model +{ + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['number', 'status', 'total']) + ->logOnlyDirty() + ->dontLogEmptyChanges(); + } +} +``` + +By default, the concern records the `created`, `updated`, and `deleted` events, as well as `restored` when the model uses soft deletes. The activity stores current values under `attribute_changes.attributes`, previous update values under `attribute_changes.old`, and deleted values under `old` only. + +The default options record the event without selecting model attributes. Use the methods below to choose the values that should be included in `attribute_changes`. + +`CausesActivity` adds `activitiesAsCauser()`. `HasActivity` combines `LogsActivity` and `CausesActivity`, and adds `activities()` as an alias for `activitiesAsSubject()`. + + +### Selecting Attributes + +`LogOptions` provides these selection methods: + +- `logOnly([...])` selects explicit direct, JSON, or dotted-relation attributes. `['*']` selects all attributes currently hydrated on the event model. +- `logAll()` is an alias for `logOnly(['*'])`. +- `logFillable()` includes the model's fillable attributes. +- `dontLogFillable()` turns that inclusion off again. +- `logUnguarded()` includes attributes that are not guarded. +- `logExcept([...])` removes selected attributes. + +The selected sets are combined, deduplicated, then reduced by `logExcept()` and `default_except_attributes`. + +Wildcard and unguarded selection use the attributes present on the event model. They do not issue a query to discover unloaded columns. Use `refreshBeforeLogging()` when a complete post-write row is required. + + +### Dirty and Empty Changes + +`logOnlyDirty()` keeps only values that differ between the current and old update snapshots. `dontLogIfAttributesChangedOnly([...])` suppresses the event when the model changed only ignored attributes such as `updated_at`. + +Empty activity records are allowed by default. Use `dontLogEmptyChanges()` to skip them, or `logEmptyChanges()` to turn them back on: + +```php +return LogOptions::defaults() + ->logOnly(['status']) + ->logOnlyDirty() + ->dontLogIfAttributesChangedOnly(['updated_at']) + ->dontLogEmptyChanges(); +``` + + +### Casts, Raw Values, and JSON Paths + +Selected values follow Eloquent accessors and casts, including enums, custom date formats, date attributes, intervals, class casts, and modern `Attribute` accessors. When a class cast defines how it serializes its value, Activity Log uses that representation. For example, a collection of non-backed enum cases is recorded as an array of case names. Reading these values for an activity does not change the subject model's attributes, cast values, dirty state, or loaded relations. + +Use `useAttributeRawValues()` for stored bytes instead of cast-visible values: + +```php +return LogOptions::defaults() + ->logOnly(['payload', 'secret']) + ->useAttributeRawValues(['secret']); +``` + +For normal create and update operations, raw values come from the model's write state. If your model customizes `getDirtyForUpdate()` to transform database values, or a cached cast has been read but not written, the in-memory value may differ from the stored row. Use [database refresh](#refreshing-database-values) when the stored row must be authoritative. + +Without refresh, a `restored` event records the values available from the model's restore operation and event snapshot. If you need the complete current database row after a restore, enable refresh and wrap `restore()` in a transaction. + +Select a nested JSON value with Eloquent's arrow syntax: + +```php +return LogOptions::defaults()->logOnly([ + 'settings->notifications->email', +]); +``` + +The stored change payload uses a matching nested array shape. Selecting the whole column or a parent path records its full value. To record only a safe subset, select those paths explicitly. + + +### Related Attributes + +Use a dotted path to read through singular Eloquent relations: + +```php +return LogOptions::defaults()->logOnly([ + 'customer.name', + 'customer.account.region', +]); +``` + +Each segment may use the exact relation name, its snake/camel alias, or a relation registered with `resolveRelationUsing()`. The leaf value is the value returned by the related model's attribute accessor or cast. The activity key remains exactly as configured. For example, `customer_profile.name` stays `customer_profile.name` even when traversal calls `customerProfile()`. + +A null relation or an omitted relation key on a partially selected model produces the configured key with a null value. Load the foreign key before the write if your audit record needs the old related value. Undefined relations and to-many results throw a clear exception; dotted logging is limited to singular model relations. + +Without refresh, direct subject values come from the model event without a query. Dotted relations are live queries. An update can query both the current and old foreign-key paths. If subject and related values must form one database snapshot, perform the write in a transaction with an isolation level that provides the consistency your application needs. + + +### Recorded Events + +Customize model events with typed static properties: + +```php +use Hypervel\ActivityLog\Enums\ActivityEvent; + +protected static array $recordEvents = [ + ActivityEvent::Created->value, + ActivityEvent::Updated->value, + ActivityEvent::Retrieved->value, +]; + +protected static array $doNotRecordEvents = [ + ActivityEvent::Deleted->value, +]; +``` + +`ActivityEvent` contains `Created`, `Updated`, `Deleted`, `Restored`, and `Retrieved`. Other Eloquent model event names may also be placed in `$recordEvents`. + +Restoring a soft-deleted model records one `restored` activity rather than a second `updated` activity. Retrieved activities use the hydrated database result already present on the model. + + +### Descriptions and Log Names + +Customize automatic descriptions and log names through `LogOptions`: + +```php +return LogOptions::defaults() + ->useLogName('billing') + ->setDescriptionForEvent( + fn (string $event): string => "Invoice was {$event}", + ); +``` + +Description closures remain serializable with the model and its active options. Models may also override `getDescriptionForEvent()` and `getLogNameToUse()`. + +If the subject defines a public `beforeActivityLogged($activity, $eventName)`, it runs after change transformation and before global callbacks and persistence. + + +### Refreshing Database Values + +By default, automatic logging uses the model values from the event. It does not select the subject again, avoiding a query and preventing a later writer's values from being recorded for the current event. + +Use `refreshBeforeLogging()` when database defaults, generated columns, or triggers must be included: + +```php +public function getActivityLogOptions(): LogOptions +{ + return LogOptions::defaults() + ->logAll() + ->refreshBeforeLogging(); +} +``` + +The option applies only to `created`, `updated`, and `restored`. It requires an active transaction on the subject's connection and performs one additional read using that connection without dispatching a `retrieved` event. The `saveOrFail()` method provides a transaction for saves, or you may wrap the write explicitly: + +```php +use Hypervel\Support\Facades\DB; + +DB::transaction(function () use ($invoice): void { + $invoice->status = 'paid'; + $invoice->save(); +}); +``` + +`restore()` does not create its own transaction, so a refreshed restore must always be wrapped in `DB::transaction()`. + +When refresh is enabled, the package selects wildcard, fillable, unguarded, and explicit attributes from the refreshed model. If you override the protected `resolveModelForLogging()` method, selection is re-run against the model returned by your override. + +Refreshing does not add a pre-write query. On a partially selected model, a newly refreshed column has no guaranteed old value and can appear as changed from `null`. Load every old value needed by the audit record before the write. + + +### Disabling Model Logging + +Disable or re-enable one subject instance without changing the rest of the request: + +```php +$invoice->disableLogging(); +$invoice->touch(); +$invoice->enableLogging(); +``` + +The public `$enableLoggingModelsEvents` property remains available for advanced model integrations. + + +## Querying Activity + +The default model provides attributed scopes for log, causer, subject, and event: + +```php +use Hypervel\ActivityLog\Enums\ActivityEvent; +use Hypervel\ActivityLog\Models\Activity; + +$activities = Activity::query() + ->inLog('billing', 'security') + ->forSubject($invoice) + ->causedBy($user) + ->forEvent(ActivityEvent::Updated) + ->latest('id') + ->paginate(); +``` + +`inLog()` accepts individual names, an array, or both. `forEvent()` accepts an `ActivityEvent` or string. + +Access the polymorphic relations and JSON values normally: + +```php +$subject = $activity->subject; +$causer = $activity->causer; +$newStatus = $activity->attribute_changes['attributes']['status'] ?? null; +$requestId = $activity->getProperty('request.id'); +``` + +Enable `include_soft_deleted_subjects` when the `subject` relation should remove `SoftDeletingScope`. Other subject global scopes remain active. + +JSON queries use your database driver's normal Eloquent syntax: + +```php +Activity::query() + ->where('properties->request_id', $requestId) + ->get(); +``` + +Add application-specific JSON indexes only for measured predicates; index syntax and useful operator classes differ across supported databases. + + +## Scoped Causers and Logging Status + +Default causers and logging status are scoped to the current request, command, or job coroutine. You may set them in middleware or while handling a command or job. Do not set request-specific values from a service provider's `boot()` method. + +```php +use Hypervel\ActivityLog\Facades\ActivityLog; + +return ActivityLog::defaultCauser( + $serviceAccount, + fn () => $next($request), +); +``` + +Within this scope the selected causer takes precedence over `causedBy()` and custom resolution callbacks. Use `causedByAnonymous()` for an anonymous entry. The callback form restores the previous causer in a `finally` block and nests safely. Without a callback, `defaultCauser()` changes the remainder of the current scope. + +For advanced identifier mapping, configure the scoped resolver: + +```php +use Hypervel\ActivityLog\Support\CauserResolver; + +$resolver = app(CauserResolver::class); +$resolver->resolveUsing(function ($subject) use ($tenant) { + return $subject === null + ? $tenant->systemUser + : $tenant->users()->findOrFail($subject); +}); +``` + +The callback may return an Eloquent model, integer/string auth identifier, or null. Invalid results throw without rendering object contents. + +Disable the current scope directly or around one callback: + +```php +ActivityLog::disableLogging(); + +$result = ActivityLog::withoutLogging(function () use ($invoice) { + return $invoice->recalculate(); +}); + +ActivityLog::enableLogging(); +``` + +`withoutLogging()` restores the prior status even when nested or when the callback throws. + + +## Callbacks and Macros + +Register global callbacks and logger macros during worker boot: + +```php +use Hypervel\Database\Eloquent\Model; +use Hypervel\ActivityLog\Contracts\Activity as ActivityContract; +use Hypervel\ActivityLog\Facades\ActivityLog; + +ActivityLog::beforeLogging( + static function (ActivityContract&Model $activity): void { + // Resolve request or tenant state here, when the callback runs. + }, +); + +ActivityLog::macro('forImport', function (string $importId) { + return $this->withProperty('import_id', $importId); +}); +``` + +Callbacks run in registration order after description placeholders, action change transformation, and the subject's `beforeActivityLogged()` hook. They run before either immediate persistence or buffer insertion. + +Because callbacks remain registered for the worker lifetime, they should not capture a request, model, user, or tenant from `boot()`. Instead, resolve request-specific state inside the callback when it runs. + +Macros run on fresh logger instances. `flushMacros()` and `LogActivityAction::flushState()` are boot/test cleanup tools, not request APIs. + +Use `ActivityLog::mixin($object)` to register the closures returned by its public and protected methods as macros. `ActivityLog::hasMacro($name)` checks whether a macro is registered. + + +### Request Batch UUIDs + +Store a grouping value in coroutine context when several activities from one request or job should share an identifier: + +```php +use Hypervel\Context\CoroutineContext; +use Hypervel\Database\Eloquent\Model; +use Hypervel\Support\Collection; +use Hypervel\Support\Str; +use Hypervel\ActivityLog\Contracts\Activity as ActivityContract; +use Hypervel\ActivityLog\Facades\ActivityLog; + +ActivityLog::beforeLogging(function (ActivityContract&Model $activity): void { + $batchUuid = CoroutineContext::getOrSet( + '__app.activity-batch-uuid', + static fn (): string => (string) Str::uuid7(), + ); + /** @var Collection $properties */ + $properties = $activity->getAttribute('properties'); + + $activity->setAttribute('properties', $properties->put('batch_uuid', $batchUuid)); +}); +``` + +The callback is application code, so choose a key in your application's context namespace. Do not use `__activity-log.*`; that namespace is reserved for package-owned state. Creating the UUID directly in `boot()` would group every request served by the worker under one value. + +The default schema stores this UUID in `properties`; it does not add a `batch_uuid` column. + + +## Buffering + +When one request or job records many activities, buffering can reduce database load by combining them into bounded bulk inserts: + +```dotenv +ACTIVITY_LOG_BUFFER_ENABLED=true +ACTIVITY_LOG_BUFFER_BATCH_SIZE=500 +``` + +Buffered activities are kept in memory for the current coroutine and are never combined with activities from another request or job. The buffer is created only when the first activity needs it. + +> [!WARNING] +> Buffering is not a durable queue. If you need activities to survive a worker crash or to be delivered across database connections, use an application outbox or queue. + +Buffered activities are written in call order. Custom columns, timestamp settings, and database defaults are preserved. + +Before enabling buffering, keep these differences in mind: + +- the returned model keeps any preassigned or Eloquent-generated UUID/ULID key, but it does not receive a database-generated ID from the later bulk insert; query the persisted row after flush when that ID is needed; +- bulk inserts bypass activity model `creating`, `saving`, `created`, and `saved` events; +- placeholders, action transformations, subject hooks, global callbacks, and timestamp preparation run before buffering; +- an activity whose table or connection differs from the buffer's captured target is rejected. + +A UUID/ULID key can therefore exist before the row is persisted. Do not treat a non-null key as proof of persistence while buffering. + + +### Transactions + +An activity prepared while its own activity connection is transacting is staged against that exact connection. The outer commit makes it eligible for insertion; rollback discards it. Savepoint order is preserved, and a transaction on another connection does not decide its outcome. + +After the domain transaction commits, buffered activities are written in a new transaction. Activities from rolled-back transactions are discarded, but the later insert is not atomic with your domain changes. A crash between the two commits can lose the activity. + +If the activity must commit atomically with domain data, disable buffering and write it immediately using the same transaction and connection. For durable or cross-connection delivery, use an application outbox. + +Calling `ActivityBuffer::flush()` while the buffer has work and its activity connection has an open application transaction throws. It drains rows in call order and stops at the first activity whose transaction outcome is still pending. + +Normal applications should rely on lifecycle flushing. Advanced code may resolve the scoped `ActivityBuffer` and call `flush()` after its activity-connection transaction has completed when it needs an earlier persistence boundary. + + +### Flush Boundaries + +Activities are flushed when the configured batch size is reached and at the following lifecycle boundaries: + +- application termination for HTTP and console scopes; +- completion of every asynchronous job attempt, including failed and retryable attempts; +- coroutine exit as a fallback for activities recorded by an ad-hoc coroutine. + +Synchronous jobs share their caller's coroutine and are flushed at the caller's enclosing lifecycle boundary. Failures from normal application and asynchronous job flushes are thrown to the caller. If the coroutine-exit fallback cannot persist an activity, Hypervel reports the failure through its exception handler. + +The buffer remains available for the full scope. Therefore, if a later termination callback records another activity after an earlier flush, the coroutine-exit fallback will still persist it. + + +### Failures and Delivery Guarantees + +Rows that are already being inserted cannot be selected again if a callback records more activity during that insert. Any additional finite work is flushed at the same lifecycle boundary. + +The package does not automatically retry an attempted batch. If an insert fails, the failed batch is removed from the in-memory buffer and the original failure is thrown or reported. Rows that have not yet been attempted remain eligible for a later flush. + +If the database cannot confirm whether a `COMMIT` succeeded, the package cannot safely retry the batch without risking duplicates. In this case, delivery is necessarily uncertain. + +Do not configure a query hook or committed-event listener that records another activity for every activity-log insert or commit. This would cause each activity insert to create another activity indefinitely. Exclude activity-log persistence from such hooks or listeners. + + +## Cleaning the Log + +Delete activities older than the configured retention period: + +```shell +php artisan activity-log:clean +``` + +Override the age or restrict cleanup to one log: + +```shell +php artisan activity-log:clean --days=90 +php artisan activity-log:clean billing --days=30 +``` + +The command asks for confirmation in production unless `--force` is supplied. Days and configured batch sizes must be positive integers. + +Cleanup repeatedly selects and deletes at most `clean_batch_size` rows, ordered by the activity model's configured created-at column and primary key. Both steps retain model global scopes and repeat the age/log predicate, so a row changed between selection and deletion is protected. + +Scheduled cleanup is off by default. Set `cleanup.enabled` in `config/activity-log.php` to run `activity-log:clean --force` daily at 04:09. Change `cleanup.schedule` to choose another time. You can keep scheduled cleanup enabled when activity logging is off. + +The published migration includes `(created_at, id)` and `(log_name, created_at, id)` indexes for global and per-log cleanup. If your activity model renames its created-at column, update both indexes in the adapted migration to use that column. Large deletes still create normal database maintenance work; monitor table growth, replication lag, and driver-specific vacuum/reclaim needs. + +The default cleanup action honors a renamed created-at column. If the activity model does not define a created-at column, provide a custom cleanup action for the schema. + + +## Customizing Storage and Actions + +The configured activity model must extend Eloquent `Model`, implement `Contracts\Activity`, be concrete, and have no required constructor arguments. Extending the package model is the simplest way to preserve casts, relations, scopes, and property lookup: + +```php +use Hypervel\ActivityLog\Models\Activity as BaseActivity; + +class Activity extends BaseActivity +{ + protected ?string $connection = 'audit'; + + protected ?string $table = 'audit_entries'; +} +``` + +Set `activity_model` to the class and adapt the published migration. For a dedicated audit database, set the connection on both sides of each relationship. For example, set `$connection = 'audit'` on the activity model and `$connection = 'mysql'` on the subject and causer models. Eloquent inherits the parent model’s connection when the related model leaves its connection unset. This applies when reading a subject or causer from an activity and when reading activity history from a subject or causer. + +Custom actions must extend `LogActivityAction` or `CleanActivityLogAction`. Set them in `actions.log_activity` and `actions.clean_log`. The service container honors explicit bindings and otherwise creates a fresh action for each operation. Useful protected extension points include: + +- `LogActivityAction::transformChanges()`, `beforeActivityLogged()`, and `save()`; +- `CleanActivityLogAction::getCutOffDate()` and `deleteOldActivities()`. + +Keep the logging pipeline order when extending it: placeholders, change transformation, subject hook, global callbacks, then persistence/buffering. + +The `LogsActivity::attributesToBeLogged()` and `LogsActivity::extractChanges()` methods are public for model and action integrations. You may also override the protected event selection and change-building methods. When overriding snapshot selection, make sure your implementation provides the query and transaction consistency required by your application. + +Published migrations belong to the application. Add tenant columns, partitions, or application indexes there. A morph type and ID alone cannot distinguish tenants with the same model IDs. If one physical table serves multiple tenants, add tenant predicates to custom query/cleanup surfaces and include tenant columns in the indexes that support those predicates. + + +## High-Volume Applications + +Choose each cost deliberately: + +- select only audit-useful attributes and exclude large or sensitive payloads; +- use `logOnlyDirty()` and `dontLogEmptyChanges()` when unchanged snapshots provide no value; +- keep the default no-query subject snapshot unless generated database values are required; +- every dotted relation path adds live relation work, and updates may need current and old paths; +- enable buffering when a single scope produces enough rows to benefit from bounded bulk inserts; +- paginate activity queries by an indexed order rather than loading the full history; +- run bounded cleanup often enough that retention does not create a large backlog; +- add composite or JSON indexes from measured application queries, not as generic defaults. + +The package does not sample or silently drop routine activity to reduce load. If the application cannot retain every event, define that policy explicitly before calling the logger or move durable high-volume ingestion through an outbox/queue designed for it. + + +## Migrating From Spatie + +Remove `spatie/laravel-activitylog` before installing this package. Update namespaces from `Spatie\Activitylog` to `Hypervel\ActivityLog`, rename published configuration to `activity-log.php`, and update command/config references to `activity-log` casing. The `activity()` helper remains available. + +For a Spatie 5.x installation: + +1. Confirm the existing `activity_log` columns and morph key types match the Hypervel model policy. +2. Reuse the existing table; do not run the package's create migration against it. +3. Publish/copy the complete Hypervel configuration. A partial hand-maintained `buffer` group must add `batch_size` because the group replaces the package default. +4. In an application migration, add the two cleanup indexes described above, using your activity model's created-at column and inspecting existing names and duplicates. +5. Remove a standalone `log_name` index only after confirming its real name and that no application query needs a different index shape; the composite per-log cleanup index already has `log_name` as its left prefix. +6. On PostgreSQL, consider converting `attribute_changes` and `properties` from `json` to `jsonb` after reviewing locks, table size, and dependent indexes. MySQL and MariaDB already use their compatible JSON representation. + +For Spatie 4.x or older data, first complete Spatie's supported schema/data upgrade to 5.x. Older layouts can combine changes with properties and can contain historical batch columns; this package does not guess how to rewrite that application data. + +New dotted relation entries keep the configured key. Historical Spatie rows may contain the resolved PHP relation method spelling when configuration used a snake/camel alias. Keep configuration spelling aligned with the relation method when key continuity matters, or make reports understand both historical and new keys. + +Review custom models, actions, callbacks, and tests for these public differences: + +- names use `ActivityLog` / `activity-log`; +- `activity()` selects the default log name only for `null`, not empty string or `"0"`; +- automatic logging does not call `fresh()` unless `refreshBeforeLogging()` is enabled inside a transaction; +- dotted relation keys retain the configured spelling; +- buffering is coroutine-scoped, bounded, and transaction-aware; +- `setLogStatus()` is replaced by `enableLogging()`, `disableLogging()`, and `withoutLogging()`; +- Hypervel clears registered callbacks between tests. + + +## Security + +An activity log is sensitive application data. Store only the attribute and property values you intend to retain: + +- use `logOnly()` to select safe fields, then `logExcept()` and `default_except_attributes` to exclude passwords, tokens, secrets, encrypted payloads, payment details, and unnecessary personal data; +- redact or replace values in a custom action/global callback before persistence; +- apply authorization and tenant scopes to every activity query; +- escape descriptions and properties when rendering them; audit content can contain user input; +- choose retention periods from legal and operational requirements, then run cleanup consistently; +- protect database backups and replicas to the same standard as the primary audit table. + +`useAttributeRawValues()` can expose ciphertext or raw database encodings. It does not make a sensitive value safe to log. + + +## Testing + +Use `withoutLogging()` around setup work that should not create audit rows, then assert stored activities through the normal model: + +```php +use Hypervel\ActivityLog\Facades\ActivityLog; +use Hypervel\ActivityLog\Models\Activity; + +ActivityLog::withoutLogging(fn () => $this->seedReferenceData()); + +$invoice->markPaid(); + +$activity = Activity::query()->latest('id')->firstOrFail(); + +$this->assertSame('updated', $activity->event); +$this->assertSame('paid', $activity->attribute_changes['attributes']['status']); +``` + +Hypervel's PHPUnit extension clears `beforeLogging()` callbacks and logger macros after each test. Causer, logging status, and buffer state are isolated by each test's coroutine and application lifecycle. + +When buffering is enabled in a test, finish the request or job, or call `ActivityBuffer::finalizeCurrent()` after any application transaction commits, before asserting database rows. With `RefreshDatabase` or `DatabaseTransactions`, the buffer writes eligible rows inside the test’s wrapping transaction so its rollback removes them. + + +## Credits + +Hypervel Activity Log began as a port of [Spatie’s Laravel Activity Log](https://github.com/spatie/laravel-activitylog) and has been adapted for Hypervel’s coroutine runtime. diff --git a/src/docs/documentation.md b/src/docs/documentation.md index b4ea31d0f..7b4e3b5ac 100644 --- a/src/docs/documentation.md +++ b/src/docs/documentation.md @@ -103,6 +103,7 @@ - [Mocking](/docs/{{version}}/mocking) - [Static Analysis](/docs/{{version}}/static-analysis) - ## Packages + - [Activity Log](/docs/{{version}}/activity-log) - [API Client](/docs/{{version}}/api-client) - [Doctor](/docs/{{version}}/doctor) - [Fortify](/docs/{{version}}/fortify) diff --git a/src/foundation/src/Testing/DatabaseTransactionsManager.php b/src/foundation/src/Testing/DatabaseTransactionsManager.php index c9c7112db..dbcd81919 100644 --- a/src/foundation/src/Testing/DatabaseTransactionsManager.php +++ b/src/foundation/src/Testing/DatabaseTransactionsManager.php @@ -66,6 +66,17 @@ public function beginTransactions(DatabaseManager $database): void } } + /** + * Get the test wrapper enclosing the current transaction on a connection. + */ + public function wrappingTransactionFor(string $connection): ?DatabaseTransactionRecord + { + return $this->getPendingTransactions()->first( + fn (DatabaseTransactionRecord $transaction): bool => $transaction->connection === $connection + && in_array($transaction, $this->wrappingTransactions, true) + ); + } + /** * Get the transactions that are applicable to callbacks. * diff --git a/src/testing/src/PHPUnit/AfterEachTestSubscriber.php b/src/testing/src/PHPUnit/AfterEachTestSubscriber.php index fac8613dd..df49d2b28 100644 --- a/src/testing/src/PHPUnit/AfterEachTestSubscriber.php +++ b/src/testing/src/PHPUnit/AfterEachTestSubscriber.php @@ -358,6 +358,7 @@ protected function flushFrameworkState(): void $this->callIfLoaded(\Hypervel\WebSocketServer\Collector\FdCollector::class); $this->callIfLoaded(\Hypervel\WebSocketServer\Context::class); + $this->flushActivityLogState(); $this->flushAiState(); $this->flushDataState(); $this->flushDoctorState(); @@ -383,6 +384,15 @@ protected function flushFrameworkState(): void $this->flushWayfinderState(); } + /** + * Flush Activity Log state. + */ + protected function flushActivityLogState(): void + { + $this->callIfLoaded(\Hypervel\ActivityLog\Actions\LogActivityAction::class); + $this->callIfLoaded(\Hypervel\ActivityLog\Support\ActivityLogger::class, 'flushMacros'); + } + /** * Flush AI state. */ diff --git a/tests/ActivityLog/Actions/CleanActivityLogActionTest.php b/tests/ActivityLog/Actions/CleanActivityLogActionTest.php new file mode 100644 index 000000000..83672c269 --- /dev/null +++ b/tests/ActivityLog/Actions/CleanActivityLogActionTest.php @@ -0,0 +1,352 @@ +set('activity-log.clean_batch_size', 2); + + foreach (range(1, 5) as $index) { + Activity::query()->create([ + 'description' => "old activity {$index}", + 'created_at' => CarbonImmutable::now()->subDays(30 + $index), + ]); + } + + Activity::query()->create([ + 'description' => 'current activity', + 'created_at' => CarbonImmutable::now(), + ]); + + $connection = (new Activity)->getConnection(); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + // The replica has not received the activities. Every cleanup page must read the writer. + $replica = new PDO('sqlite::memory:'); + $replica->exec('create table activity_log (id integer, created_at text)'); + $previousReadPdo = $connection->getRawReadPdo(); + $connection->setReadPdo($replica); + + try { + $this->assertSame(0, Activity::query()->count()); + $deleted = $this->action()->execute(30); + $queries = $connection->getQueryLog(); + } finally { + $connection->setReadPdo($previousReadPdo); + $connection->disableQueryLog(); + $connection->flushQueryLog(); + } + + $selects = array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with( + strtolower($query['query']), + 'select "id" from "activity_log"', + ), + )); + $deletes = array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with( + strtolower($query['query']), + 'delete from "activity_log"', + ), + )); + + $this->assertSame(5, $deleted); + $this->assertCount(4, $selects); + $this->assertCount(3, $deletes); + $this->assertSame([2, 2, 1], array_map( + function (array $query): int { + $matched = preg_match( + '/"activity_log"\."id" in \(([^)]+)\)/', + strtolower($query['query']), + $matches, + ); + + $this->assertSame(1, $matched); + + return substr_count($matches[1], ',') + 1; + }, + $deletes, + )); + $this->assertSame(['current activity'], Activity::query()->pluck('description')->all()); + } + + public function testDeletesOnlyTheRequestedLog(): void + { + foreach (['target', 'target', 'other'] as $logName) { + Activity::query()->create([ + 'log_name' => $logName, + 'description' => "{$logName} activity", + 'created_at' => CarbonImmutable::now()->subDays(31), + ]); + } + + $this->assertSame(2, $this->action()->execute(30, 'target')); + $this->assertSame(['other'], Activity::query()->pluck('log_name')->all()); + } + + public function testKeepsActivitiesAtTheExactCutoff(): void + { + $cutoff = CarbonImmutable::now()->subDays(30); + + Activity::query()->create([ + 'description' => 'before cutoff', + 'created_at' => $cutoff->subSecond(), + ]); + Activity::query()->create([ + 'description' => 'at cutoff', + 'created_at' => $cutoff, + ]); + Activity::query()->create([ + 'description' => 'after cutoff', + 'created_at' => $cutoff->addSecond(), + ]); + + $this->assertSame(1, $this->action()->execute(30)); + $this->assertSame([ + 'at cutoff', + 'after cutoff', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + } + + public function testSerializesTheCutoffWithTheConfiguredActivityModel(): void + { + config()->set('activity-log.activity_model', UnixDateCleanActivity::class); + + UnixDateCleanActivity::query()->create([ + 'description' => 'old unix activity', + 'created_at' => CarbonImmutable::now()->subDays(31), + ]); + UnixDateCleanActivity::query()->create([ + 'description' => 'current unix activity', + 'created_at' => CarbonImmutable::now(), + ]); + + $this->assertSame(1, $this->action()->execute(30)); + $this->assertSame( + ['current unix activity'], + Activity::query()->pluck('description')->all(), + ); + } + + public function testUsesTheConfiguredCreatedAtColumn(): void + { + Schema::create('renamed_activity_log', static function (Blueprint $table): void { + $table->id(); + $table->string('log_name')->nullable(); + $table->text('description'); + $table->timestamp('logged_at')->nullable(); + }); + config()->set( + 'activity-log.activity_model', + RenamedCreatedAtCleanActivity::class, + ); + + try { + RenamedCreatedAtCleanActivity::query()->create([ + 'description' => 'old renamed activity', + 'logged_at' => CarbonImmutable::now()->subDays(31), + ]); + RenamedCreatedAtCleanActivity::query()->create([ + 'description' => 'current renamed activity', + 'logged_at' => CarbonImmutable::now(), + ]); + + $this->assertSame(1, $this->action()->execute(30)); + $this->assertSame( + ['current renamed activity'], + RenamedCreatedAtCleanActivity::query()->pluck('description')->all(), + ); + } finally { + Schema::dropIfExists('renamed_activity_log'); + } + } + + public function testKeylessActivitiesCanBeLoggedButCannotBeCleaned(): void + { + $model = new class extends Activity { + protected ?string $primaryKey = null; + + public bool $incrementing = false; + }; + config()->set('activity-log.activity_model', $model::class); + activity()->log('keyless activity'); + + $this->assertSame('keyless activity', Activity::query()->value('description')); + $this->expectException(InvalidConfiguration::class); + $this->expectExceptionMessage('Cleaning the activity log requires a primary key on [' . $model::class . '].'); + $this->action()->execute(30); + } + + public function testRejectsAnActivityModelWithoutACreatedAtColumn(): void + { + config()->set( + 'activity-log.activity_model', + CleanActivityWithoutCreatedAtColumn::class, + ); + + $this->expectException(InvalidConfiguration::class); + $this->expectExceptionMessage( + 'The configured activity model [' . CleanActivityWithoutCreatedAtColumn::class + . '] does not define a created-at column.', + ); + + $this->action()->execute(30); + } + + public function testRespectsActivityModelGlobalScopes(): void + { + Activity::query()->create([ + 'description' => 'visible old activity', + 'created_at' => CarbonImmutable::now()->subDays(31), + ]); + Activity::query()->create([ + 'description' => 'protected old activity', + 'created_at' => CarbonImmutable::now()->subDays(31), + ]); + config()->set('activity-log.activity_model', ScopedCleanActivity::class); + + $this->assertSame(1, $this->action()->execute(30)); + $this->assertSame( + ['protected old activity'], + Activity::query()->pluck('description')->all(), + ); + } + + public function testRechecksEligibilityBeforeDeletingASelectedRow(): void + { + config()->set('activity-log.clean_batch_size', 2); + $rowThatBecomesCurrent = Activity::query()->create([ + 'description' => 'becomes current', + 'created_at' => CarbonImmutable::now()->subDays(31), + ]); + Activity::query()->create([ + 'description' => 'remains old', + 'created_at' => CarbonImmutable::now()->subDays(31), + ]); + + $connection = (new Activity)->getConnection(); + $updated = false; + $connection->beforeExecuting(function (string $query) use ( + &$updated, + $rowThatBecomesCurrent, + ): void { + if ($updated || ! str_starts_with(strtolower($query), 'delete from "activity_log"')) { + return; + } + + $updated = true; + Activity::query() + ->whereKey($rowThatBecomesCurrent->getKey()) + ->update(['created_at' => CarbonImmutable::now()]); + }); + + try { + $deleted = $this->action()->execute(30); + } finally { + $connection->clearBeforeExecutingCallbacks(); + } + + $this->assertTrue($updated); + $this->assertSame(1, $deleted); + $this->assertSame(['becomes current'], Activity::query()->pluck('description')->all()); + } + + public function testRejectsANonPositiveRetentionPeriod(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The maximum age in days must be at least 1.'); + + $this->action()->execute(0); + } + + /** + * Resolve a fresh cleanup action. + */ + protected function action(): CleanActivityLogAction + { + return $this->app + ->make(ActivityLogConfiguration::class) + ->cleanActivityLogAction(); + } +} + +class ScopedCleanActivity extends Activity +{ + /** + * Register the cleanup visibility scope. + */ + protected static function booted(): void + { + static::addGlobalScope( + 'protected activity', + static fn (Builder $query): Builder => $query->where( + 'description', + '!=', + 'protected old activity', + ), + ); + } +} + +class UnixDateCleanActivity extends Activity +{ + protected ?string $dateFormat = 'U'; +} + +class RenamedCreatedAtCleanActivity extends Activity +{ + public const ?string CREATED_AT = 'logged_at'; + + public const ?string UPDATED_AT = null; + + protected ?string $table = 'renamed_activity_log'; +} + +class CleanActivityWithoutCreatedAtColumn extends Activity +{ + public const ?string CREATED_AT = null; + + public const ?string UPDATED_AT = null; + + public bool $timestamps = false; +} diff --git a/tests/ActivityLog/Actions/LogActivityActionTest.php b/tests/ActivityLog/Actions/LogActivityActionTest.php new file mode 100644 index 000000000..795a66700 --- /dev/null +++ b/tests/ActivityLog/Actions/LogActivityActionTest.php @@ -0,0 +1,180 @@ +steps[] = "subject:{$activity->description}:{$eventName}"; + $activity->setAttribute( + 'properties', + $activity->properties->put('subject_hook', true), + ); + } + }; + $subject->steps = $steps; + $subject->setAttribute('name', 'subject name'); + + $activity = new Activity; + $activity->setAttribute('event', 'created'); + $activity->setAttribute('attribute_changes', collect()); + $activity->setAttribute('properties', collect()); + $activity->subject()->associate($subject); + + LogActivityAction::beforeLogging(function (Activity $activity) use ($steps): void { + $steps[] = 'callback:' . ($activity->getProperty('subject_hook') ? 'after subject' : 'before subject'); + }); + + $action = new RecordingLogActivityAction( + $this->app->make(ActivityLogConfiguration::class), + $this->app, + $steps, + ); + + $result = $action->execute($activity, 'Activity for :subject.name'); + + $this->assertSame($activity, $result); + $this->assertSame([ + 'transform:Activity for subject name', + 'subject:Activity for subject name:created', + 'callback:after subject', + 'save', + ], $steps->getArrayCopy()); + } + + public function testImmediateFalseSaveFailsClosed(): void + { + $activity = new FalseSavingActivity; + $activity->setAttribute('attribute_changes', collect()); + $activity->setAttribute('properties', collect()); + + $this->expectException(CouldNotLogActivity::class); + $this->expectExceptionMessage('Could not persist the activity.'); + + $this->action()->execute($activity, 'not persisted'); + } + + public function testBuildsAFreshUnboundConfiguredAction(): void + { + config()->set('activity-log.actions.log_activity', ConfiguredLogActivityAction::class); + $configuration = $this->app->make(ActivityLogConfiguration::class); + + $first = $configuration->logActivityAction(); + $second = $configuration->logActivityAction(); + + $this->assertInstanceOf(ConfiguredLogActivityAction::class, $first); + $this->assertInstanceOf(ConfiguredLogActivityAction::class, $second); + $this->assertNotSame($first, $second); + } + + public function testHonorsAnExplicitConfiguredActionBinding(): void + { + config()->set('activity-log.actions.log_activity', ConfiguredLogActivityAction::class); + $instance = new ConfiguredLogActivityAction( + $this->app->make(ActivityLogConfiguration::class), + $this->app, + ); + $this->app->instance(ConfiguredLogActivityAction::class, $instance); + $configuration = $this->app->make(ActivityLogConfiguration::class); + + $this->assertSame($instance, $configuration->logActivityAction()); + $this->assertSame($instance, $configuration->logActivityAction()); + } + + public function testRejectsAnInvalidConfiguredActionBindingResult(): void + { + config()->set('activity-log.actions.log_activity', ConfiguredLogActivityAction::class); + $this->app->bind( + ConfiguredLogActivityAction::class, + static fn (): stdClass => new stdClass, + ); + + $this->expectException(InvalidConfiguration::class); + $this->expectExceptionMessage( + 'The container binding for [' . ConfiguredLogActivityAction::class + . '] must resolve to [' . LogActivityAction::class . ']; stdClass returned.', + ); + + $this->app + ->make(ActivityLogConfiguration::class) + ->logActivityAction(); + } + + /** + * Create the default logging action. + */ + protected function action(): LogActivityAction + { + return new LogActivityAction( + $this->app->make(ActivityLogConfiguration::class), + $this->app, + ); + } +} + +class RecordingLogActivityAction extends LogActivityAction +{ + public function __construct( + ActivityLogConfiguration $configuration, + Container $container, + protected ArrayObject $steps, + ) { + parent::__construct($configuration, $container); + } + + /** + * Record the change transformation step. + */ + protected function transformChanges(ActivityContract&Model $activity): void + { + $this->steps[] = 'transform:' . $activity->getAttribute('description'); + } + + /** + * Record the persistence step. + */ + protected function save(ActivityContract&Model $activity): void + { + $this->steps[] = 'save'; + } +} + +class FalseSavingActivity extends Activity +{ + /** + * Reject persistence. + */ + public function save(array $options = []): bool + { + return false; + } +} + +class ConfiguredLogActivityAction extends LogActivityAction +{ +} diff --git a/tests/ActivityLog/ActivityLogManagerTest.php b/tests/ActivityLog/ActivityLogManagerTest.php new file mode 100644 index 000000000..16f1e80a1 --- /dev/null +++ b/tests/ActivityLog/ActivityLogManagerTest.php @@ -0,0 +1,242 @@ +app->make(ActivityLogManager::class); + $configuration = $this->app->make(ActivityLogConfiguration::class); + + $this->assertSame($manager, $this->app->make(ActivityLogManager::class)); + $this->assertSame($manager, ActivityLog::getFacadeRoot()); + $this->assertSame( + $configuration, + $this->app->make(ActivityLogConfiguration::class), + ); + $this->assertNotSame($manager->logger(), $manager->logger()); + $this->assertNotSame(ActivityLog::logger(), ActivityLog::logger()); + } + + public function testHelperPreservesEmptyAndZeroLogNames(): void + { + activity()->log('default name'); + activity('')->log('empty name'); + activity('0')->log('zero name'); + + $this->assertSame([ + config('activity-log.default_log_name'), + '', + '0', + ], Activity::query()->orderBy('id')->pluck('log_name')->all()); + } + + public function testFacadeMacrosOperateOnFreshLoggers(): void + { + ActivityLog::macro( + 'marked', + function (string $marker): ActivityLogger { + return $this->withProperty('marker', $marker); + }, + ); + + $this->assertTrue(ActivityLog::hasMacro('marked')); + + ActivityLog::logger()->marked('first')->log('first activity'); + ActivityLog::logger()->marked('second')->log('second activity'); + + $activities = Activity::query()->orderBy('id')->get(); + + $this->assertSame('first', $activities[0]->getProperty('marker')); + $this->assertSame('second', $activities[1]->getProperty('marker')); + + ActivityLog::flushMacros(); + + $this->assertFalse(ActivityLog::hasMacro('marked')); + } + + public function testBootRegistrarsDoNotResolveScopedServicesOrLoggers(): void + { + $this->app->bind( + ActivityLogger::class, + static fn (): never => throw new RuntimeException('logger resolved'), + ); + $this->app->scoped( + CauserResolver::class, + static fn (): never => throw new RuntimeException('resolver resolved'), + ); + + ActivityLog::macro('registered_only', static fn (): null => null); + ActivityLog::beforeLogging(static function (): void { + }); + + $this->assertTrue(ActivityLog::hasMacro('registered_only')); + } + + public function testDefaultCauserIsVisibleToEveryLoggingHook(): void + { + $causer = User::query()->firstOrFail(); + $subject = new class extends Article { + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $activity->setAttribute( + 'properties', + $activity->properties->put( + 'subject_hook_causer', + $activity->causer?->getKey(), + ), + ); + } + }; + $this->app->make(CauserResolver::class)->setCauser($causer); + LogActivityAction::beforeLogging(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put( + 'global_callback_causer', + $activity->causer?->getKey(), + ), + ); + }); + + activity() + ->performedOn($subject) + ->tap(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put( + 'tap_causer', + $activity->causer?->getKey(), + ), + ); + }) + ->log('Causer :causer.name'); + + $activity = Activity::query()->firstOrFail(); + + $this->assertSame('Causer name 1', $activity->description); + $this->assertSame($causer->getKey(), $activity->getProperty('tap_causer')); + $this->assertSame($causer->getKey(), $activity->getProperty('subject_hook_causer')); + $this->assertSame($causer->getKey(), $activity->getProperty('global_callback_causer')); + } + + public function testAnonymousCauserDissociatesAnAlreadyResolvedDefault(): void + { + $causer = User::query()->firstOrFail(); + $this->app->make(CauserResolver::class)->setCauser($causer); + + activity() + ->tap(function (Activity $activity) use ($causer): void { + $this->assertSame($causer->getKey(), $activity->causer?->getKey()); + }) + ->causedByAnonymous() + ->log('Causer :causer.name'); + + $activity = Activity::query()->firstOrFail(); + + $this->assertNull($activity->causer_id); + $this->assertNull($activity->causer_type); + $this->assertNull($activity->causer); + $this->assertSame('Causer :causer.name', $activity->description); + } + + public function testAvoidsDefaultCauserResolutionForExplicitAnonymousAndDisabledLogs(): void + { + $configuration = $this->app->make(ActivityLogConfiguration::class); + $status = new ActivityLogStatus($configuration); + $resolver = Double::for(CauserResolver::class)->strict(); + $explicitCauser = Article::query()->firstOrFail(); + $resolver->expects('resolve') + ->with(Argument::same($explicitCauser)) + ->returns($explicitCauser); + + (new ActivityLogger($configuration, $status, $resolver)) + ->causedBy($explicitCauser) + ->log('explicit'); + (new ActivityLogger($configuration, $status, $resolver)) + ->causedByAnonymous() + ->log('anonymous'); + (new ActivityLogger($configuration, $status, $resolver)) + ->disableLogging() + ->log('disabled'); + + $this->assertSame([ + 'explicit', + 'anonymous', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + } + + public function testBuilderResetsAfterADisabledLog(): void + { + $logger = activity('transient log') + ->event('transient event') + ->withProperty('transient', true) + ->disableLogging(); + + $this->assertNull($logger->log('disabled')); + + $activity = $logger + ->enableLogging() + ->log('enabled after reset'); + + $this->assertNotNull($activity); + $this->assertSame(config('activity-log.default_log_name'), $activity->log_name); + $this->assertNull($activity->event); + $this->assertSame([], $activity->properties->all()); + } + + public function testBuilderResetsAfterAFailedLog(): void + { + $rejectNextSave = true; + Activity::saving(static function () use (&$rejectNextSave): ?bool { + if (! $rejectNextSave) { + return null; + } + + $rejectNextSave = false; + + return false; + }); + $logger = activity('transient log') + ->event('transient event') + ->withProperty('transient', true); + + try { + $logger->log('rejected'); + $this->fail('Expected the first activity save to be rejected.'); + } catch (CouldNotLogActivity $exception) { + $this->assertSame('Could not persist the activity.', $exception->getMessage()); + } + + $activity = $logger->log('persisted after failure'); + + $this->assertNotNull($activity); + $this->assertSame(config('activity-log.default_log_name'), $activity->log_name); + $this->assertNull($activity->event); + $this->assertSame([], $activity->properties->all()); + } +} diff --git a/tests/ActivityLog/ActivityLogServiceProviderTest.php b/tests/ActivityLog/ActivityLogServiceProviderTest.php new file mode 100644 index 000000000..bb42dccc2 --- /dev/null +++ b/tests/ActivityLog/ActivityLogServiceProviderTest.php @@ -0,0 +1,169 @@ + $enabled]); + } + + $event = array_find($this->app->make(Schedule::class)->events(), static fn (Event $event): bool => $event->command === 'activity-log:clean --force'); + + if ($expression === null) { + $this->assertNull($event); + } else { + $this->assertSame($expression, $event?->expression); + $this->assertTrue($event->runInBackground); + $this->assertTrue($event->withoutOverlapping); + $this->assertTrue($event->onOneServer); + } + } + + public function testRegistersExpectedDefaultsAndServiceLifetimes(): void + { + $config = $this->app->make('config'); + + $this->assertTrue($config->boolean('activity-log.enabled')); + $this->assertSame(365, $config->integer('activity-log.clean_after_days')); + $this->assertSame(1000, $config->integer('activity-log.clean_batch_size')); + $this->assertSame(500, $config->integer('activity-log.buffer.batch_size')); + + $this->assertNotSame( + $this->app->make(ActivityLogger::class), + $this->app->make(ActivityLogger::class), + ); + $this->assertSame( + $this->app->make(ActivityLogStatus::class), + $this->app->make(ActivityLogStatus::class), + ); + $this->assertSame( + $this->app->make(CauserResolver::class), + $this->app->make(CauserResolver::class), + ); + $this->assertSame( + $this->app->make(ActivityBuffer::class), + $this->app->make(ActivityBuffer::class), + ); + $this->assertSame( + $this->app->make(ActivityLogManager::class), + $this->app->make(ActivityLogManager::class), + ); + $this->assertSame( + $this->app->make(ActivityLogConfiguration::class), + $this->app->make(ActivityLogConfiguration::class), + ); + } + + public function testDeclaresProviderDiscoveryInBothManifests(): void + { + $root = dirname(__DIR__, 2); + $rootManifest = json_decode( + file_get_contents($root . '/composer.json'), + true, + flags: JSON_THROW_ON_ERROR, + ); + $splitManifest = json_decode( + file_get_contents($root . '/src/activity-log/composer.json'), + true, + flags: JSON_THROW_ON_ERROR, + ); + + foreach ([$rootManifest, $splitManifest] as $manifest) { + $this->assertContains( + ActivityLogServiceProvider::class, + $manifest['extra']['hypervel']['providers'], + ); + } + } + + public function testRegistersConfigurationAndMigrationPublishGroups(): void + { + $root = dirname(__DIR__, 2); + + $this->assertSame([ + $root . '/src/activity-log/config/activity-log.php' => config_path('activity-log.php'), + ], ServiceProvider::pathsToPublish( + ActivityLogServiceProvider::class, + 'activity-log-config', + )); + $this->assertSame([ + $root . '/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php' => database_path( + 'migrations/2026_08_04_000000_create_activity_log_table.php', + ), + ], ServiceProvider::pathsToPublish( + ActivityLogServiceProvider::class, + 'activity-log-migrations', + )); + } + + public function testRegistersTheCleanCommand(): void + { + $commands = $this->app->make(Kernel::class)->all(); + + $this->assertInstanceOf( + CleanActivityLogCommand::class, + $commands['activity-log:clean'], + ); + } + + public function testRegistersOnePassiveJobObserver(): void + { + $events = $this->app->make('events'); + + $this->assertInstanceOf(Dispatcher::class, $events); + $this->assertCount(1, $events->getObservers(JobAttempted::class)); + } + + public function testEmptyLifecycleBoundariesDoNotResolveABuffer(): void + { + $resolutions = 0; + $this->app->scoped( + ActivityBuffer::class, + static function () use (&$resolutions): never { + ++$resolutions; + + throw new RuntimeException('buffer resolved'); + }, + ); + + $this->assertNull(ActivityBuffer::current()); + + $this->app->terminate(); + $this->app->make('events')->dispatch(new JobAttempted( + 'test', + Double::for(Job::class)->strict(), + )); + + $this->assertSame(0, $resolutions); + $this->assertNull(ActivityBuffer::current()); + } +} diff --git a/tests/ActivityLog/Casts/IntervalCasts.php b/tests/ActivityLog/Casts/IntervalCasts.php new file mode 100644 index 000000000..c6724ea72 --- /dev/null +++ b/tests/ActivityLog/Casts/IntervalCasts.php @@ -0,0 +1,43 @@ + */ +class IntervalCasts implements CastsAttributes +{ + /** + * Transform an interval from its stored value. + * + * @param array $attributes + */ + public function get(Model $model, string $key, mixed $value, array $attributes): ?string + { + if ($value === null || $value === '') { + return null; + } + + return (string) CarbonInterval::create($value); + } + + /** + * Transform an interval to its stored value. + * + * @param array $attributes + */ + public function set(Model $model, string $key, mixed $value, array $attributes): ?string + { + if ($value === null || $value === '') { + return null; + } + + $value = is_string($value) ? CarbonInterval::create($value) : $value; + + return CarbonInterval::getDateIntervalSpec($value); + } +} diff --git a/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php b/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php new file mode 100644 index 000000000..659646200 --- /dev/null +++ b/tests/ActivityLog/Commands/CleanActivityLogCommandTest.php @@ -0,0 +1,157 @@ +set('activity-log.clean_after_days', 31); + } + + /** + * Reset the test clock and fixture database. + */ + protected function tearDownInCoroutine(): void + { + try { + CarbonImmutable::setTestNow(null); + } finally { + parent::tearDownInCoroutine(); + } + } + + public function testCanCleanTheActivityLog(): void + { + foreach (range(1, 60) as $index) { + Activity::create([ + 'description' => "item {$index}", + 'created_at' => CarbonImmutable::now()->subDays($index)->startOfDay(), + ]); + } + + $this->assertCount(60, Activity::all()); + + Artisan::call('activity-log:clean'); + + $this->assertCount(31, Activity::all()); + + $cutOffDate = CarbonImmutable::now()->subDays(31)->format('Y-m-d H:i:s'); + + $this->assertCount(0, Activity::where('created_at', '<', $cutOffDate)->get()); + } + + public function testCanAcceptDaysAsOptionToOverrideConfigSetting(): void + { + foreach (range(1, 60) as $index) { + Activity::create([ + 'description' => "item {$index}", + 'created_at' => CarbonImmutable::now()->subDays($index)->startOfDay(), + ]); + } + + $this->assertCount(60, Activity::all()); + + Artisan::call('activity-log:clean', ['--days' => 7]); + + $this->assertCount(7, Activity::all()); + + $cutOffDate = CarbonImmutable::now()->subDays(7)->format('Y-m-d H:i:s'); + + $this->assertCount(0, Activity::where('created_at', '<', $cutOffDate)->get()); + } + + #[DataProvider('invalidDays')] + public function testDoesNotCleanTheActivityLogWhenDaysConfigValueIsInvalid(mixed $days): void + { + config()->set('activity-log.clean_after_days', $days); + + foreach (range(1, 60) as $index) { + Activity::create([ + 'description' => "item {$index}", + 'created_at' => CarbonImmutable::now()->subDays($index)->startOfDay(), + ]); + } + + $this->assertCount(60, Activity::all()); + + $exitCode = Artisan::call('activity-log:clean'); + + $this->assertSame(1, $exitCode); + $this->assertStringContainsString('activity-log.clean_after_days', Artisan::output()); + $this->assertCount(60, Activity::all()); + } + + public function testCanCleanOnlyASpecificLog(): void + { + foreach (range(1, 60) as $index) { + Activity::create([ + 'log_name' => 'my-log', + 'description' => "item {$index}", + 'created_at' => CarbonImmutable::now()->subDays($index)->startOfDay(), + ]); + } + + foreach (range(1, 60) as $index) { + Activity::create([ + 'log_name' => 'other-log', + 'description' => "item {$index}", + 'created_at' => CarbonImmutable::now()->subDays($index)->startOfDay(), + ]); + } + + $this->assertCount(120, Activity::all()); + + Artisan::call('activity-log:clean', ['log' => 'my-log']); + + $this->assertSame(31, Activity::where('log_name', 'my-log')->count()); + $this->assertSame(60, Activity::where('log_name', 'other-log')->count()); + } + + #[DataProvider('invalidDays')] + public function testDoesNotCleanTheActivityLogWhenDaysOptionValueIsInvalid(mixed $days): void + { + foreach (range(1, 60) as $index) { + Activity::create([ + 'description' => "item {$index}", + 'created_at' => CarbonImmutable::now()->subDays($index)->startOfDay(), + ]); + } + + $this->assertCount(60, Activity::all()); + + $exitCode = Artisan::call('activity-log:clean', ['--days' => $days]); + + $this->assertSame(1, $exitCode); + $this->assertCount(60, Activity::all()); + } + + /** + * Provide invalid retention values. + * + * @return array + */ + public static function invalidDays(): array + { + return [ + 'boolean' => [false], + 'non-numeric string' => ['abc'], + 'fraction' => ['7.5'], + 'empty string' => [''], + ]; + } +} diff --git a/tests/ActivityLog/Concurrency/ActivityLogIsolationTest.php b/tests/ActivityLog/Concurrency/ActivityLogIsolationTest.php new file mode 100644 index 000000000..5581d7193 --- /dev/null +++ b/tests/ActivityLog/Concurrency/ActivityLogIsolationTest.php @@ -0,0 +1,107 @@ +firstOrFail(); + $secondCauser = User::query()->findOrFail(2); + + $results = parallel([ + 'first' => function () use ($firstCauser): array { + $status = $this->app->make(ActivityLogStatus::class); + $resolver = $this->app->make(CauserResolver::class); + $buffer = $this->app->make(ActivityBuffer::class); + $status->disable(); + $resolver->setCauser($firstCauser); + usleep(1000); + + return [ + 'status_id' => spl_object_id($status), + 'resolver_id' => spl_object_id($resolver), + 'buffer_id' => spl_object_id($buffer), + 'disabled' => $status->disabled(), + 'causer' => $resolver->resolve()?->getKey(), + ]; + }, + 'second' => function () use ($secondCauser): array { + $status = $this->app->make(ActivityLogStatus::class); + $resolver = $this->app->make(CauserResolver::class); + $buffer = $this->app->make(ActivityBuffer::class); + $status->enable(); + $resolver->setCauser($secondCauser); + usleep(1000); + + return [ + 'status_id' => spl_object_id($status), + 'resolver_id' => spl_object_id($resolver), + 'buffer_id' => spl_object_id($buffer), + 'disabled' => $status->disabled(), + 'causer' => $resolver->resolve()?->getKey(), + ]; + }, + ]); + + $this->assertNotSame($results['first']['status_id'], $results['second']['status_id']); + $this->assertNotSame($results['first']['resolver_id'], $results['second']['resolver_id']); + $this->assertNotSame($results['first']['buffer_id'], $results['second']['buffer_id']); + $this->assertTrue($results['first']['disabled']); + $this->assertFalse($results['second']['disabled']); + $this->assertSame($firstCauser->getKey(), $results['first']['causer']); + $this->assertSame($secondCauser->getKey(), $results['second']['causer']); + $this->assertNull(ActivityBuffer::current()); + $this->assertFalse($this->app->make(ActivityLogStatus::class)->disabled()); + $this->assertNull($this->app->make(CauserResolver::class)->resolve()); + } + + public function testCopiedContextSharesCauserAndStatusButFinalizesItsOwnBuffer(): void + { + $causer = User::query()->firstOrFail(); + $status = $this->app->make(ActivityLogStatus::class); + $resolver = $this->app->make(CauserResolver::class); + $buffer = $this->app->make(ActivityBuffer::class); + config(['activity-log.buffer.enabled' => true]); + activity()->log('parent'); + $status->disable(); + $resolver->setCauser($causer); + + $result = parallel([ + 'child' => function (): array { + activity()->enableLogging()->log('child'); + activity()->disableLogging(); + $status = $this->app->make(ActivityLogStatus::class); + $resolver = $this->app->make(CauserResolver::class); + $buffer = $this->app->make(ActivityBuffer::class); + + return [ + 'status_id' => spl_object_id($status), + 'resolver_id' => spl_object_id($resolver), + 'buffer_id' => spl_object_id($buffer), + 'disabled' => $status->disabled(), + 'causer' => $resolver->resolve()?->getKey(), + ]; + }, + ], copyContext: true)['child']; + + $this->assertSame(spl_object_id($status), $result['status_id']); + $this->assertSame(spl_object_id($resolver), $result['resolver_id']); + $this->assertNotSame(spl_object_id($buffer), $result['buffer_id']); + $this->assertSame(['child'], Activity::query()->pluck('description')->all()); + $this->assertSame(1, $buffer->count()); + $this->assertTrue($result['disabled']); + $this->assertSame($causer->getKey(), $result['causer']); + } +} diff --git a/tests/ActivityLog/Concurrency/ActivityLogPooledPersistenceTest.php b/tests/ActivityLog/Concurrency/ActivityLogPooledPersistenceTest.php new file mode 100644 index 000000000..4182bf6b0 --- /dev/null +++ b/tests/ActivityLog/Concurrency/ActivityLogPooledPersistenceTest.php @@ -0,0 +1,151 @@ +deleteDirectory(static::$databaseDirectory); + $filesystem->ensureDirectoryExists(static::$databaseDirectory); + + static::$databasePath = static::$databaseDirectory . '/database.sqlite'; + touch(static::$databasePath); + } + + public static function tearDownAfterClass(): void + { + (new Filesystem)->deleteDirectory(static::$databaseDirectory); + + parent::tearDownAfterClass(); + } + + /** + * Define a file-backed pooled database for concurrent persistence. + */ + protected function defineEnvironment(Application $app): void + { + parent::defineEnvironment($app); + + $app->make('config')->set('database.connections.sqlite', [ + 'driver' => 'sqlite', + 'database' => static::$databasePath, + 'busy_timeout' => 5000, + 'pool' => [ + 'testing_enabled' => true, + 'min_retained_connections' => 1, + 'max_connections' => 3, + 'heartbeat_interval' => null, + ], + ]); + } + + public function testWriteAliasRollbackDiscardsBufferedActivities(): void + { + config(['activity-log.buffer.enabled' => true]); + + DB::usingConnection('sqlite::write', function (): void { + $connection = (new Activity)->getConnection(); + $connection->beginTransaction(); + + try { + activity()->log('rolled back'); + } finally { + $connection->rollBack(); + } + }); + + ActivityBuffer::finalizeCurrent(); + $this->assertSame(0, Activity::query()->count()); + } + + public function testSiblingBuffersPersistThroughTheirBorrowedConnections(): void + { + $firstQueries = new ArrayObject; + $secondQueries = new ArrayObject; + + $results = parallel([ + 'first' => fn (): array => $this->bufferInCurrentCoroutine( + 'first coroutine', + $firstQueries, + ), + 'second' => fn (): array => $this->bufferInCurrentCoroutine( + 'second coroutine', + $secondQueries, + ), + ]); + + $this->assertNotSame($results['first']['buffer_id'], $results['second']['buffer_id']); + $this->assertSame(1, $results['first']['count']); + $this->assertSame(1, $results['second']['count']); + $this->assertActivityInsertWasObserved($firstQueries); + $this->assertActivityInsertWasObserved($secondQueries); + $this->assertSame([ + 'first coroutine', + 'second coroutine', + ], Activity::query()->orderBy('description')->pluck('description')->all()); + } + + /** + * Add one row and retain its connection query log through finalization. + * + * @return array{buffer_id: int, count: int} + */ + protected function bufferInCurrentCoroutine( + string $description, + ArrayObject $queries, + ): array { + $configuration = $this->app->make(ActivityLogConfiguration::class); + $activity = $configuration->activityModelInstance(); + $connection = $activity->getConnection(); + $connection->beforeExecuting(static function (string $query) use ($queries): void { + $queries[] = $query; + }); + + $activity->setAttribute('description', $description); + $buffer = $this->app->make(ActivityBuffer::class); + $buffer->add($activity); + usleep(1000); + + return [ + 'buffer_id' => spl_object_id($buffer), + 'count' => $buffer->count(), + ]; + } + + /** + * Assert finalization inserted into the activity table before pool release. + */ + protected function assertActivityInsertWasObserved(ArrayObject $queries): void + { + $this->assertCount(1, $queries); + $this->assertStringStartsWith( + 'insert into "activity_log"', + strtolower((string) $queries[0]), + ); + } +} diff --git a/tests/ActivityLog/Database/ActivityLogMigrationTest.php b/tests/ActivityLog/Database/ActivityLogMigrationTest.php new file mode 100644 index 000000000..eac8c756f --- /dev/null +++ b/tests/ActivityLog/Database/ActivityLogMigrationTest.php @@ -0,0 +1,125 @@ +migration()->up(); + + $this->assertSame([ + 'id', + 'log_name', + 'description', + 'subject_type', + 'subject_id', + 'event', + 'causer_type', + 'causer_id', + 'attribute_changes', + 'properties', + 'created_at', + 'updated_at', + ], Schema::getColumnListing('activity_log')); + + $columns = []; + + foreach (Schema::getColumns('activity_log') as $column) { + $columns[$column['name']] = $column; + } + + $this->assertSame('integer', $columns['id']['type_name']); + $this->assertFalse($columns['description']['nullable']); + $this->assertTrue($columns['log_name']['nullable']); + $this->assertTrue($columns['subject_type']['nullable']); + $this->assertTrue($columns['subject_id']['nullable']); + $this->assertTrue($columns['event']['nullable']); + $this->assertTrue($columns['causer_type']['nullable']); + $this->assertTrue($columns['causer_id']['nullable']); + $this->assertSame('text', $columns['attribute_changes']['type_name']); + $this->assertSame('text', $columns['properties']['type_name']); + + $indexes = []; + + foreach (Schema::getIndexes('activity_log') as $index) { + if (! $index['primary']) { + $indexes[$index['name']] = $index['columns']; + } + } + + ksort($indexes); + + $this->assertSame([ + 'activity_log_causer' => ['causer_type', 'causer_id'], + 'activity_log_created_at_id_index' => ['created_at', 'id'], + 'activity_log_name_created_at_id_index' => ['log_name', 'created_at', 'id'], + 'activity_log_subject' => ['subject_type', 'subject_id'], + ], $indexes); + } + + #[DataProvider('morphKeyTypes')] + public function testMigrationUsesConfiguredMorphKeyType(string $morphKeyType, string $columnType): void + { + SchemaBuilder::defaultMorphKeyType($morphKeyType); + + $this->migration()->up(); + + $this->assertSame($columnType, Schema::getColumnType('activity_log', 'subject_id')); + $this->assertSame($columnType, Schema::getColumnType('activity_log', 'causer_id')); + } + + /** + * Provide supported morph key types and their SQLite column types. + * + * @return array + */ + public static function morphKeyTypes(): array + { + return [ + 'integer' => ['int', 'integer'], + 'UUID' => ['uuid', 'varchar'], + 'ULID' => ['ulid', 'varchar'], + ]; + } + + public function testMigrationCanBeReversed(): void + { + $migration = $this->migration(); + + $migration->up(); + + $this->assertTrue(Schema::hasTable('activity_log')); + + $migration->down(); + + $this->assertFalse(Schema::hasTable('activity_log')); + } + + /** + * Load the publish-only activity log migration. + */ + protected function migration(): Migration + { + return require dirname(__DIR__, 3) + . '/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php'; + } +} diff --git a/tests/ActivityLog/Enums/IntBackedEnum.php b/tests/ActivityLog/Enums/IntBackedEnum.php new file mode 100644 index 000000000..0bee23992 --- /dev/null +++ b/tests/ActivityLog/Enums/IntBackedEnum.php @@ -0,0 +1,11 @@ + + */ + protected function casts(): array + { + return [ + 'attribute_changes' => 'collection', + 'properties' => 'collection', + ]; + } + + /** + * Get the activity subject. + * + * @return MorphTo + */ + public function subject(): MorphTo + { + $relation = $this->morphTo(); + + if (Container::getInstance() + ->make(ActivityLogConfiguration::class) + ->includeSoftDeletedSubjects()) { + $relation->getQuery()->withoutGlobalScope(SoftDeletingScope::class); + } + + return $relation; + } + + /** + * Get the activity causer. + * + * @return MorphTo + */ + public function causer(): MorphTo + { + return $this->morphTo(); + } + + /** + * Get an activity property. + */ + public function getProperty(string $propertyName, mixed $defaultValue = null): mixed + { + $properties = $this->getAttribute('properties'); + + return Arr::get($properties?->toArray() ?? [], $propertyName, $defaultValue); + } + + /** + * Scope activities to the given log names. + * + * @param array|string ...$logNames + */ + #[Scope] + protected function inLog(Builder $query, string|array ...$logNames): void + { + $names = []; + + foreach ($logNames as $value) { + array_push($names, ...(array) $value); + } + + $query->whereIn('log_name', $names); + } + + /** + * Scope activities to the given causer. + */ + #[Scope] + protected function causedBy(Builder $query, Model $causer): void + { + $query + ->where('causer_type', $causer->getMorphClass()) + ->where('causer_id', $causer->getKey()); + } + + /** + * Scope activities to the given subject. + */ + #[Scope] + protected function forSubject(Builder $query, Model $subject): void + { + $query + ->where('subject_type', $subject->getMorphClass()) + ->where('subject_id', $subject->getKey()); + } + + /** + * Scope activities to the given event. + */ + #[Scope] + protected function forEvent(Builder $query, string|ActivityEvent $event): void + { + $query->where('event', $event instanceof ActivityEvent ? $event->value : $event); + } + + /** + * Get the custom property attribute. + */ + public function getCustomPropertyAttribute(): mixed + { + return $this->getAttribute('attribute_changes'); + } +} diff --git a/tests/ActivityLog/Models/ActivityModelTest.php b/tests/ActivityLog/Models/ActivityModelTest.php new file mode 100644 index 000000000..f642e82b4 --- /dev/null +++ b/tests/ActivityLog/Models/ActivityModelTest.php @@ -0,0 +1,155 @@ +log('hello everybody'); + } + } + + public function testProvidesAScopeToGetActivitiesFromASpecificLog(): void + { + $activityInLog3 = Activity::inLog('log3')->get(); + + $this->assertCount(1, $activityInLog3); + $this->assertSame('log3', $activityInLog3->first()->log_name); + } + + public function testProvidesAScopeToGetLogItemsFromMultipleLogs(): void + { + $activities = Activity::inLog('log2', 'log4')->orderBy('log_name')->get(); + + $this->assertCount(2, $activities); + $this->assertSame('log2', $activities->first()->log_name); + $this->assertSame('log4', $activities->last()->log_name); + } + + public function testProvidesAScopeToGetLogItemsFromMultipleLogsUsingAnArray(): void + { + $activities = Activity::inLog(['log1', 'log2'])->orderBy('log_name')->get(); + + $this->assertCount(2, $activities); + $this->assertSame('log1', $activities->first()->log_name); + $this->assertSame('log2', $activities->last()->log_name); + } + + public function testProvidesAScopeToGetLogItemsForASpecificCauser(): void + { + $subject = Article::firstOrFail(); + $causer = User::firstOrFail(); + + activity()->on($subject)->by($causer)->log('Foo'); + activity()->on($subject)->by(User::create([ + 'name' => 'Another User', + ]))->log('Bar'); + + $activities = Activity::causedBy($causer)->get(); + + $this->assertCount(1, $activities); + $this->assertSame($causer->getKey(), $activities->first()->causer_id); + $this->assertSame($causer::class, $activities->first()->causer_type); + $this->assertSame('Foo', $activities->first()->description); + } + + public function testProvidesAScopeToGetLogItemsForASpecificEvent(): void + { + $subject = Article::firstOrFail(); + + activity() + ->on($subject) + ->event('create') + ->log('Foo'); + + $activities = Activity::forEvent('create')->get(); + + $this->assertCount(1, $activities); + $this->assertSame('create', $activities->first()->event); + } + + public function testProvidesAScopeToGetLogItemsForASpecificSubject(): void + { + $subject = Article::firstOrFail(); + $causer = User::firstOrFail(); + + activity()->on($subject)->by($causer)->log('Foo'); + activity()->on(Article::create([ + 'name' => 'Another article', + ]))->by($causer)->log('Bar'); + + $activities = Activity::forSubject($subject)->get(); + + $this->assertCount(1, $activities); + $this->assertSame($subject->getKey(), $activities->first()->subject_id); + $this->assertSame($subject::class, $activities->first()->subject_type); + $this->assertSame('Foo', $activities->first()->description); + } + + public function testProvidesAScopeToGetLogItemsForASpecificMorphMappedCauser(): void + { + Relation::morphMap([ + 'articles' => Article::class, + 'users' => User::class, + ]); + + try { + $subject = Article::firstOrFail(); + $causer = User::firstOrFail(); + + activity()->on($subject)->by($causer)->log('Foo'); + activity()->on($subject)->by(User::create([ + 'name' => 'Another User', + ]))->log('Bar'); + + $activities = Activity::causedBy($causer)->get(); + + $this->assertCount(1, $activities); + $this->assertSame($causer->getKey(), $activities->first()->causer_id); + $this->assertSame('users', $activities->first()->causer_type); + $this->assertSame('Foo', $activities->first()->description); + } finally { + Relation::morphMap([], false); + } + } + + public function testProvidesAScopeToGetLogItemsForASpecificMorphMappedSubject(): void + { + Relation::morphMap([ + 'articles' => Article::class, + 'users' => User::class, + ]); + + try { + $subject = Article::firstOrFail(); + $causer = User::firstOrFail(); + + activity()->on($subject)->by($causer)->log('Foo'); + activity()->on(Article::create([ + 'name' => 'Another article', + ]))->by($causer)->log('Bar'); + + $activities = Activity::forSubject($subject)->get(); + + $this->assertCount(1, $activities); + $this->assertSame($subject->getKey(), $activities->first()->subject_id); + $this->assertSame('articles', $activities->first()->subject_type); + $this->assertSame('Foo', $activities->first()->description); + } finally { + Relation::morphMap([], false); + } + } +} diff --git a/tests/ActivityLog/Models/AnotherInvalidActivity.php b/tests/ActivityLog/Models/AnotherInvalidActivity.php new file mode 100644 index 000000000..2d363205f --- /dev/null +++ b/tests/ActivityLog/Models/AnotherInvalidActivity.php @@ -0,0 +1,48 @@ + 'collection', + ]; + + /** + * Get the activity subject. + */ + public function subject(): MorphTo + { + if (config()->boolean('activity-log.include_soft_deleted_subjects')) { + return $this->morphTo()->withTrashed(); + } + + return $this->morphTo(); + } + + /** + * Get the activity causer. + */ + public function causer(): MorphTo + { + return $this->morphTo(); + } + + /** + * Get an activity property. + */ + public function getProperty(string $propertyName, mixed $defaultValue = null): mixed + { + return Arr::get($this->properties->toArray(), $propertyName, $defaultValue); + } +} diff --git a/tests/ActivityLog/Models/Article.php b/tests/ActivityLog/Models/Article.php new file mode 100644 index 000000000..7269b577c --- /dev/null +++ b/tests/ActivityLog/Models/Article.php @@ -0,0 +1,37 @@ + + */ + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } + + /** + * Get the owner name attribute. + */ + public function getOwnerNameAttribute(): ?string + { + return $this->user?->name; + } +} diff --git a/tests/ActivityLog/Models/ArticleWithLogDescriptionClosure.php b/tests/ActivityLog/Models/ArticleWithLogDescriptionClosure.php new file mode 100644 index 000000000..f9fcfff7f --- /dev/null +++ b/tests/ActivityLog/Models/ArticleWithLogDescriptionClosure.php @@ -0,0 +1,24 @@ +setDescriptionForEvent( + static fn (string $eventName): string => $eventName, + ); + } +} diff --git a/tests/ActivityLog/Models/CustomActivityModelTest.php b/tests/ActivityLog/Models/CustomActivityModelTest.php new file mode 100644 index 000000000..bb64d2155 --- /dev/null +++ b/tests/ActivityLog/Models/CustomActivityModelTest.php @@ -0,0 +1,79 @@ +set('activity-log.activity_model', Activity::class); + + $activity = activity()->log($this->activityDescription); + + $this->assertNotNull($activity); + $this->assertSame($this->activityDescription, $activity->description); + $this->assertInstanceOf(Activity::class, $activity); + } + + public function testRejectsANullModelConfiguration(): void + { + config()->set('activity-log.activity_model', null); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Configuration value for key [activity-log.activity_model] must be a string, NULL given.', + ); + + activity()->log($this->activityDescription); + } + + public function testThrowsAnExceptionWhenModelDoesNotImplementActivity(): void + { + config()->set('activity-log.activity_model', InvalidActivity::class); + + $this->expectException(InvalidConfiguration::class); + + activity()->log($this->activityDescription); + } + + public function testThrowsAnExceptionWhenModelDoesNotExtendModel(): void + { + config()->set('activity-log.activity_model', AnotherInvalidActivity::class); + + $this->expectException(InvalidConfiguration::class); + + activity()->log($this->activityDescription); + } + + public function testStoresChangesAndPropertiesSeparately(): void + { + config()->set('activity-log.activity_model', Activity::class); + + $changes = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => null, + ], + ]; + + $properties = ['key' => 'value']; + + $activity = activity() + ->withChanges($changes) + ->withProperties($properties) + ->log($this->activityDescription); + + $this->assertNotNull($activity); + $this->assertSame($changes, $activity->attribute_changes->toArray()); + $this->assertSame($properties, $activity->properties->toArray()); + $this->assertSame($changes, $activity->custom_property->toArray()); + } +} diff --git a/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php b/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php new file mode 100644 index 000000000..ad1bccd0b --- /dev/null +++ b/tests/ActivityLog/Models/CustomDatabaseConnectionActivityModelTest.php @@ -0,0 +1,79 @@ +migrateActivityLogTable(); + }, + ); + } + + /** + * Remove the custom connection's activity table. + */ + protected function tearDownInCoroutine(): void + { + try { + DB::usingConnection( + 'custom_connection_name', + static function (): void { + Schema::dropIfExists('activity_log'); + }, + ); + } finally { + parent::tearDownInCoroutine(); + } + } + + public function testUsesTheCustomConnectionForImmediateWrites(): void + { + config()->set( + 'activity-log.activity_model', + CustomDatabaseConnectionOnActivityModel::class, + ); + + $activity = activity()->log('Custom connection'); + + $this->assertInstanceOf(CustomDatabaseConnectionOnActivityModel::class, $activity); + $this->assertSame('custom_connection_name', $activity->getConnectionName()); + $this->assertSame(1, CustomDatabaseConnectionOnActivityModel::query()->count()); + $this->assertSame(0, DefaultActivity::query()->count()); + } + + public function testUsesTheCustomConnectionForBufferedWrites(): void + { + config()->set([ + 'activity-log.activity_model' => CustomDatabaseConnectionOnActivityModel::class, + 'activity-log.buffer.enabled' => true, + ]); + + $activity = activity()->log('Buffered custom connection'); + + $this->assertInstanceOf(CustomDatabaseConnectionOnActivityModel::class, $activity); + $this->assertSame(0, CustomDatabaseConnectionOnActivityModel::query()->count()); + + $this->app->make(ActivityBuffer::class)->flush(); + + $this->assertSame(1, CustomDatabaseConnectionOnActivityModel::query()->count()); + $this->assertSame(0, DefaultActivity::query()->count()); + } +} diff --git a/tests/ActivityLog/Models/CustomDatabaseConnectionOnActivityModel.php b/tests/ActivityLog/Models/CustomDatabaseConnectionOnActivityModel.php new file mode 100644 index 000000000..de7e94535 --- /dev/null +++ b/tests/ActivityLog/Models/CustomDatabaseConnectionOnActivityModel.php @@ -0,0 +1,13 @@ +id(); + $table->string('log_name')->nullable(); + $table->text('description'); + $table->nullableMorphs('subject'); + $table->string('event')->nullable(); + $table->nullableMorphs('causer'); + $table->jsonb('attribute_changes')->nullable(); + $table->jsonb('properties')->nullable(); + $table->timestamps(); + }); + } + + /** + * Remove the custom activity table. + */ + protected function tearDownInCoroutine(): void + { + try { + Schema::dropIfExists('custom_table_name'); + } finally { + parent::tearDownInCoroutine(); + } + } + + public function testUsesTheCustomTableForImmediateQueriesAndCleanup(): void + { + $this->assertSame('activity_log', (new DefaultActivity)->getTable()); + + config()->set( + 'activity-log.activity_model', + CustomTableNameOnActivityModel::class, + ); + + $activity = activity() + ->createdAt(CarbonImmutable::parse('2000-01-01 00:00:00')) + ->log('Custom table'); + + $this->assertInstanceOf(CustomTableNameOnActivityModel::class, $activity); + $this->assertSame('custom_table_name', $activity->getTable()); + $this->assertSame(1, CustomTableNameOnActivityModel::query()->count()); + $this->assertSame(0, DefaultActivity::query()->count()); + + $deleted = $this->app + ->make(ActivityLogConfiguration::class) + ->cleanActivityLogAction() + ->execute(1); + + $this->assertSame(1, $deleted); + $this->assertSame(0, CustomTableNameOnActivityModel::query()->count()); + } + + public function testUsesTheCustomTableForBufferedWrites(): void + { + config()->set([ + 'activity-log.activity_model' => CustomTableNameOnActivityModel::class, + 'activity-log.buffer.enabled' => true, + ]); + + $activity = activity()->log('Buffered custom table'); + + $this->assertInstanceOf(CustomTableNameOnActivityModel::class, $activity); + $this->assertSame(0, CustomTableNameOnActivityModel::query()->count()); + + $this->app->make(ActivityBuffer::class)->flush(); + + $this->assertSame(1, CustomTableNameOnActivityModel::query()->count()); + $this->assertSame(0, DefaultActivity::query()->count()); + } +} diff --git a/tests/ActivityLog/Models/CustomTableNameOnActivityModel.php b/tests/ActivityLog/Models/CustomTableNameOnActivityModel.php new file mode 100644 index 000000000..41049abd4 --- /dev/null +++ b/tests/ActivityLog/Models/CustomTableNameOnActivityModel.php @@ -0,0 +1,13 @@ +dontLogEmptyChanges() + ->logOnly(['name']); + } +} diff --git a/tests/ActivityLog/Models/User.php b/tests/ActivityLog/Models/User.php new file mode 100644 index 000000000..33f3c49ae --- /dev/null +++ b/tests/ActivityLog/Models/User.php @@ -0,0 +1,97 @@ +getAttribute($this->getAuthIdentifierName()); + } + + /** + * Get the name of the password attribute for the user. + */ + public function getAuthPasswordName(): string + { + return 'password'; + } + + /** + * Get the password for the user. + */ + public function getAuthPassword(): ?string + { + return $this->getAttribute('password'); + } + + /** + * Get the token value for the "remember me" session. + */ + public function getRememberToken(): ?string + { + return 'token'; + } + + /** + * Set the token value for the "remember me" session. + */ + public function setRememberToken(?string $value): void + { + } + + /** + * Get the column name for the "remember me" token. + */ + public function getRememberTokenName(): string + { + return 'tokenName'; + } + + /** + * Get the user's articles. + * + * @return HasMany + */ + public function articles(): HasMany + { + return $this->hasMany(Article::class); + } + + /** + * Get the user's latest article. + * + * @return HasOne + */ + public function latestArticle(): HasOne + { + return $this->hasOne(Article::class)->latest()->limit(1); + } +} diff --git a/tests/ActivityLog/Support/ActivityBufferTest.php b/tests/ActivityLog/Support/ActivityBufferTest.php new file mode 100644 index 000000000..675f18c22 --- /dev/null +++ b/tests/ActivityLog/Support/ActivityBufferTest.php @@ -0,0 +1,1019 @@ +set('activity-log.buffer.enabled', true); + } + + public function testBuffersActivitiesInsteadOfSavingThemImmediately(): void + { + activity()->log('buffered activity'); + + $this->assertSame(0, Activity::query()->count()); + $this->assertTrue($this->buffer()->hasPending()); + } + + public function testFlushesBufferedActivitiesToTheDatabase(): void + { + $firstActivity = activity()->log('first activity'); + activity()->log('second activity'); + + $this->assertNotNull($firstActivity); + $this->assertSame(0, Activity::query()->count()); + + $this->buffer()->flush(); + + $this->assertNull($firstActivity->getKey()); + $this->assertSame(2, Activity::query()->count()); + $this->assertSame('first activity', Activity::query()->firstOrFail()->description); + $this->assertSame( + 'second activity', + Activity::query()->orderByDesc('id')->firstOrFail()->description, + ); + } + + public function testGeneratesUniqueIdsOnTheReturnedActivityBeforeFlushing(): void + { + Schema::create('uuid_activity_log', static function (Blueprint $table): void { + $table->uuid('id')->primary(); + $table->string('log_name')->nullable(); + $table->text('description'); + $table->nullableMorphs('subject'); + $table->string('event')->nullable(); + $table->nullableMorphs('causer'); + $table->jsonb('attribute_changes')->nullable(); + $table->jsonb('properties')->nullable(); + $table->timestamps(); + }); + + try { + config()->set('activity-log.activity_model', UuidActivityLog::class); + + $activity = activity()->log('uuid activity'); + + $this->assertNotNull($activity); + // Prevent the final equality from passing vacuously on null === null. + $this->assertNotNull($activity->getKey()); + $this->assertSame(0, UuidActivityLog::query()->count()); + + $this->buffer()->flush(); + + $this->assertSame( + $activity->getKey(), + UuidActivityLog::query()->firstOrFail()->getKey(), + ); + } finally { + ActivityBuffer::finalizeCurrent(); + Schema::dropIfExists('uuid_activity_log'); + } + } + + public function testSavesActivitiesImmediatelyWhenBufferIsDisabled(): void + { + config()->set('activity-log.buffer.enabled', false); + + activity()->log('immediate activity'); + + $this->assertSame(1, Activity::query()->count()); + $this->assertNull(ActivityBuffer::current()); + } + + public function testFlushesWithCorrectProperties(): void + { + $properties = ['key' => 'value', 'nested' => ['sub' => 'data']]; + + activity() + ->withProperties($properties) + ->log('activity with properties'); + + $this->buffer()->flush(); + + $activity = Activity::query()->firstOrFail(); + + $this->assertSame('activity with properties', $activity->description); + $this->assertSame('value', $activity->getProperty('key')); + $this->assertSame('data', $activity->getProperty('nested.sub')); + } + + public function testFlushesWithCorrectSubjectAndCauser(): void + { + $article = Article::query()->firstOrFail(); + $user = User::query()->firstOrFail(); + + activity() + ->performedOn($article) + ->causedBy($user) + ->log('activity with relations'); + + $this->buffer()->flush(); + + $activity = Activity::query()->firstOrFail(); + + $this->assertSame($article->getMorphClass(), $activity->subject_type); + $this->assertSame($article->getKey(), $activity->subject_id); + $this->assertSame($user->getMorphClass(), $activity->causer_type); + $this->assertSame($user->getKey(), $activity->causer_id); + } + + public function testFlushesWithCorrectLogName(): void + { + activity('custom-log')->log('named log activity'); + + $this->buffer()->flush(); + + $this->assertSame('custom-log', Activity::query()->firstOrFail()->log_name); + } + + public function testFlushesWithCorrectEvent(): void + { + activity() + ->event('created') + ->log('event activity'); + + $this->buffer()->flush(); + + $this->assertSame('created', Activity::query()->firstOrFail()->event); + } + + public function testFlushesWithCorrectAttributeChanges(): void + { + activity() + ->withChanges(['attributes' => ['name' => 'new'], 'old' => ['name' => 'old']]) + ->log('changes activity'); + + $this->buffer()->flush(); + + $activity = Activity::query()->firstOrFail(); + + $this->assertSame([ + 'attributes' => ['name' => 'new'], + 'old' => ['name' => 'old'], + ], $activity->attribute_changes->toArray()); + } + + public function testPreservesACustomCreatedAtTimestamp(): void + { + $customDate = now()->subDays(5); + + activity() + ->createdAt($customDate) + ->log('backdated activity'); + + $this->buffer()->flush(); + + $this->assertSame( + $customDate->toAtomString(), + Activity::query()->firstOrFail()->created_at?->toAtomString(), + ); + } + + public function testBufferedInsertHookReceivesTimestampsAndControlsTheStoredColumns(): void + { + $model = new class extends Activity { + protected function getAttributesForInsert(): array + { + $attributes = parent::getAttributesForInsert(); + $attributes['description'] = $attributes['created_at']; + unset($attributes['updated_at']); + + return $attributes; + } + }; + config()->set('activity-log.activity_model', $model::class); + + $activity = activity()->log('custom insert'); + $this->buffer()->flush(); + + $this->assertNull($activity->created_at); + $row = Activity::query()->toBase()->sole(); + $this->assertNotNull($row->created_at); + $this->assertSame($row->created_at, $row->description); + $this->assertNull($row->updated_at); + } + + public function testSetsTimestampsAutomaticallyWhenNotProvided(): void + { + activity()->log('auto timestamp'); + + $this->buffer()->flush(); + + $activity = Activity::query()->firstOrFail(); + + $this->assertNotNull($activity->created_at); + $this->assertNotNull($activity->updated_at); + } + + public function testIsANoOpWhenFlushingAnEmptyBuffer(): void + { + $this->buffer()->flush(); + + $this->assertSame(0, Activity::query()->count()); + } + + public function testClearsTheBufferAfterFlushing(): void + { + activity()->log('will be flushed'); + + $buffer = $this->buffer(); + + $this->assertTrue($buffer->hasPending()); + $this->assertSame(1, $buffer->count()); + + $buffer->flush(); + + $this->assertFalse($buffer->hasPending()); + $this->assertSame(0, $buffer->count()); + } + + public function testCanFlushMultipleTimesSafely(): void + { + activity()->log('first'); + + $buffer = $this->buffer(); + + $buffer->flush(); + $buffer->flush(); + + $this->assertSame(1, Activity::query()->count()); + } + + public function testResolvesDescriptionPlaceholdersBeforeBuffering(): void + { + $article = Article::create(['name' => 'my article']); + + activity() + ->performedOn($article) + ->log('Subject is :subject.name'); + + $this->buffer()->flush(); + + $this->assertSame( + 'Subject is my article', + Activity::query()->firstOrFail()->description, + ); + } + + public function testWrapperRollbackRemovesDirectAndCommittedInnerActivities(): void + { + $database = $this->app->make('db'); + $connection = $database->connection(); + config()->set('activity-log.buffer.batch_size', 3); + (new DatabaseTransactionsManager(['sqlite']))->beginTransactions($database); + + try { + activity()->log('wrapper'); + $connection->transaction(static fn () => activity()->log('inner commit')); + $connection->beginTransaction(); + activity()->log('inner rollback'); + $connection->rollBack(); + + $this->assertSame(['wrapper', 'inner commit'], Activity::query()->orderBy('id')->pluck('description')->all()); + + $connection->beginTransaction(); + // The missing description fails the first batch, leaving the fourth row unattempted. + $this->buffer()->add(new Activity); + $connection->transaction(static function (): void { + activity()->log('second in batch'); + activity()->log('third in batch'); + activity()->log('unattempted'); + }); + + try { + $connection->commit(); + $this->fail('Expected the first insert to fail.'); + } catch (QueryException $exception) { + $this->assertStringContainsString('activity_log.description', $exception->getMessage()); + } + + $this->assertSame(1, $this->buffer()->count()); + } finally { + $connection->rollBack(0); + } + + $this->assertSame(0, $this->buffer()->count()); + ActivityBuffer::finalizeCurrent(); + $this->assertSame(0, Activity::query()->count()); + } + + public function testTransactionRowsRemainStagedUntilTheOuterCommit(): void + { + $connection = $this->activityConnection(); + $connection->beginTransaction(); + + try { + activity()->log('staged activity'); + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(1, $this->buffer()->count()); + $this->assertFalse($this->buffer()->canFlush()); + } finally { + $connection->commit(); + } + + $this->assertSame(1, $this->buffer()->count()); + $this->assertTrue($this->buffer()->canFlush()); + + $this->buffer()->flush(); + + $this->assertSame(['staged activity'], Activity::query()->pluck('description')->all()); + } + + public function testNestedRollbackDiscardsOnlyTheSavepointRows(): void + { + $connection = $this->activityConnection(); + $connection->beginTransaction(); + + try { + activity()->log('outer activity'); + $connection->beginTransaction(); + activity()->log('savepoint activity'); + $connection->rollBack(); + + $this->assertSame(1, $connection->transactionLevel()); + $this->assertSame(1, $this->buffer()->count()); + } finally { + $connection->commit(); + } + + $this->buffer()->flush(); + + $this->assertSame(['outer activity'], Activity::query()->pluck('description')->all()); + } + + public function testForeignCommitCannotPromoteAnActivityTransactionRow(): void + { + $activityConnection = $this->activityConnection(); + $foreignConnection = $this->foreignConnection(); + $activityConnection->beginTransaction(); + + try { + activity()->log('rolled back activity'); + $foreignConnection->beginTransaction(); + $foreignConnection->commit(); + + $this->assertSame(1, $this->buffer()->count()); + } finally { + $activityConnection->rollBack(); + } + + $this->buffer()->flush(); + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(0, $this->buffer()->count()); + } + + public function testForeignRollbackCannotDiscardAnActivityTransactionRow(): void + { + $activityConnection = $this->activityConnection(); + $foreignConnection = $this->foreignConnection(); + $foreignConnection->beginTransaction(); + $activityConnection->beginTransaction(); + + try { + activity()->log('committed activity'); + $foreignConnection->rollBack(); + + $this->assertSame(1, $this->buffer()->count()); + } finally { + $activityConnection->commit(); + } + + $this->buffer()->flush(); + + $this->assertSame(['committed activity'], Activity::query()->pluck('description')->all()); + } + + public function testTransactionOnOnlyAnotherConnectionDoesNotStageTheRow(): void + { + $foreignConnection = $this->foreignConnection(); + $foreignConnection->beginTransaction(); + + try { + activity()->log('independent activity'); + + $this->assertTrue($this->buffer()->canFlush()); + $this->buffer()->flush(); + $this->assertSame(1, Activity::query()->count()); + } finally { + $foreignConnection->rollBack(); + } + } + + public function testSequenceOrderSurvivesNestedTransactionResolution(): void + { + activity()->log('before transaction'); + $connection = $this->activityConnection(); + $connection->beginTransaction(); + + try { + activity()->log('outer before savepoint'); + $connection->beginTransaction(); + activity()->log('inside savepoint'); + $connection->afterCommit(function (): void { + $this->assertTrue($this->buffer()->canFlush()); + $this->buffer()->flush(); + $this->assertSame(['before transaction'], Activity::query()->pluck('description')->all()); + $this->assertFalse($this->buffer()->canFlush()); + }); + $connection->commit(); + activity()->log('outer after savepoint'); + } finally { + $connection->commit(); + } + + activity()->log('after transaction'); + $this->buffer()->flush(); + + $this->assertSame([ + 'before transaction', + 'outer before savepoint', + 'inside savepoint', + 'outer after savepoint', + 'after transaction', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + } + + public function testThresholdWaitsForEveryStagedOutcome(): void + { + config()->set('activity-log.buffer.batch_size', 2); + $connection = $this->activityConnection(); + $observedRowsAfterFirstPromotion = null; + $connection->beginTransaction(); + + try { + activity()->log('first staged activity'); + $connection->afterCommit(function () use (&$observedRowsAfterFirstPromotion): void { + $observedRowsAfterFirstPromotion = Activity::query()->count(); + }); + activity()->log('second staged activity'); + } finally { + $connection->commit(); + } + + $this->assertSame(0, $observedRowsAfterFirstPromotion); + $this->assertSame(2, Activity::query()->count()); + $this->assertSame(0, $this->buffer()->count()); + } + + public function testFlushInsideAnEarlierCommitCallbackLeavesStagedRowsUntouched(): void + { + $connection = $this->activityConnection(); + $connection->beginTransaction(); + + try { + $connection->afterCommit(function (): void { + $this->buffer()->flush(); + }); + activity()->log('committed after early flush'); + } finally { + $connection->commit(); + } + + $this->assertSame(1, $this->buffer()->count()); + $this->assertSame(0, Activity::query()->count()); + + $this->buffer()->flush(); + + $this->assertSame(['committed after early flush'], Activity::query()->pluck('description')->all()); + } + + public function testFlushInsideAnEarlierRollbackCallbackLeavesResolutionToTheOwnerCallback(): void + { + $connection = $this->activityConnection(); + $connection->beginTransaction(); + + try { + $connection->afterRollBack(function (): void { + $this->buffer()->flush(); + }); + activity()->log('rolled back after early flush'); + } finally { + $connection->rollBack(); + } + + $this->assertSame(0, $this->buffer()->count()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testFinalizationRejectsAnOpenActivityTransactionAndIsRepeatableAfterRollback(): void + { + $connection = $this->activityConnection(); + $connection->beginTransaction(); + activity()->log('open transaction activity'); + + try { + ActivityBuffer::finalizeCurrent(); + $this->fail('Expected finalization to reject an open activity transaction.'); + } catch (CouldNotLogActivity $exception) { + $this->assertSame( + 'The activity buffer cannot be flushed while its database connection has an active transaction.', + $exception->getMessage(), + ); + } finally { + $connection->rollBack(); + } + + ActivityBuffer::finalizeCurrent(); + ActivityBuffer::finalizeCurrent(); + + $this->assertSame(0, $this->buffer()->count()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testEarlierCommitCallbackFailureDoesNotDiscardCommittedActivity(): void + { + config()->set('activity-log.buffer.batch_size', 1); + $connection = $this->activityConnection(); + $failure = new RuntimeException('earlier commit callback failed'); + $connection->beginTransaction(); + + $connection->afterCommit(static function () use ($failure): never { + throw $failure; + }); + activity()->log('committed activity'); + $thrown = null; + + try { + $connection->commit(); + } catch (RuntimeException $exception) { + $thrown = $exception; + } + + $this->assertSame($failure, $thrown); + $this->assertSame(['committed activity'], Activity::query()->pluck('description')->all()); + $this->assertSame(0, $this->buffer()->count()); + } + + public function testRollbackCallbacksStillDiscardRowsAfterAnEarlierFailure(): void + { + $connection = $this->activityConnection(); + $failure = new RuntimeException('earlier rollback callback failed'); + $connection->beginTransaction(); + $connection->afterRollBack(static function () use ($failure): never { + throw $failure; + }); + activity()->log('rolled back activity'); + $thrown = null; + + try { + $connection->rollBack(); + } catch (RuntimeException $exception) { + $thrown = $exception; + } + + $this->assertSame($failure, $thrown); + $this->assertSame(0, $this->buffer()->count()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testThresholdAndRemainderUseBoundedInsertStatements(): void + { + $statements = 0; + Activity::addGlobalScope('track-statements', static function (EloquentBuilder $builder) use (&$statements): void { + $builder->getQuery()->beforeQuery(static function () use (&$statements): void { + ++$statements; + }); + }); + config()->set('activity-log.buffer.batch_size', 2); + $connection = $this->activityConnection(); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + + try { + foreach (range(1, 5) as $index) { + activity()->log("activity {$index}"); + } + + $this->buffer()->flush(); + $queries = $connection->getQueryLog(); + } finally { + $connection->disableQueryLog(); + $connection->flushQueryLog(); + } + + $inserts = array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with( + strtolower($query['query']), + 'insert into "activity_log"', + ), + )); + + $this->assertCount(3, $inserts); + $this->assertSame(3, $statements); + $this->assertSame([ + 'activity 1', + 'activity 2', + 'activity 3', + 'activity 4', + 'activity 5', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + $this->assertSame(0, $this->buffer()->count()); + } + + public function testAdjacentColumnShapesPreserveInsertionOrderAndDatabaseDefaults(): void + { + Schema::table('activity_log', static function (Blueprint $table): void { + $table->string('extra')->default('database default'); + }); + config()->set('activity-log.buffer.batch_size', 10); + $connection = $this->activityConnection(); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + + try { + activity()->log('default shape before'); + activity() + ->tap(static function (Activity $activity): void { + $activity->setAttribute('extra', 'explicit value'); + }) + ->log('explicit shape'); + activity()->log('default shape after'); + $this->buffer()->flush(); + $queries = $connection->getQueryLog(); + } finally { + $connection->disableQueryLog(); + $connection->flushQueryLog(); + } + + $inserts = array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with( + strtolower($query['query']), + 'insert into "activity_log"', + ), + )); + $rows = Activity::query() + ->orderBy('id') + ->toBase() + ->get(['description', 'extra']); + + $this->assertCount(3, $inserts); + $this->assertSame([ + ['description' => 'default shape before', 'extra' => 'database default'], + ['description' => 'explicit shape', 'extra' => 'explicit value'], + ['description' => 'default shape after', 'extra' => 'database default'], + ], $rows->map(static fn (object $row): array => (array) $row)->all()); + } + + public function testModelsWithoutTimestampsDoNotGainBufferTimestamps(): void + { + config()->set('activity-log.activity_model', ActivityLogWithoutTimestamps::class); + + activity()->log('without timestamps'); + $this->buffer()->flush(); + + $row = Activity::query()->toBase()->first(); + $this->assertNotNull($row); + $this->assertNull($row->created_at); + $this->assertNull($row->updated_at); + } + + public function testRenamedAndDisabledTimestampColumnsMatchImmediatePersistence(): void + { + Schema::table('activity_log', static function (Blueprint $table): void { + $table->timestamp('logged_at')->nullable(); + }); + config()->set('activity-log.activity_model', ActivityLogCreatedAtOnly::class); + + activity()->log('custom timestamps'); + $this->buffer()->flush(); + + $row = Activity::query()->toBase()->first(); + $this->assertNotNull($row); + $this->assertNotNull($row->logged_at); + $this->assertNull($row->created_at); + $this->assertNull($row->updated_at); + } + + public function testFlushWritesToTheConnectionSelectedWhenBuffering(): void + { + DB::usingConnection('custom_connection_name', function (): void { + $this->migrateActivityLogTable(); + activity()->log('scoped database'); + }); + + $this->buffer()->flush(); + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(['scoped database'], $this->foreignConnection()->table('activity_log')->pluck('description')->all()); + } + + public function testBufferedBinaryValuesUseBinaryBindings(): void + { + Schema::table('activity_log', static function (Blueprint $table): void { + $table->binary('token')->nullable(); + }); + + $activity = new Activity; + $activity->mergeCasts(['token' => AsBinary::class . ':uuid']); + $activity->setAttribute('description', 'binary value'); + $activity->setAttribute('token', '00112233-4455-6677-8899-aabbccddeeff'); + $this->buffer()->add($activity); + $this->buffer()->flush(); + + $row = $this->activityConnection()->selectOne('select typeof(token) as storage, hex(token) as value from activity_log'); + $this->assertSame('blob', $row->storage); + $this->assertSame('00112233445566778899AABBCCDDEEFF', $row->value); + } + + public function testChangingTheBufferedPersistenceTargetIsRejected(): void + { + try { + activity() + ->tap(static function (Activity $activity): void { + $activity->setTable('users'); + }) + ->log('changed target'); + $this->fail('Expected a changed buffer target to be rejected.'); + } catch (InvalidConfiguration $exception) { + $this->assertSame( + 'Buffered activity [Hypervel\ActivityLog\Models\Activity] targets ' + . 'connection [sqlite] and table [users], but this buffer owns connection [sqlite] ' + . 'and table [activity_log].', + $exception->getMessage(), + ); + } + + $this->assertSame(0, $this->buffer()->count()); + $this->assertSame(0, Activity::query()->count()); + } + + public function testFailedInsertDiscardsTheAttemptedBatchAndPreservesLaterRows(): void + { + config()->set('activity-log.buffer.batch_size', 1); + $this->activityConnection()->statement(<<<'SQL' + CREATE TRIGGER fail_activity_insert + BEFORE INSERT ON activity_log + WHEN NEW.description = 'failing activity' + BEGIN + SELECT RAISE(FAIL, 'buffer insert failed'); + END + SQL); + + try { + activity()->log('failing activity'); + $this->fail('Expected the buffered insert to fail.'); + } catch (QueryException $exception) { + $this->assertStringContainsString('buffer insert failed', $exception->getMessage()); + } + + $this->assertSame(0, $this->buffer()->count()); + activity()->log('later activity'); + + $this->assertSame(['later activity'], Activity::query()->pluck('description')->all()); + $this->buffer()->flush(); + $this->assertSame(['later activity'], Activity::query()->pluck('description')->all()); + } + + public function testFailureInALaterShapeRollsBackAndDiscardsTheWholeAttemptedBatch(): void + { + Schema::table('activity_log', static function (Blueprint $table): void { + $table->string('extra')->nullable(); + }); + config()->set('activity-log.buffer.batch_size', 2); + $this->activityConnection()->statement(<<<'SQL' + CREATE TRIGGER fail_later_activity_shape + BEFORE INSERT ON activity_log + WHEN NEW.description = 'failing second shape' + BEGIN + SELECT RAISE(FAIL, 'later shape failed'); + END + SQL); + + activity()->log('first shape'); + + try { + activity() + ->tap(static function (Activity $activity): void { + $activity->setAttribute('extra', 'different shape'); + }) + ->log('failing second shape'); + $this->fail('Expected the later shape insert to fail.'); + } catch (QueryException $exception) { + $this->assertStringContainsString('later shape failed', $exception->getMessage()); + } + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(0, $this->buffer()->count()); + activity()->log('unrelated tail'); + $this->buffer()->flush(); + + $this->assertSame(['unrelated tail'], Activity::query()->pluck('description')->all()); + } + + public function testFalseInsertFailsClosedAndIsNeverRetried(): void + { + $activity = Double::for(new Activity)->passthru(); + $activity->timestamps = false; + $activity->setConnection('sqlite'); + $activity->setRawAttributes(['description' => 'false insert']); + $eloquentBuilder = Double::for(EloquentBuilder::class)->strict(); + $queryBuilder = Double::for(QueryBuilder::class)->strict(); + $activity->expects('newQuery')->returns($eloquentBuilder); + $eloquentBuilder->expects('toBase')->returns($queryBuilder); + $queryBuilder->expects('insert')->returns(false); + + $configuration = Double::for(ActivityLogConfiguration::class)->strict(); + $configuration->expects('activityModelInstance')->returns($activity); + $configuration->expects('bufferBatchSize')->returns(1); + $buffer = new ActivityBuffer($configuration); + + try { + $buffer->add($activity); + $this->fail('Expected a false insert result to fail closed.'); + } catch (CouldNotLogActivity $exception) { + $this->assertSame('Could not persist the activity.', $exception->getMessage()); + } + + $this->assertSame(0, $buffer->count()); + $buffer->flush(); + $this->assertSame(0, $buffer->count()); + } + + public function testInternalCommitCallbackCanAddWorkWithoutSeeingTheClaimedBatch(): void + { + $connection = $this->activityConnection(); + $registered = false; + $callbackTransactionLevel = null; + $claimedRowsVisibleToCallback = null; + $connection->beforeExecuting(function (string $query) use ( + $connection, + &$registered, + &$callbackTransactionLevel, + &$claimedRowsVisibleToCallback, + ): void { + if ($registered + || ! str_starts_with(strtolower($query), 'insert into "activity_log"')) { + return; + } + + $registered = true; + $connection->afterCommit(function () use ( + $connection, + &$callbackTransactionLevel, + &$claimedRowsVisibleToCallback, + ): void { + $callbackTransactionLevel = $connection->transactionLevel(); + $claimedRowsVisibleToCallback = Activity::query()->pluck('description')->all(); + + activity()->log('reentrant callback activity'); + }); + }); + + try { + activity()->log('claimed activity'); + $this->buffer()->flush(); + } finally { + $connection->clearBeforeExecutingCallbacks(); + } + + $this->assertSame(0, $callbackTransactionLevel); + $this->assertSame(['claimed activity'], $claimedRowsVisibleToCallback); + $this->assertSame([ + 'claimed activity', + 'reentrant callback activity', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + $this->assertSame(0, $this->buffer()->count()); + } + + public function testThresholdReentryCannotReselectTheClaimedBatch(): void + { + // A batch size of one re-enters flushBatch() while its caller is still on + // the stack, so the in-flight sequence must already have been claimed. + config()->set('activity-log.buffer.batch_size', 1); + $connection = $this->activityConnection(); + $registered = false; + $connection->beforeExecuting(function (string $query) use ($connection, &$registered): void { + if ($registered + || ! str_starts_with(strtolower($query), 'insert into "activity_log"')) { + return; + } + + // Re-arming on the nested insert would create an intentional, + // unbounded feedback loop rather than bounded re-entry. + $registered = true; + $connection->afterCommit(static function (): void { + activity()->log('nested threshold activity'); + }); + }); + + try { + activity()->log('claimed threshold activity'); + } finally { + $connection->clearBeforeExecutingCallbacks(); + } + + $this->assertSame([ + 'claimed threshold activity', + 'nested threshold activity', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + $this->assertSame(0, $this->buffer()->count()); + } + + public function testFailedPostCommitFlushLeavesDomainWorkCommitted(): void + { + $connection = $this->activityConnection(); + $connection->transaction(static function (): void { + Article::query()->create(['name' => 'committed domain row']); + activity()->log('post-commit failure'); + }); + $connection->statement(<<<'SQL' + CREATE TRIGGER fail_post_commit_activity + BEFORE INSERT ON activity_log + WHEN NEW.description = 'post-commit failure' + BEGIN + SELECT RAISE(FAIL, 'post-commit activity failed'); + END + SQL); + + try { + ActivityBuffer::finalizeCurrent(); + $this->fail('Expected the post-commit activity insert to fail.'); + } catch (QueryException $exception) { + $this->assertStringContainsString('post-commit activity failed', $exception->getMessage()); + } + + $this->assertSame(1, Article::query()->where('name', 'committed domain row')->count()); + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(0, $this->buffer()->count()); + } + + /** + * Get the current scoped activity buffer. + */ + protected function buffer(): ActivityBuffer + { + return $this->app->make(ActivityBuffer::class); + } + + /** + * Get the activity model connection. + */ + protected function activityConnection(): Connection + { + return (new Activity)->getConnection(); + } + + /** + * Get the separate fixture connection. + */ + protected function foreignConnection(): Connection + { + return (new Activity)->setConnection('custom_connection_name')->getConnection(); + } +} + +class ActivityLogWithoutTimestamps extends Activity +{ + public bool $timestamps = false; +} + +class ActivityLogCreatedAtOnly extends Activity +{ + public const ?string CREATED_AT = 'logged_at'; + + public const ?string UPDATED_AT = null; +} + +class UuidActivityLog extends Activity +{ + use HasUuids; + + protected ?string $table = 'uuid_activity_log'; +} diff --git a/tests/ActivityLog/Support/ActivityLogConfigurationTest.php b/tests/ActivityLog/Support/ActivityLogConfigurationTest.php new file mode 100644 index 000000000..0b2c9ea2f --- /dev/null +++ b/tests/ActivityLog/Support/ActivityLogConfigurationTest.php @@ -0,0 +1,309 @@ +configuration(); + + $this->assertTrue($configuration->enabled()); + $this->assertSame(365, $configuration->cleanAfterDays()); + $this->assertSame(1000, $configuration->cleanBatchSize()); + $this->assertSame('default', $configuration->defaultLogName()); + $this->assertNull($configuration->defaultAuthDriver()); + $this->assertFalse($configuration->includeSoftDeletedSubjects()); + $this->assertSame(Activity::class, $configuration->activityModel()); + $this->assertSame([], $configuration->defaultExceptAttributes()); + $this->assertFalse($configuration->bufferEnabled()); + $this->assertSame(500, $configuration->bufferBatchSize()); + } + + public function testCastsEnvironmentValuesAtTheConfigBoundary(): void + { + $keys = [ + 'ACTIVITY_LOG_ENABLED' => '0', + 'ACTIVITY_LOG_CLEAN_BATCH_SIZE' => '17', + 'ACTIVITY_LOG_BUFFER_ENABLED' => '1', + 'ACTIVITY_LOG_BUFFER_BATCH_SIZE' => '23', + ]; + $previous = []; + + foreach ($keys as $key => $value) { + $previous[$key] = Env::has($key) ? Env::get($key) : null; + Env::set($key, $value); + } + + try { + $config = require dirname(__DIR__, 3) . '/src/activity-log/config/activity-log.php'; + } finally { + foreach ($previous as $key => $value) { + if ($value === null) { + Env::forget($key); + } else { + Env::set($key, (string) $value); + } + } + } + + config()->set('activity-log', $config); + $configuration = $this->configuration(); + + $this->assertFalse($configuration->enabled()); + $this->assertSame(17, $configuration->cleanBatchSize()); + $this->assertTrue($configuration->bufferEnabled()); + $this->assertSame(23, $configuration->bufferBatchSize()); + } + + #[DataProvider('invalidPositiveIntegers')] + public function testRejectsInvalidPositiveIntegers( + string $key, + mixed $value, + string $method, + string $message, + ): void { + config()->set($key, $value); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + $this->configuration()->{$method}(); + } + + /** + * Provide invalid positive integer configuration. + * + * @return array + */ + public static function invalidPositiveIntegers(): array + { + return [ + 'zero retention' => [ + 'activity-log.clean_after_days', + 0, + 'cleanAfterDays', + 'Configuration value for key [activity-log.clean_after_days] must be at least 1.', + ], + 'negative clean batch' => [ + 'activity-log.clean_batch_size', + -1, + 'cleanBatchSize', + 'Configuration value for key [activity-log.clean_batch_size] must be at least 1.', + ], + 'numeric-string buffer batch' => [ + 'activity-log.buffer.batch_size', + '10', + 'bufferBatchSize', + 'Configuration value for key [activity-log.buffer.batch_size] must be an integer, string given.', + ], + ]; + } + + #[DataProvider('invalidNullableStrings')] + public function testRejectsInvalidNullableStrings( + string $key, + mixed $value, + string $method, + string $message, + ): void { + config()->set($key, $value); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + $this->configuration()->{$method}(); + } + + /** + * Provide invalid nullable string configuration. + * + * @return array + */ + public static function invalidNullableStrings(): array + { + return [ + 'default log name' => [ + 'activity-log.default_log_name', + 1, + 'defaultLogName', + 'Configuration value for key [activity-log.default_log_name] must be a string or null, integer given.', + ], + 'default auth driver' => [ + 'activity-log.default_auth_driver', + [], + 'defaultAuthDriver', + 'Configuration value for key [activity-log.default_auth_driver] must be a string or null, array given.', + ], + ]; + } + + public function testPartialNestedBufferConfigurationFailsAtTheMissingRequiredKey(): void + { + config()->set('activity-log.buffer', ['enabled' => true]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Configuration value for key [activity-log.buffer.batch_size] must be an integer, NULL given.', + ); + + $this->configuration()->bufferBatchSize(); + } + + #[DataProvider('invalidExcludedAttributes')] + public function testRejectsInvalidGlobalAttributeExclusions(array $attributes): void + { + config()->set('activity-log.default_except_attributes', $attributes); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Configuration value for key [activity-log.default_except_attributes] must be a list of strings.', + ); + + $this->configuration()->defaultExceptAttributes(); + } + + /** + * Provide invalid global attribute exclusions. + * + * @return array}> + */ + public static function invalidExcludedAttributes(): array + { + return [ + 'associative' => [['password' => true]], + 'non-string member' => [['password', 1]], + ]; + } + + public function testRejectsNonConcreteOrConstructedActivityModels(): void + { + $configuration = $this->configuration(); + + foreach ([AbstractConfiguredActivity::class, ConstructedActivity::class] as $model) { + config()->set('activity-log.activity_model', $model); + + try { + $configuration->activityModel(); + $this->fail("Expected [{$model}] to be rejected."); + } catch (InvalidConfiguration $exception) { + $this->assertStringContainsString($model, $exception->getMessage()); + } + } + } + + #[DataProvider('invalidActions')] + public function testRejectsInvalidActionClasses(string $action): void + { + config()->set('activity-log.actions.log_activity', $action); + + $this->expectException(InvalidConfiguration::class); + $this->expectExceptionMessage( + "The configured action [{$action}] must be a concrete subclass of [" + . LogActivityAction::class . '].', + ); + + $this->configuration()->logActivityAction(); + } + + /** + * Provide invalid action classes. + * + * @return array + */ + public static function invalidActions(): array + { + return [ + 'wrong base' => [stdClass::class], + 'abstract action' => [AbstractLogActivityAction::class], + ]; + } + + public function testCachesValidatedModelAndActionMetadataForItsLifetime(): void + { + config()->set([ + 'activity-log.activity_model' => Activity::class, + 'activity-log.actions.log_activity' => CachedLogActivityAction::class, + ]); + $configuration = $this->configuration(); + + $this->assertSame(Activity::class, $configuration->activityModel()); + $this->assertInstanceOf( + CachedLogActivityAction::class, + $configuration->logActivityAction(), + ); + + config()->set([ + 'activity-log.activity_model' => InvalidActivity::class, + 'activity-log.actions.log_activity' => ReplacementLogActivityAction::class, + ]); + + $this->assertSame(Activity::class, $configuration->activityModel()); + $this->assertInstanceOf( + CachedLogActivityAction::class, + $configuration->logActivityAction(), + ); + } + + public function testANewConfigurationServiceReadsReloadedMetadata(): void + { + $repository = $this->app->make(Repository::class); + $configuration = new ActivityLogConfiguration($repository, $this->app); + config()->set('activity-log.activity_model', Activity::class); + + $this->assertSame(Activity::class, $configuration->activityModel()); + + config()->set('activity-log.activity_model', InvalidActivity::class); + $reloaded = new ActivityLogConfiguration($repository, $this->app); + + $this->expectException(InvalidConfiguration::class); + + $reloaded->activityModel(); + } + + /** + * Get the worker configuration service. + */ + protected function configuration(): ActivityLogConfiguration + { + return $this->app->make(ActivityLogConfiguration::class); + } +} + +abstract class AbstractConfiguredActivity extends Activity +{ +} + +class ConstructedActivity extends Activity +{ + public function __construct(string $required) + { + parent::__construct(); + } +} + +abstract class AbstractLogActivityAction extends LogActivityAction +{ +} + +class CachedLogActivityAction extends LogActivityAction +{ +} + +class ReplacementLogActivityAction extends LogActivityAction +{ +} diff --git a/tests/ActivityLog/Support/ActivityLogLifecycleTest.php b/tests/ActivityLog/Support/ActivityLogLifecycleTest.php new file mode 100644 index 000000000..e2e0b1024 --- /dev/null +++ b/tests/ActivityLog/Support/ActivityLogLifecycleTest.php @@ -0,0 +1,216 @@ +set('activity-log.buffer.enabled', true); + } + + public function testCoroutineFallbackFlushesRowsAddedAfterApplicationTermination(): void + { + $lateCallbackRan = false; + $sameBuffer = false; + $this->app->terminating(function () use (&$lateCallbackRan, &$sameBuffer): void { + if ($lateCallbackRan) { + return; + } + + $lateCallbackRan = true; + $buffer = ActivityBuffer::current(); + activity()->log('late terminating activity'); + $sameBuffer = $buffer === ActivityBuffer::current(); + }); + + parallel([ + 'request' => function (): void { + activity()->log('application boundary activity'); + $this->app->terminate(); + + $this->assertSame( + ['application boundary activity'], + Activity::query()->pluck('description')->all(), + ); + $this->assertSame(1, ActivityBuffer::current()?->count()); + }, + ]); + + $this->assertTrue($lateCallbackRan); + $this->assertTrue($sameBuffer); + $this->assertSame([ + 'application boundary activity', + 'late terminating activity', + ], Activity::query()->orderBy('id')->pluck('description')->all()); + } + + public function testJobAttemptedFlushesAFailedAsynchronousAttempt(): void + { + $job = new class(connectionName: 'database') extends FakeJob { + public function fire(): void + { + activity()->log('failed job activity'); + + throw new RuntimeException('job failed'); + } + }; + + try { + $this->app->make('queue.worker')->process('database', $job, new WorkerOptions); + $this->fail('Expected the job to fail.'); + } catch (RuntimeException $exception) { + $this->assertSame($job->failedWith, $exception); + } + + $this->assertSame( + ['failed job activity'], + Activity::query()->pluck('description')->all(), + ); + $this->assertSame(0, ActivityBuffer::current()?->count()); + } + + public function testSyncJobLeavesTheBufferToTheEnclosingBoundary(): void + { + activity()->log('sync job activity'); + $syncJob = new SyncJob($this->app, '{}', 'sync', 'sync'); + + $this->app->make('events')->dispatch(new JobAttempted('sync', $syncJob)); + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(1, ActivityBuffer::current()?->count()); + + ActivityBuffer::finalizeCurrent(); + + $this->assertSame( + ['sync job activity'], + Activity::query()->pluck('description')->all(), + ); + } + + public function testPassiveObserverFlushesAfterAListenerStopsPropagation(): void + { + $this->app->make('events')->listen( + JobAttempted::class, + static fn (): false => false, + ); + activity()->log('stopped listener activity'); + + $this->app->make('events')->dispatch(new JobAttempted( + 'test', + Double::for(Job::class)->strict(), + )); + + $this->assertSame( + ['stopped listener activity'], + Activity::query()->pluck('description')->all(), + ); + } + + public function testActiveListenerFailureRemainsPrimaryWhenObserverFlushAlsoFails(): void + { + $this->failActivityInserts(); + $listenerFailure = new RuntimeException('active listener failed'); + $this->app->make('events')->listen( + JobAttempted::class, + static function () use ($listenerFailure): never { + throw $listenerFailure; + }, + ); + activity()->log('observer failure activity'); + + try { + $this->app->make('events')->dispatch(new JobAttempted( + 'test', + Double::for(Job::class)->strict(), + )); + $this->fail('Expected the active listener to fail.'); + } catch (RuntimeException $exception) { + $this->assertSame($listenerFailure, $exception); + } + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(0, ActivityBuffer::current()?->count()); + } + + public function testObserverFlushFailurePropagatesWithoutAnActiveFailure(): void + { + $this->failActivityInserts(); + activity()->log('propagated observer failure'); + + try { + $this->app->make('events')->dispatch(new JobAttempted( + 'test', + Double::for(Job::class)->strict(), + )); + $this->fail('Expected the observer flush to fail.'); + } catch (QueryException $exception) { + $this->assertStringContainsString('lifecycle activity failed', $exception->getMessage()); + } + + $this->assertSame(0, Activity::query()->count()); + $this->assertSame(0, ActivityBuffer::current()?->count()); + } + + public function testAdHocCoroutineFallbackReportsPersistenceFailure(): void + { + $this->failActivityInserts(); + $exceptions = Double::for(ExceptionHandler::class)->strict(); + $exceptions->expects('report') + ->with(Argument::satisfies( + static fn (Throwable $exception): bool => $exception instanceof QueryException + && str_contains($exception->getMessage(), 'lifecycle activity failed'), + )); + $this->app->instance(ExceptionHandler::class, $exceptions); + + parallel([ + 'ad hoc' => static function (): void { + activity()->log('deferred failure activity'); + }, + ]); + + $this->assertSame(0, Activity::query()->count()); + $this->assertNull(ActivityBuffer::current()); + } + + /** + * Make every activity insert fail for this test. + */ + protected function failActivityInserts(): void + { + (new Activity)->getConnection()->statement(<<<'SQL' + CREATE TRIGGER fail_lifecycle_activity_insert + BEFORE INSERT ON activity_log + BEGIN + SELECT RAISE(FAIL, 'lifecycle activity failed'); + END + SQL); + } +} diff --git a/tests/ActivityLog/Support/ActivityLoggerTest.php b/tests/ActivityLog/Support/ActivityLoggerTest.php new file mode 100644 index 000000000..62f0cd067 --- /dev/null +++ b/tests/ActivityLog/Support/ActivityLoggerTest.php @@ -0,0 +1,730 @@ +log($this->activityDescription); + + $this->assertSame($this->activityDescription, $this->lastActivity()->description); + } + + public function testCanLogAnActivityWithFacade(): void + { + ActivityFacade::log($this->activityDescription); + + $this->assertSame($this->activityDescription, $this->lastActivity()->description); + } + + public function testFacadeCreatesIndependentActivityLoggers(): void + { + $first = ActivityFacade::logger() + ->event('first') + ->withProperty('builder', 'first'); + $second = ActivityFacade::logger() + ->event('second') + ->withProperty('builder', 'second'); + + $this->assertNotSame($first, $second); + + $first->log('First activity'); + $second->log('Second activity'); + + $activities = Activity::query()->orderBy('id')->get(); + + $this->assertSame('first', $activities[0]->event); + $this->assertSame('first', $activities[0]->getProperty('builder')); + $this->assertSame('second', $activities[1]->event); + $this->assertSame('second', $activities[1]->getProperty('builder')); + } + + public function testCanLogMultipleConsecutiveActivities(): void + { + ActivityFacade::log($this->activityDescription); + + ActivityFacade::causedByAnonymous() + ->event('created') + ->log($this->activityDescription); + + $activity = $this->lastActivity(); + + $this->assertSame($this->activityDescription, $activity->description); + $this->assertSame('created', $activity->event); + $this->assertNull($activity->causer_id); + $this->assertNull($activity->causer_type); + } + + public function testWillNotLogAnActivityWhenTheLogIsNotEnabled(): void + { + config()->set('activity-log.enabled', false); + + activity()->log($this->activityDescription); + + $this->assertNull($this->getLastActivity()); + } + + public function testWillLogActivityWithANullLogName(): void + { + config()->set('activity-log.default_log_name', null); + + activity()->log($this->activityDescription); + + $this->assertNull($this->lastActivity()->log_name); + } + + public function testRejectsANullEnabledOption(): void + { + config()->set('activity-log.enabled', null); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Configuration value for key [activity-log.enabled] must be a boolean, NULL given.', + ); + + activity()->log($this->activityDescription); + } + + public function testWillLogToTheDefaultLogByDefault(): void + { + activity()->log($this->activityDescription); + + $this->assertSame(config('activity-log.default_log_name'), $this->lastActivity()->log_name); + } + + public function testCanLogAnActivityToASpecificLog(): void + { + $customLogName = 'secondLog'; + + activity($customLogName)->log($this->activityDescription); + $this->assertSame($customLogName, $this->lastActivity()->log_name); + + activity()->useLog($customLogName)->log($this->activityDescription); + $this->assertSame($customLogName, $this->lastActivity()->log_name); + } + + public function testCanLogAnActivityWithASubject(): void + { + $subject = Article::query()->firstOrFail(); + + activity() + ->performedOn($subject) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Article::class, $activity->subject); + $this->assertSame($subject->getKey(), $activity->subject?->getKey()); + } + + public function testCanLogAnActivityWithACauser(): void + { + $user = User::query()->firstOrFail(); + + activity() + ->causedBy($user) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(User::class, $activity->causer); + $this->assertSame($user->getKey(), $activity->causer?->getKey()); + } + + public function testCanLogAnActivityWithACauserOtherThanUserModel(): void + { + $article = Article::query()->firstOrFail(); + + activity() + ->causedBy($article) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Article::class, $activity->causer); + $this->assertSame($article->getKey(), $activity->causer?->getKey()); + } + + public function testCanLogAnActivityWithACauserSetFromAnotherContext(): void + { + $causer = Article::query()->firstOrFail(); + $this->app->make(CauserResolver::class)->setCauser($causer); + + activity()->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Article::class, $activity->causer); + $this->assertSame($causer->getKey(), $activity->causer?->getKey()); + } + + public function testCanLogAnActivityWithACauserWhenThereIsNoWebGuard(): void + { + config()->set([ + 'auth.guards.web' => null, + 'auth.guards.foo' => ['driver' => 'session', 'provider' => 'users'], + 'activity-log.default_auth_driver' => 'foo', + ]); + + $user = User::query()->firstOrFail(); + Auth::guard('foo')->setUser($user); + activity()->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(User::class, $activity->causer); + $this->assertSame($user->getKey(), $activity->causer?->getKey()); + } + + public function testPreassignedCauserAndArrayPropertiesOnACustomActivity(): void + { + $user = User::query()->findOrFail(2); + Auth::login($user); + config(['activity-log.activity_model' => ActivityWithDefaultCauser::class]); + + $activity = activity()->withProperty('key', ['nested' => 'value'])->log('custom')->fresh(); + + $this->assertSame(1, $activity->causer_id); + $this->assertSame('value', $activity->getProperty('key.nested')); + } + + public function testBackedEnumLogNamesWorkAcrossLoggerOptionsAndQueryScopes(): void + { + activity(StringBackedEnum::Published)->log('published'); + activity()->inLog(IntBackedEnum::Draft)->log('draft'); + $article = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->useLogName(StringBackedEnum::Draft); + } + }; + $article->name = 'example'; + $article->save(); + + $this->assertSame('0', Activity::inLog(IntBackedEnum::Draft)->sole()->log_name); + $this->assertSame(['published', '0'], Activity::inLog(StringBackedEnum::Published, IntBackedEnum::Draft)->orderBy('id')->pluck('log_name')->all()); + $this->assertSame(['published', 'draft'], Activity::inLog([StringBackedEnum::Published, 'draft'])->orderBy('id')->pluck('log_name')->all()); + } + + public function testCanLogActivityWithProperties(): void + { + activity() + ->withProperties([ + 'property' => [ + 'subProperty' => 'value', + ], + ]) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Collection::class, $activity->properties); + $this->assertSame('value', $activity->getProperty('property.subProperty')); + } + + public function testCanLogActivityWithNullProperties(): void + { + activity() + ->withProperties(['property' => null]) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Collection::class, $activity->properties); + $this->assertNull($activity->getProperty('property')); + } + + public function testCanLogActivityWithASingleProperty(): void + { + activity() + ->withProperty('key', 'value') + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Collection::class, $activity->properties); + $this->assertSame('value', $activity->getProperty('key')); + $this->assertSame('default value', $activity->getProperty('non_existent', 'default value')); + } + + public function testCanTranslateAGivenCauserIdToAnObject(): void + { + $userId = User::query()->firstOrFail()->getKey(); + + activity() + ->causedBy($userId) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(User::class, $activity->causer); + $this->assertSame($userId, $activity->causer?->getKey()); + } + + public function testWillThrowAnExceptionIfItCannotTranslateACauserId(): void + { + $this->expectException(CouldNotLogActivity::class); + + activity()->causedBy(999); + } + + public function testWillUseTheLoggedInUserAsTheCauserByDefault(): void + { + $user = User::query()->findOrFail(1); + + Auth::login($user); + + activity()->log('hello poetsvrouwman'); + + $activity = $this->lastActivity(); + + $this->assertInstanceOf(User::class, $activity->causer); + $this->assertSame($user->getKey(), $activity->causer?->getKey()); + } + + public function testCanLogActivityUsingAnAnonymousCauser(): void + { + activity() + ->causedByAnonymous() + ->log('hello poetsvrouwman'); + + $this->assertNull($this->lastActivity()->causer_id); + $this->assertNull($this->lastActivity()->causer_type); + } + + public function testAnonymousCauserOverridesTheLoggedInUser(): void + { + Auth::login(User::query()->findOrFail(1)); + + activity() + ->byAnonymous() + ->log('hello poetsvrouwman'); + + $this->assertNull($this->lastActivity()->causer_id); + $this->assertNull($this->lastActivity()->causer_type); + } + + public function testCanReplaceThePlaceholders(): void + { + $article = Article::create(['name' => 'article name']); + $causer = Article::create(['name' => 'user name']); + + activity() + ->performedOn($article) + ->causedBy($causer) + ->withProperties(['key' => 'value', 'key2' => ['subkey' => 'subvalue']]) + ->log('Subject name is :subject.name, causer name is :causer.name and property key is :properties.key and sub key :properties.key2.subkey'); + + $this->assertSame( + 'Subject name is article name, causer name is user name and property key is value and sub key subvalue', + $this->lastActivity()->description, + ); + } + + public function testCanReplacePlaceholdersWithObjectPropertiesAndAccessors(): void + { + $article = Article::create([ + 'name' => 'article name', + 'user_id' => User::query()->firstOrFail()->getKey(), + ]); + + $article->setAttribute('foo', new stdClass); + $article->foo->bar = new stdClass; + $article->foo->bar->baz = 'zal'; + + activity() + ->performedOn($article) + ->withProperties(['key' => 'value', 'key2' => ['subkey' => 'subvalue']]) + ->log('Subject name is :subject.name, deeply nested property is :subject.foo.bar.baz, object :subject.foo, array :properties.key2, accessor property is :subject.owner_name'); + + $this->assertSame( + 'Subject name is article name, deeply nested property is zal, object :subject.foo, array :properties.key2, accessor property is name 1', + $this->lastActivity()->description, + ); + } + + public function testCanLogAnActivityWithEvent(): void + { + $article = Article::create(['name' => 'article name']); + + activity() + ->performedOn($article) + ->event('create') + ->log('test event'); + + $this->assertSame('create', $this->lastActivity()->event); + } + + public function testWillNotReplaceNonPlaceholders(): void + { + $description = 'hello: :hello'; + + activity()->log($description); + + $this->assertSame($description, $this->lastActivity()->description); + } + + public function testReturnsTheConfiguredCustomActivityModelAfterLogging(): void + { + $activityModel = new class extends Activity { + }; + + config()->set('activity-log.activity_model', $activityModel::class); + + $loggedActivity = activity()->log('test'); + + $this->assertInstanceOf($activityModel::class, $loggedActivity); + } + + public function testWillNotLogAnActivityWhenTheLogIsManuallyDisabled(): void + { + activity()->disableLogging(); + + activity()->log($this->activityDescription); + + $this->assertNull($this->getLastActivity()); + } + + public function testWillLogAnActivityWhenTheLogIsManuallyEnabled(): void + { + config()->set('activity-log.enabled', false); + + activity()->enableLogging(); + activity()->log($this->activityDescription); + + $this->assertSame($this->activityDescription, $this->lastActivity()->description); + } + + public function testAcceptsNullParameterForCausedBy(): void + { + $activity = activity()->causedBy(null)->log('nothing'); + + $this->assertNotNull($activity); + } + + public function testCanLogActivityWhenAttributesAreChangedWithTap(): void + { + $properties = [ + 'property' => [ + 'subProperty' => 'value', + ], + ]; + + activity() + ->tap(function (Activity $activity) use ($properties): void { + $activity->setAttribute('properties', collect($properties)); + $activity->setAttribute('created_at', CarbonImmutable::yesterday()->startOfDay()); + }) + ->log($this->activityDescription); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(Collection::class, $activity->properties); + $this->assertSame('value', $activity->getProperty('property.subProperty')); + $this->assertSame( + CarbonImmutable::yesterday()->startOfDay()->format('Y-m-d H:i:s'), + $activity->created_at?->format('Y-m-d H:i:s'), + ); + } + + public function testWillTapASubject(): void + { + $model = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $activity->setAttribute('description', 'my custom description'); + } + }; + + activity() + ->on($model) + ->log($this->activityDescription); + + $this->assertSame('my custom description', Activity::query()->firstOrFail()->description); + } + + public function testWillLogACustomCreatedAtDateTime(): void + { + $activityDateTime = now()->subDays(10); + + activity() + ->createdAt($activityDateTime) + ->log('created'); + + $this->assertSame( + $activityDateTime->toAtomString(), + Activity::query()->firstOrFail()->created_at?->toAtomString(), + ); + } + + public function testCreatedAtUsesTheConfiguredCreatedAtColumn(): void + { + Schema::table('activity_log', static function (Blueprint $table): void { + $table->timestamp('logged_at')->nullable(); + }); + config()->set( + 'activity-log.activity_model', + LoggerActivityWithRenamedCreatedAt::class, + ); + $activityDateTime = now()->subDays(10); + + activity() + ->createdAt($activityDateTime) + ->log('created'); + + $activity = LoggerActivityWithRenamedCreatedAt::query()->firstOrFail(); + + $this->assertSame( + $activityDateTime->toAtomString(), + $activity->logged_at?->toAtomString(), + ); + $this->assertNull($activity->getRawOriginal('created_at')); + } + + public function testCreatedAtRejectsAnActivityModelWithoutACreatedAtColumn(): void + { + config()->set( + 'activity-log.activity_model', + LoggerActivityWithoutCreatedAtColumn::class, + ); + + $this->expectException(InvalidConfiguration::class); + $this->expectExceptionMessage( + 'The configured activity model [' . LoggerActivityWithoutCreatedAtColumn::class + . '] does not define a created-at column.', + ); + + activity()->createdAt(now()); + } + + public function testWillDisableLogsForACallback(): void + { + $result = activity()->withoutLogging(function (): string { + activity()->log('created'); + + return 'hello'; + }); + + $this->assertNull($this->getLastActivity()); + $this->assertSame('hello', $result); + } + + public function testWillDisableLogsForACallbackWithoutAffectingPreviousState(): void + { + activity()->withoutLogging(function (): void { + activity()->log('created'); + }); + + $this->assertNull($this->getLastActivity()); + + activity()->log('outer'); + + $this->assertSame('outer', $this->lastActivity()->description); + } + + public function testWillDisableLogsForACallbackWithoutAffectingDisabledState(): void + { + activity()->disableLogging(); + + activity()->withoutLogging(function (): void { + activity()->log('created'); + activity()->enableLogging(); + }); + + $this->assertNull($this->getLastActivity()); + + activity()->log('outer'); + + $this->assertNull($this->getLastActivity()); + } + + public function testWillRestoreDisabledStateWhenTheCallbackThrows(): void + { + activity()->disableLogging(); + + try { + activity()->withoutLogging(function (): never { + activity()->log('created'); + activity()->enableLogging(); + + throw new Exception('OH NO'); + }); + } catch (Exception $exception) { + $this->assertSame('OH NO', $exception->getMessage()); + } + + $this->assertNull($this->getLastActivity()); + + activity()->log('outer'); + + $this->assertNull($this->getLastActivity()); + } + + public function testLogsBackedEnumsInProperties(): void + { + activity() + ->withProperties(['int_backed_enum' => IntBackedEnum::Draft]) + ->withProperty('string_backed_enum', StringBackedEnum::Published) + ->log($this->activityDescription); + + $this->assertSame(0, $this->lastActivity()->properties['int_backed_enum']); + $this->assertSame('published', $this->lastActivity()->properties['string_backed_enum']); + } + + public function testDoesNotLogNonBackedEnumsInProperties(): void + { + $this->expectException(JsonEncodingException::class); + + activity() + ->withProperty('non_backed_enum', NonBackedEnum::Published) + ->log($this->activityDescription); + } + + public function testCanModifyAnActivityUsingBeforeLogging(): void + { + LogActivityAction::beforeLogging(function (Activity $activity): void { + $activity->setAttribute('description', 'modified by beforeLogging'); + }); + + activity()->log('original description'); + + $this->assertSame('modified by beforeLogging', $this->lastActivity()->description); + } + + public function testCanRegisterMultipleBeforeLoggingCallbacks(): void + { + LogActivityAction::beforeLogging(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put('first', true), + ); + }); + + LogActivityAction::beforeLogging(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put('second', true), + ); + }); + + activity()->log('test'); + + $activity = $this->lastActivity(); + + $this->assertTrue($activity->getProperty('first')); + $this->assertTrue($activity->getProperty('second')); + } + + public function testCanUseBeforeLoggingViaTheFacade(): void + { + ActivityFacade::beforeLogging(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put('from_facade', true), + ); + }); + + activity()->log('test'); + + $this->assertTrue($this->lastActivity()->getProperty('from_facade')); + } + + public function testRunsBeforeLoggingCallbacksForModelEventActivities(): void + { + LogActivityAction::beforeLogging(function (Activity $activity): void { + $activity->setAttribute( + 'properties', + $activity->properties->put('hook_ran', true), + ); + }); + + $article = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + }; + + $article->setAttribute('name', 'test'); + $article->save(); + + $this->assertTrue($this->lastActivity()->getProperty('hook_ran')); + } +} + +class ActivityWithDefaultCauser extends Activity +{ + protected ?string $table = 'activity_log'; + + protected array $attributes = ['causer_type' => User::class, 'causer_id' => 1]; + + protected function casts(): array + { + return array_replace(parent::casts(), ['properties' => 'array']); + } +} + +class LoggerActivityWithRenamedCreatedAt extends Activity +{ + public const ?string CREATED_AT = 'logged_at'; + + public const ?string UPDATED_AT = null; +} + +class LoggerActivityWithoutCreatedAtColumn extends Activity +{ + public const ?string CREATED_AT = null; + + public const ?string UPDATED_AT = null; + + public bool $timestamps = false; +} diff --git a/tests/ActivityLog/Support/CauserResolverTest.php b/tests/ActivityLog/Support/CauserResolverTest.php new file mode 100644 index 000000000..d3d30347a --- /dev/null +++ b/tests/ActivityLog/Support/CauserResolverTest.php @@ -0,0 +1,242 @@ +firstOrFail(); + Auth::login($user); + + $causer = $this->resolver()->resolve(); + + $this->assertInstanceOf(User::class, $causer); + $this->assertSame($user->getKey(), $causer->getKey()); + } + + public function testResolvingASessionUserCanLogItsRetrievedEvent(): void + { + config(['auth.providers.users.model' => LoggedAccessUser::class]); + $guard = Auth::guard('web'); + $guard->getSession()->put($guard->getName(), 1); + + $activity = activity()->log('manual'); + + $this->assertSame(1, $activity->causer_id); + $this->assertNull(Activity::query()->where('event', 'retrieved')->sole()->causer_id); + } + + public function testReportsTheGuardWhenTheAuthenticatedUserIsNotAnEloquentModel(): void + { + Auth::login(new GenericUser([ + 'id' => 1, + 'password' => null, + 'remember_token' => null, + ])); + + $this->expectException(CouldNotLogActivity::class); + $this->expectExceptionMessage( + 'The [web] auth guard returned [Hypervel\Auth\GenericUser]; activity causers must be Eloquent models.', + ); + + $this->resolver()->resolve(); + } + + public function testWillThrowAnExceptionIfItCannotResolveUserById(): void + { + $this->expectException(CouldNotLogActivity::class); + + $this->resolver()->resolve(9999); + } + + public function testCanResolveUserFromPassedId(): void + { + $causer = $this->resolver()->resolve(1); + + $this->assertInstanceOf(User::class, $causer); + $this->assertSame(1, $causer->getKey()); + } + + public function testWillResolveTheProvidedOverrideCallback(): void + { + $this->resolver()->resolveUsing( + static fn (): Article => Article::query()->firstOrFail(), + ); + + $causer = $this->resolver()->resolve(); + + $this->assertInstanceOf(Article::class, $causer); + $this->assertSame(1, $causer->getKey()); + } + + public function testExplicitCauserInsideResolutionUsesTheConfiguredMapper(): void + { + $user = User::query()->firstOrFail(); + $article = Article::query()->firstOrFail(); + + $this->resolver()->resolveUsing(static function ($subject) use ($user, $article) { + if ($subject === null) { + activity()->causedBy('mapped-actor')->log('inner'); + + return $user; + } + + return $subject === 'mapped-actor' ? $article : null; + }); + + $outer = activity()->log('outer'); + + $this->assertTrue($outer->causer->is($user)); + $this->assertTrue(Activity::query()->where('description', 'inner')->sole()->causer->is($article)); + } + + public function testWillResolveAnyModel(): void + { + $article = Article::query()->firstOrFail(); + + $causer = $this->resolver()->resolve($article); + + $this->assertInstanceOf(Article::class, $causer); + $this->assertSame($article->getKey(), $causer->getKey()); + } + + public function testCanScopeACauserUsingWithCauser(): void + { + $user = User::query()->firstOrFail(); + $resolver = $this->resolver(); + + $result = $resolver->withCauser( + $user, + static fn () => $resolver->resolve(), + ); + + $this->assertInstanceOf(User::class, $result); + $this->assertSame($user->getKey(), $result->getKey()); + } + + public function testRestoresThePreviousCauserAfterWithCauser(): void + { + $first = User::query()->firstOrFail(); + $second = User::query()->findOrFail(2); + $resolver = $this->resolver(); + + $resolver->setCauser($first); + + $resolver->withCauser($second, function () use ($resolver, $second): void { + $this->assertSame($second->getKey(), $resolver->resolve()?->getKey()); + }); + + $this->assertSame($first->getKey(), $resolver->resolve()?->getKey()); + } + + public function testRestoresThePreviousCauserWhenWithCauserThrows(): void + { + $first = User::query()->firstOrFail(); + $second = User::query()->findOrFail(2); + $resolver = $this->resolver(); + + $resolver->setCauser($first); + + try { + $failure = new RuntimeException('test'); + $resolver->withCauser($second, static fn (): never => throw $failure); + $this->fail('Expected the callback exception.'); + } catch (RuntimeException $exception) { + $this->assertSame($failure, $exception); + } + + $this->assertSame($first->getKey(), $resolver->resolve()?->getKey()); + } + + public function testSetCauserTakesPriorityOverResolveUsing(): void + { + $user = User::query()->firstOrFail(); + $article = Article::query()->firstOrFail(); + $resolver = $this->resolver(); + + $resolver->resolveUsing(static fn (): Article => $article); + $resolver->setCauser($user); + + $causer = $resolver->resolve(); + + $this->assertInstanceOf(User::class, $causer); + $this->assertSame($user->getKey(), $causer->getKey()); + } + + public function testCanSetADefaultCauserViaTheFacade(): void + { + $user = User::query()->firstOrFail(); + + ActivityLog::defaultCauser($user); + + activity()->log('test with default causer'); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(User::class, $activity->causer); + $this->assertSame($user->getKey(), $activity->causer?->getKey()); + } + + public function testCanScopeADefaultCauserViaTheFacadeWithACallback(): void + { + $user = User::query()->firstOrFail(); + + ActivityLog::defaultCauser($user, static function (): void { + activity()->log('scoped causer'); + }); + + $activity = Activity::query()->firstOrFail(); + + $this->assertInstanceOf(User::class, $activity->causer); + $this->assertSame($user->getKey(), $activity->causer?->getKey()); + } + + public function testRestoresThePreviousCauserAfterTheFacadeCallback(): void + { + $first = User::query()->firstOrFail(); + $second = User::query()->findOrFail(2); + + ActivityLog::defaultCauser($first); + + ActivityLog::defaultCauser($second, static function (): void { + activity()->log('inner'); + }); + + activity()->log('outer'); + + $activities = Activity::query()->orderBy('id')->get(); + + $this->assertSame($second->getKey(), $activities[0]->causer?->getKey()); + $this->assertSame($first->getKey(), $activities[1]->causer?->getKey()); + } + + /** + * Get the scoped causer resolver. + */ + protected function resolver(): CauserResolver + { + return $this->app->make(CauserResolver::class); + } +} + +class LoggedAccessUser extends User +{ + use LogsActivity; + + protected static array $recordEvents = ['retrieved']; +} diff --git a/tests/ActivityLog/TestCase.php b/tests/ActivityLog/TestCase.php new file mode 100644 index 000000000..a359858dd --- /dev/null +++ b/tests/ActivityLog/TestCase.php @@ -0,0 +1,194 @@ + + */ + protected function getPackageProviders(Application $app): array + { + return [ + ActivityLogServiceProvider::class, + ]; + } + + /** + * Define the activity log test environment. + */ + protected function defineEnvironment(Application $app): void + { + $app->make('config')->set([ + 'app.key' => 'base64:' . base64_encode(str_repeat('a', 32)), + 'auth.defaults.guard' => 'web', + 'auth.guards.web' => [ + 'driver' => 'session', + 'provider' => 'users', + ], + 'auth.providers.users' => [ + 'driver' => 'eloquent', + 'model' => User::class, + ], + 'database.default' => 'sqlite', + 'database.connections.sqlite' => [ + 'driver' => 'sqlite', + 'database' => ':memory:', + ], + 'database.connections.custom_connection_name' => [ + 'driver' => 'sqlite', + 'database' => ':memory:', + ], + ]); + } + + /** + * Prepare the activity log fixture database. + */ + protected function setUpInCoroutine(): void + { + $this->setUpDatabase(); + } + + /** + * Remove the activity log fixture database. + */ + protected function tearDownInCoroutine(): void + { + ActivityBuffer::finalizeCurrent(); + + Schema::dropIfExists('articles'); + Schema::dropIfExists('users'); + Schema::dropIfExists('activity_log'); + } + + /** + * Set up the activity log fixture database. + */ + protected function setUpDatabase(): void + { + $this->migrateActivityLogTable(); + + $this->createTables('users', 'articles'); + $this->seedModels(Article::class, User::class); + } + + /** + * Run the publish-only activity log migration. + */ + protected function migrateActivityLogTable(): void + { + /** @var Migration $migration */ + $migration = require dirname(__DIR__, 2) + . '/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php'; + + $migration->up(); + } + + /** + * Create fixture tables. + */ + protected function createTables(string ...$tableNames): void + { + foreach ($tableNames as $tableName) { + Schema::create($tableName, function (Blueprint $table) use ($tableName): void { + $table->increments('id'); + $table->string('name')->nullable(); + $table->string('text')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + if ($tableName === 'articles') { + $table->integer('user_id')->unsigned()->nullable(); + $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + $table->text('json')->nullable(); + $table->string('interval')->nullable(); + $table->decimal('price')->nullable(); + $table->string('status')->nullable(); + } + }); + } + } + + /** + * Seed fixture models. + * + * @param class-string ...$modelClasses + */ + protected function seedModels(string ...$modelClasses): void + { + foreach ($modelClasses as $modelClass) { + foreach ([1, 0] as $index) { + $modelClass::create(['name' => "name {$index}"]); + } + } + } + + /** + * Get the most recently created activity. + */ + public function getLastActivity(): ?Activity + { + $activity = new Activity; + + return $activity->newQuery() + ->orderByDesc($activity->getKeyName()) + ->first(); + } + + /** + * Get the most recently created activity or fail. + */ + protected function lastActivity(): Activity + { + $activity = $this->getLastActivity(); + + $this->assertNotNull($activity); + + return $activity; + } + + /** + * Create an article using the active test fixture class. + */ + public function createArticle(): Article + { + $article = new $this->article; + $article->setAttribute('name', 'my name'); + $article->save(); + + return $article; + } + + /** + * Authenticate a new fixture user. + */ + public function loginWithFakeUser(): User + { + $user = new $this->user; + + $this->be($user); + + return $user; + } +} diff --git a/tests/ActivityLog/Testing/TestStateTest.php b/tests/ActivityLog/Testing/TestStateTest.php new file mode 100644 index 000000000..cdcc4f8c1 --- /dev/null +++ b/tests/ActivityLog/Testing/TestStateTest.php @@ -0,0 +1,112 @@ + $properties */ + $properties = $activity->getAttribute('properties'); + + $activity->setAttribute('properties', $properties->put('callback', true)); + }); + ActivityLogger::macro('withTestMarker', function (): ActivityLogger { + return $this->withProperty('macro', true); + }); + + $beforeCleanup = activity()->withTestMarker()->log('before cleanup'); + + $this->assertNotNull($beforeCleanup); + $this->assertTrue(ActivityLogger::hasMacro('withTestMarker')); + $this->assertTrue($beforeCleanup->getProperty('callback')); + $this->assertTrue($beforeCleanup->getProperty('macro')); + + (new class extends AfterEachTestSubscriber { + public function flushActivityLogState(): void + { + parent::flushActivityLogState(); + } + })->flushActivityLogState(); + + $afterCleanup = activity()->log('after cleanup'); + + $this->assertNotNull($afterCleanup); + $this->assertFalse(ActivityLogger::hasMacro('withTestMarker')); + $this->assertNull($afterCleanup->getProperty('callback')); + $this->assertNull($afterCleanup->getProperty('macro')); + } + + public function testBeforeLoggingCallbacksRunInRegistrationOrder(): void + { + $steps = []; + LogActivityAction::beforeLogging(static function () use (&$steps): void { + $steps[] = 'first'; + }); + LogActivityAction::beforeLogging(static function () use (&$steps): void { + $steps[] = 'second'; + }); + + activity()->log('ordered callbacks'); + + $this->assertSame(['first', 'second'], $steps); + } + + public function testApplicationBatchUuidIsScopedToEachCoroutine(): void + { + LogActivityAction::beforeLogging(static function (ActivityContract&Model $activity): void { + $batchUuid = CoroutineContext::getOrSet( + '__app.activity-batch-uuid', + static fn (): string => (string) Str::uuid7(), + ); + /** @var Collection $properties */ + $properties = $activity->getAttribute('properties'); + + $activity->setAttribute('properties', $properties->put('batch_uuid', $batchUuid)); + }); + + $batchUuids = parallel([ + 'first request' => static function (): array { + $first = activity()->log('first request, first activity'); + $second = activity()->log('first request, second activity'); + + return [ + $first?->getProperty('batch_uuid'), + $second?->getProperty('batch_uuid'), + ]; + }, + 'second request' => static function (): array { + $activity = activity()->log('second request activity'); + + return [$activity?->getProperty('batch_uuid')]; + }, + ], concurrent: 1); + + $this->assertIsString($batchUuids['first request'][0]); + $this->assertIsString($batchUuids['first request'][1]); + $this->assertIsString($batchUuids['second request'][0]); + $this->assertSame( + $batchUuids['first request'][0], + $batchUuids['first request'][1], + ); + $this->assertNotSame( + $batchUuids['first request'][0], + $batchUuids['second request'][0], + ); + } +} diff --git a/tests/ActivityLog/Traits/CausesActivityTest.php b/tests/ActivityLog/Traits/CausesActivityTest.php new file mode 100644 index 000000000..952186125 --- /dev/null +++ b/tests/ActivityLog/Traits/CausesActivityTest.php @@ -0,0 +1,21 @@ +firstOrFail(); + + activity()->by($causer)->log('perform activity'); + activity()->by($causer)->log('perform another activity'); + + $this->assertCount(2, $causer->activitiesAsCauser); + } +} diff --git a/tests/ActivityLog/Traits/DetectsChangesRegressionTest.php b/tests/ActivityLog/Traits/DetectsChangesRegressionTest.php new file mode 100644 index 000000000..ad07d27b1 --- /dev/null +++ b/tests/ActivityLog/Traits/DetectsChangesRegressionTest.php @@ -0,0 +1,1488 @@ +logOnly(['name', 'text']); + } + }; + + $connection = $articleClass->getConnection(); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + + try { + $article = $articleClass::query()->create([ + 'name' => 'original', + 'text' => 'before', + ]); + $createQueries = $connection->getQueryLog(); + + $connection->flushQueryLog(); + $article->update([ + 'name' => 'updated', + 'text' => 'after', + ]); + $updateQueries = $connection->getQueryLog(); + } finally { + $connection->disableQueryLog(); + $connection->flushQueryLog(); + } + + $subjectSelects = static fn (array $queries): array => array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with(strtolower($query['query']), 'select') + && str_contains(strtolower($query['query']), 'articles'), + )); + + $this->assertSame([], $subjectSelects($createQueries)); + $this->assertSame([], $subjectSelects($updateQueries)); + $this->assertSame([ + 'attributes' => [ + 'name' => 'updated', + 'text' => 'after', + ], + 'old' => [ + 'name' => 'original', + 'text' => 'before', + ], + ], $this->getLastActivity()?->attribute_changes?->toArray()); + } + + public function testRefreshBeforeLoggingRequiresAnExistingWriteTransaction(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public bool $refreshActivity = false; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + $options = LogOptions::defaults()->logOnly(['name']); + + return $this->refreshActivity + ? $options->refreshBeforeLogging() + : $options; + } + }; + + $article = $articleClass::query()->create(['name' => 'original']); + $article->refreshActivity = true; + $article->setAttribute('name', 'updated'); + + $this->expectException(CouldNotLogActivity::class); + $this->expectExceptionMessage( + 'Refreshing [' . $article::class . '] before activity logging requires an active transaction. ' + . 'Use saveOrFail() for saves, or wrap the write, including restore(), in DB::transaction().', + ); + + $article->save(); + } + + public function testRefreshBeforeLoggingSelectsTheSubjectExactlyOnceInsideTheWriteTransaction(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public bool $refreshActivity = false; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + $options = LogOptions::defaults()->logOnly(['name']); + + return $this->refreshActivity + ? $options->refreshBeforeLogging() + : $options; + } + }; + + $article = $articleClass::query()->create(['name' => 'original']); + $article->refreshActivity = true; + $article->setAttribute('name', 'updated'); + $connection = $article->getConnection(); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + + try { + $connection->transaction(static fn (): bool => $article->save()); + $queries = $connection->getQueryLog(); + } finally { + $connection->disableQueryLog(); + $connection->flushQueryLog(); + } + + $subjectSelects = array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with(strtolower($query['query']), 'select') + && str_contains(strtolower($query['query']), 'articles'), + )); + + $this->assertCount(1, $subjectSelects); + $this->assertSame([ + 'attributes' => ['name' => 'updated'], + 'old' => ['name' => 'original'], + ], $this->getLastActivity()?->attribute_changes?->toArray()); + } + + public function testOldSnapshotPreservesRuntimeConnectionAndTableSettings(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['name', 'runtime_context']); + } + + /** + * Get the runtime persistence target used by this instance. + */ + public function getRuntimeContextAttribute(): string + { + return $this->getConnectionName() . ':' . $this->getTable(); + } + }; + + $article = new $articleClass; + $article->setConnection('sqlite'); + $article->setTable('articles'); + $article->setAttribute('name', 'original'); + $article->save(); + + $article->setAttribute('name', 'updated'); + $article->save(); + + $this->assertSame([ + 'attributes' => [ + 'name' => 'updated', + 'runtime_context' => 'sqlite:articles', + ], + 'old' => [ + 'name' => 'original', + 'runtime_context' => 'sqlite:articles', + ], + ], $this->getLastActivity()?->attribute_changes?->toArray()); + } + + #[DataProvider('cachedClassCastProviders')] + public function testCachedClassCastExtractionPreservesTheSubject( + string $castClass, + ): void { + $article = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['json', 'missing']); + } + + /** + * Get the raw attributes without merging cached casts. + * + * @return array + */ + public function rawAttributesForTest(): array + { + return $this->attributes; + } + }; + $article->mergeCasts(['json' => $castClass]); + $article->setRawAttributes([ + 'name' => 'subject', + 'json' => '{"value":"before"}', + ], sync: true); + $user = User::query()->create(['name' => 'owner']); + $article->setRelation('user', $user); + + $value = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $value); + $value['value'] = 'after'; + + $rawBefore = $article->rawAttributesForTest(); + $originalBefore = $article->getRawOriginal(); + $relationsBefore = $article->getRelations(); + $dirtyBefore = (clone $article)->getDirty(); + + $changes = $article::extractChanges($article); + + $this->assertInstanceOf(ArrayObject::class, $changes['json']); + $this->assertSame('after', $changes['json']['value']); + $this->assertNull($changes['missing']); + $this->assertSame($rawBefore, $article->rawAttributesForTest()); + $this->assertSame($originalBefore, $article->getRawOriginal()); + $this->assertSame($relationsBefore, $article->getRelations()); + $this->assertSame($dirtyBefore, (clone $article)->getDirty()); + $this->assertArrayNotHasKey('missing', $article->rawAttributesForTest()); + } + + /** + * Provide class casts that return the two supported setter response shapes. + * + * @return iterable}> + */ + public static function cachedClassCastProviders(): iterable + { + yield 'array response' => [ActivityLogArrayResponseCast::class]; + yield 'string response' => [ActivityLogStringResponseCast::class]; + } + + public function testCachedModernAttributeExtractionPreservesTheSubject(): void + { + $article = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['json']); + } + + /** + * Get the raw attributes without merging cached attributes. + * + * @return array + */ + public function rawAttributesForTest(): array + { + return $this->attributes; + } + + /** + * Cast the JSON payload as a cached mutable object. + */ + protected function json(): Attribute + { + return Attribute::make( + get: static fn (string $value): ArrayObject => new ArrayObject( + json_decode($value, true, flags: JSON_THROW_ON_ERROR), + ArrayObject::ARRAY_AS_PROPS, + ), + set: static fn (ArrayObject $value): string => json_encode( + $value->getArrayCopy(), + JSON_THROW_ON_ERROR, + ), + ); + } + }; + $article->setRawAttributes([ + 'name' => 'subject', + 'json' => '{"value":"before"}', + ], sync: true); + + $value = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $value); + $value['value'] = 'after'; + $rawBefore = $article->rawAttributesForTest(); + + $changes = $article::extractChanges($article); + + $this->assertInstanceOf(ArrayObject::class, $changes['json']); + $this->assertSame('after', $changes['json']['value']); + $this->assertSame($rawBefore, $article->rawAttributesForTest()); + } + + public function testWildcardKeepsTheFullJsonValueWhenASubpathIsSelected(): void + { + $article = new class extends Article { + use LogsActivity; + + protected array $casts = ['json' => 'array']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['*', 'json->data'])->logOnlyDirty()->dontLogEmptyChanges(); + } + }; + $article->fill(['json' => ['data' => 1, 'extra' => 2]])->save(); + $article->update(['json' => ['data' => 1, 'extra' => 3]]); + + $activity = $this->lastActivity(); + $this->assertSame('updated', $activity->event); + $this->assertSame(['data' => 1, 'extra' => 3], $activity->attribute_changes['attributes']['json']); + $this->assertSame(['data' => 1, 'extra' => 2], $activity->attribute_changes['old']['json']); + } + + public function testJsonPathUsesTheNormalizedCachedClassCast(): void + { + $article = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['json->nested->value']); + } + + /** + * Get the raw attributes without merging cached casts. + * + * @return array + */ + public function rawAttributesForTest(): array + { + return $this->attributes; + } + }; + $article->mergeCasts(['json' => ActivityLogArrayResponseCast::class]); + $article->setRawAttributes([ + 'json' => '{"nested":{"value":"before"}}', + ], sync: true); + + $value = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $value); + $value['nested']['value'] = 'after'; + $rawBefore = $article->rawAttributesForTest(); + + $this->assertSame([ + 'json' => [ + 'nested' => ['value' => 'after'], + ], + ], $article::extractChanges($article)); + $this->assertSame($rawBefore, $article->rawAttributesForTest()); + } + + public function testAutomaticChangesUseTheResolvedSnapshotAndExtractorForBothSides(): void + { + $article = new class extends Article { + use LogsActivity { + extractChanges as private extractSelectedChanges; + } + + protected bool $selected = false; + + public ?self $retainedSnapshot = null; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->useLogName($this->selected ? 'snapshot' : 'event'); + } + + public function attributesToBeLogged(): array + { + return $this->selected ? ['name'] : []; + } + + protected function resolveModelForLogging(string $processingEvent): static + { + $this->retainedSnapshot = (new self)->setRawAttributes($this->getAttributes()); + $this->retainedSnapshot->selected = true; + + return $this->retainedSnapshot; + } + + public static function extractChanges(Model $model): array + { + $attributes = self::extractSelectedChanges($model); + + return ['redacted' => strlen($attributes['name'])]; + } + }; + + $article->name = 'before'; + $article->save(); + $article->update(['name' => 'after']); + $this->assertSame('snapshot', $article->retainedSnapshot->getLogNameToUse()); + + $this->assertSame([ + 'attributes' => ['redacted' => 5], + 'old' => ['redacted' => 6], + ], $this->lastActivity()->attribute_changes->all()); + } + + public function testRawEnumAndDateFieldsKeepTheirStoredRepresentation(): void + { + $article = new class extends Article { + use LogsActivity; + + protected function casts(): array + { + return ['status' => StringBackedEnum::class, 'updated_at' => 'datetime:Y-m-d']; + } + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['status', 'updated_at'])->useAttributeRawValues(['status', 'updated_at']); + } + }; + $article->setAttribute('status', StringBackedEnum::Published); + $article->save(); + + $this->assertSame([ + 'status' => 'published', + 'updated_at' => $article->getRawOriginal('updated_at'), + ], $this->lastActivity()->attribute_changes->get('attributes')); + } + + /** + * @param class-string $mappedItem + */ + #[DataProvider('mappedCollectionItems')] + public function testDirtyLoggingPreservesStringAndJsonScalarTypes(string $mappedItem): void + { + $article = new class extends Article { + use LogsActivity; + + public array $selected = ['name', 'json', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly($this->selected)->logOnlyDirty(); + } + }; + $article->mergeCasts(['json' => 'object', 'text' => AsCollection::of($mappedItem)]); + $article->fill(['name' => '01', 'json' => [['n' => 1]], 'text' => [['n' => 1]]])->save(); + $article->update(['name' => '1']); + $this->assertSame([ + 'attributes' => ['name' => '1'], + 'old' => ['name' => '01'], + ], $this->lastActivity()->attribute_changes->all()); + + $article->update(['json' => [['n' => '1']], 'text' => [['n' => '1']]]); + + $this->assertSame([ + 'attributes' => ['json' => [['n' => '1']], 'text' => [['n' => '1']]], + 'old' => ['json' => [['n' => 1]], 'text' => [['n' => 1]]], + ], $this->lastActivity()->attribute_changes->all()); + + $article->selected = ['text->0->n']; + $this->assertSame(['text' => [['n' => '1']]], $article::extractChanges($article)); + } + + /** + * @return iterable + */ + public static function mappedCollectionItems(): iterable + { + yield 'JSON serializable' => [Fluent::class]; + yield 'public field' => [ActivityLogPublicItem::class]; + yield 'arrayable' => [ActivityLogArrayableItem::class]; + } + + public function testTypedAccessorResultsKeepTheirEnumAndDateFormats(): void + { + $article = new class extends Article { + use LogsActivity; + + protected array $casts = ['status' => NonBackedEnum::class, 'updated_at' => 'immutable_datetime:Y-m-d']; + + public function getStatusAttribute(): NonBackedEnum + { + return NonBackedEnum::Published; + } + + protected function updatedAt(): Attribute + { + return Attribute::get(static fn () => CarbonImmutable::parse('2026-12-01 12:00:00')); + } + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['status', 'updated_at']); + } + }; + + $this->assertSame(['status' => 'Published', 'updated_at' => '2026-12-01'], $article::extractChanges($article)); + } + + public function testEnumContainersUseTheirCastSerializerForWholeValuesAndPaths(): void + { + $draft = User::query()->forceCreate(['text' => '["Draft"]']); + $published = User::query()->forceCreate(['text' => '["Published"]']); + $article = new class extends Article { + use LogsActivity; + + protected static array $recordEvents = ['updated']; + + protected function casts(): array + { + return [ + 'json' => AsEnumCollection::of(NonBackedEnum::class), + 'text' => AsEnumArrayObject::of(NonBackedEnum::class), + ]; + } + + public function user(): BelongsTo + { + return parent::user()->withCasts(['text' => AsEnumCollection::of(NonBackedEnum::class)]); + } + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['json', 'text->0', 'user.text'])->logOnlyDirty()->dontLogEmptyChanges(); + } + }; + $article->fill(['json' => [NonBackedEnum::Draft], 'text' => [NonBackedEnum::Draft], 'user_id' => $draft->getKey()])->save(); + $article->update(['name' => 'unrelated']); + $this->assertSame(0, Activity::query()->count()); + + $article->update(['json' => [NonBackedEnum::Published], 'text' => [NonBackedEnum::Published], 'user_id' => $published->getKey()]); + + $this->assertSame([ + 'attributes' => ['json' => ['Published'], 'text' => ['Published'], 'user.text' => ['Published']], + 'old' => ['json' => ['Draft'], 'text' => ['Draft'], 'user.text' => ['Draft']], + ], $this->lastActivity()->attribute_changes->all()); + } + + public function testDirectSaveClearingDeletedAtIsLoggedAndPartialRestoreIsLoggedOnce(): void + { + $article = new class extends Article { + use LogsActivity; + use SoftDeletes; + }; + $article->name = 'record'; + $article->save(); + $article->delete(); + $article->update(['deleted_at' => null, 'name' => 'changed']); + $this->assertSame('updated', $this->lastActivity()->event); + + $article->delete(); + $partial = $article->newQuery()->onlyTrashed()->select(['id', 'name'])->findOrFail($article->getKey()); + Activity::query()->delete(); + $partial->restore(); + + $this->assertSame(['restored'], Activity::query()->pluck('event')->all()); + } + + public function testEncryptedRawCreateAndUpdateValuesMatchThePersistedRow(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => AsEncryptedArrayObject::class, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['json']) + ->logOnlyDirty() + ->useAttributeRawValues(['json']); + } + }; + + $article = $articleClass::query()->create([ + 'name' => 'subject', + 'json' => ['value' => 'created'], + ]); + $storedCreateValue = $article->newQuery() + ->whereKey($article->getKey()) + ->toBase() + ->value('json'); + + $this->assertIsString($storedCreateValue); + $this->assertSame( + $storedCreateValue, + $this->getLastActivity()?->attribute_changes?->get('attributes')['json'] ?? null, + ); + + $article = $article->fresh(); + $this->assertNotNull($article); + $value = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $value); + $value['value'] = 'updated'; + $article->save(); + $storedUpdateValue = $article->newQuery() + ->whereKey($article->getKey()) + ->toBase() + ->value('json'); + + $this->assertIsString($storedUpdateValue); + $this->assertSame( + $storedUpdateValue, + $this->getLastActivity()?->attribute_changes?->get('attributes')['json'] ?? null, + ); + $this->assertNotSame($storedCreateValue, $storedUpdateValue); + } + + public function testActivityPreparationDoesNotMergeCachedCastsOntoTheLiveSubject(): void + { + ActivityLogCountingCast::reset(); + + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => ActivityLogCountingCast::class, + ]; + + /** @var array */ + public array $activityPreparationCalls = []; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['json']); + } + + /** + * Record the live-model setter count before change extraction. + */ + public function getDescriptionForEvent(string $eventName): string + { + $this->activityPreparationCalls[$eventName]['before'] + = ActivityLogCountingCast::callsFor($this); + + return $eventName; + } + + /** + * Record the live-model setter count after change extraction. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $this->activityPreparationCalls[$eventName]['after'] + = ActivityLogCountingCast::callsFor($this); + } + }; + $article = new $articleClass; + $article->setRawAttributes([ + 'name' => 'subject', + 'json' => '{"value":"created"}', + ]); + $createdValue = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $createdValue); + $createdValue['value'] = 'created and mutated'; + + $article->save(); + + $this->assertSame( + $article->activityPreparationCalls['created']['before'], + $article->activityPreparationCalls['created']['after'], + ); + + $updatedValue = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $updatedValue); + $updatedValue['value'] = 'updated'; + $article->save(); + + $this->assertSame( + $article->activityPreparationCalls['updated']['before'], + $article->activityPreparationCalls['updated']['after'], + ); + } + + public function testRestoredRawValueUsesTheWriteSnapshotAfterFinishSaveMerges(): void + { + $articleClass = new class extends Article { + use LogsActivity; + use SoftDeletes; + + protected array $casts = [ + 'json' => AsEncryptedArrayObject::class, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['json']) + ->useAttributeRawValues(['json']); + } + + /** + * Get the raw attributes without merging cached casts. + * + * @return array + */ + public function rawAttributesForTest(): array + { + return $this->attributes; + } + }; + + $article = $articleClass::query()->create([ + 'name' => 'subject', + 'json' => ['value' => 'created'], + ]); + $article->delete(); + $value = $article->getAttribute('json'); + $this->assertInstanceOf(ArrayObject::class, $value); + $value['value'] = 'restored'; + + $article->restore(); + + $storedValue = $article->newQuery() + ->whereKey($article->getKey()) + ->toBase() + ->value('json'); + $liveRawValue = $article->rawAttributesForTest()['json']; + $loggedValue = $this->getLastActivity()?->attribute_changes?->get('attributes')['json'] ?? null; + + $this->assertIsString($storedValue); + $this->assertIsString($liveRawValue); + $this->assertNotSame($storedValue, $liveRawValue); + $this->assertSame($storedValue, $loggedValue); + $this->assertSame(ActivityEvent::Restored->value, $this->getLastActivity()?->event); + } + + public function testRestoredRefreshTakesPrecedenceOverTheLogicalWriteSnapshot(): void + { + $articleClass = new class extends Article { + use LogsActivity; + use SoftDeletes; + + protected static array $recordEvents = [ + 'created', + 'updated', + 'deleted', + 'restored', + 'retrieved', + ]; + + public bool $refreshActivity = false; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + $options = LogOptions::defaults() + ->logOnly(['text']) + ->useAttributeRawValues(['text']); + + return $this->refreshActivity + ? $options->refreshBeforeLogging() + : $options; + } + + /** + * Transform statement values without changing logical model values. + * + * @return array + */ + protected function getDirtyForUpdate(): array + { + $dirty = parent::getDirtyForUpdate(); + + if (array_key_exists('text', $dirty)) { + $dirty['text'] = 'database:' . $dirty['text']; + } + + return $dirty; + } + }; + + $article = $articleClass::query()->create([ + 'name' => 'subject', + 'text' => 'original', + ]); + $article->delete(); + Activity::query()->delete(); + $article->setAttribute('text', 'restored'); + $article->refreshActivity = true; + + $article->getConnection()->transaction(static fn (): bool => $article->restore()); + + $this->assertSame(1, Activity::query()->count()); + $this->assertSame(ActivityEvent::Restored->value, $this->getLastActivity()?->event); + $this->assertSame( + 'database:restored', + $this->getLastActivity()?->attribute_changes?->get('attributes')['text'] ?? null, + ); + } + + public function testRestoreEmitsOnlyTheRestoredActivity(): void + { + $articleClass = new class extends Article { + use LogsActivity; + use SoftDeletes; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['name', 'deleted_at']); + } + }; + + $article = $articleClass::query()->create(['name' => 'subject']); + $article->delete(); + Activity::query()->delete(); + + $article->restore(); + + $this->assertSame(1, Activity::query()->count()); + $this->assertSame(ActivityEvent::Restored->value, $this->getLastActivity()?->event); + } + + public function testRetrievedEventUsesTheTypedActivityEventValue(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected static array $recordEvents = [ + ActivityEvent::Retrieved->value, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['name']); + } + }; + $article = $articleClass::withoutEvents( + static fn () => $articleClass::query()->create(['name' => 'subject']), + ); + + $retrieved = $articleClass::query()->findOrFail($article->getKey()); + + $this->assertSame('subject', $retrieved->getAttribute('name')); + $this->assertSame(ActivityEvent::Retrieved->value, $this->getLastActivity()?->event); + } + + public function testWildcardRefreshIncludesDatabaseDefaultsMissingFromTheEventModel(): void + { + Schema::table('articles', static function (Blueprint $table): void { + $table->string('database_value')->default('database default'); + }); + + $articleClass = new class extends Article { + use LogsActivity; + + public bool $refreshActivity = false; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + $options = LogOptions::defaults()->logAll(); + + return $this->refreshActivity + ? $options->refreshBeforeLogging() + : $options; + } + }; + + $eventSnapshot = $articleClass::query()->create(['name' => 'event snapshot']); + $eventChanges = $this->getLastActivity()?->attribute_changes?->toArray(); + $this->assertArrayNotHasKey('database_value', $eventChanges['attributes'] ?? []); + + $refreshed = new $articleClass; + $refreshed->refreshActivity = true; + $refreshed->setAttribute('name', 'refreshed snapshot'); + $refreshed->getConnection()->transaction(static fn (): bool => $refreshed->save()); + + $this->assertNotNull($eventSnapshot->getKey()); + $this->assertSame( + 'database default', + $this->getLastActivity()?->attribute_changes?->get('attributes')['database_value'] ?? null, + ); + } + + public function testPartialUpdateRefreshDocumentsUnavailableOldValues(): void + { + Model::preventAccessingMissingAttributes(); + $articleClass = new class extends Article { + use LogsActivity; + + public bool $refreshActivity = false; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + $options = LogOptions::defaults() + ->logAll() + ->logOnlyDirty(); + + return $this->refreshActivity + ? $options->refreshBeforeLogging() + : $options; + } + }; + $stored = $articleClass::query()->create([ + 'name' => 'original', + 'text' => 'not selected before the update', + ]); + Activity::query()->delete(); + + $article = $articleClass::query() + ->select(['id', 'name']) + ->findOrFail($stored->getKey()); + $article->refreshActivity = true; + $article->setAttribute('name', 'updated'); + $article->getConnection()->transaction(static fn (): bool => $article->save()); + $changes = $this->getLastActivity()?->attribute_changes?->toArray(); + + $this->assertSame( + 'not selected before the update', + $changes['attributes']['text'] ?? null, + ); + $this->assertArrayHasKey('text', $changes['old']); + $this->assertNull($changes['old']['text']); + } + + public function testReadButUnwrittenCachedRawValueUsesTheEventSnapshot(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public ?string $eventRawValue = null; + + protected array $casts = [ + 'json' => AsEncryptedArrayObject::class, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'json']) + ->useAttributeRawValues(['json']); + } + + /** + * Get the raw attributes without merging cached casts. + * + * @return array + */ + public function rawAttributesForTest(): array + { + return $this->attributes; + } + + /** + * Capture the raw value at the activity event boundary. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + if ($eventName === ActivityEvent::Updated->value) { + $this->eventRawValue = $this->attributes['json']; + } + } + }; + $article = $articleClass::query()->create([ + 'name' => 'original', + 'json' => ['value' => 'unchanged'], + ])->fresh(); + $this->assertNotNull($article); + $this->assertInstanceOf(ArrayObject::class, $article->getAttribute('json')); + $article->setAttribute('name', 'updated'); + + $article->save(); + + $postSaveRawValue = $article->rawAttributesForTest()['json']; + $loggedRawValue = $this->getLastActivity()?->attribute_changes?->get('attributes')['json'] ?? null; + $storedRawValue = $article->newQuery() + ->whereKey($article->getKey()) + ->toBase() + ->value('json'); + + $this->assertIsString($article->eventRawValue); + $this->assertIsString($postSaveRawValue); + $this->assertSame($article->eventRawValue, $loggedRawValue); + $this->assertNotSame($storedRawValue, $article->eventRawValue); + $this->assertNotSame($article->eventRawValue, $postSaveRawValue); + } + + public function testEventOptionsAreEvaluatedOnceAndTransientStateAlwaysClears(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public string $testMode = 'success'; + + public int $optionsEvaluations = 0; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + ++$this->optionsEvaluations; + + $options = LogOptions::defaults()->logOnly(['name']); + + return match ($this->testMode) { + 'empty changes' => $options->logOnly([])->dontLogEmptyChanges(), + 'refresh exception' => $options->refreshBeforeLogging(), + default => $options, + }; + } + + /** + * Get the activity description for an event. + */ + public function getDescriptionForEvent(string $eventName): string + { + return $this->testMode === 'empty description' ? '' : $eventName; + } + + /** + * Get transient activity state for this test. + * + * @return array{null|LogOptions, null|list} + */ + public function transientActivityStateForTest(): array + { + return [$this->activityLogOptions, $this->activityLogAttributes]; + } + }; + + $disabled = new $articleClass; + $disabled->disableLogging(); + $disabled->setAttribute('name', 'disabled'); + $disabled->save(); + $this->assertSame(1, $disabled->optionsEvaluations); + $this->assertSame([null, null], $disabled->transientActivityStateForTest()); + + $emptyDescription = new $articleClass; + $emptyDescription->testMode = 'empty description'; + $emptyDescription->setAttribute('name', 'empty description'); + $emptyDescription->save(); + $this->assertSame(1, $emptyDescription->optionsEvaluations); + $this->assertSame([null, null], $emptyDescription->transientActivityStateForTest()); + + $emptyChanges = new $articleClass; + $emptyChanges->testMode = 'empty changes'; + $emptyChanges->setAttribute('name', 'empty changes'); + $emptyChanges->save(); + $this->assertSame(1, $emptyChanges->optionsEvaluations); + $this->assertSame([null, null], $emptyChanges->transientActivityStateForTest()); + + $refreshException = new $articleClass; + $refreshException->testMode = 'refresh exception'; + $refreshException->setAttribute('name', 'refresh exception'); + + try { + $refreshException->save(); + $this->fail('Expected refresh-before-logging to require a transaction.'); + } catch (CouldNotLogActivity) { + $this->assertSame(1, $refreshException->optionsEvaluations); + $this->assertSame([null, null], $refreshException->transientActivityStateForTest()); + } + + $success = new $articleClass; + $success->setAttribute('name', 'success'); + $success->save(); + $this->assertSame(1, $success->optionsEvaluations); + $this->assertSame([null, null], $success->transientActivityStateForTest()); + } + + public function testRefreshOptionDoesNotRefreshDeletedRetrievedOrCustomEvents(): void + { + $articleClass = new class extends Article { + use LogsActivity; + use SoftDeletes; + + protected static array $recordEvents = [ + 'saved', + 'deleted', + 'retrieved', + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name']) + ->refreshBeforeLogging(); + } + }; + + $article = $articleClass::query()->create(['name' => 'subject']); + $article->delete(); + $articleClass::withTrashed()->findOrFail($article->getKey()); + + $this->assertSame( + ['saved', 'deleted', ActivityEvent::Retrieved->value], + Activity::query()->orderBy('id')->pluck('event')->all(), + ); + } + + public function testPartialSnapshotWithAnUnselectedForeignKeyRecordsAnUnknownRelation(): void + { + Model::preventAccessingMissingAttributes(); + $subject = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['user.name']); + } + }; + $subject->name = 'initial'; + $subject->save(); + $projected = $subject->newQuery()->select(['id', 'name'])->findOrFail($subject->getKey()); + $projected->update(['name' => 'current side missing']); + $this->assertSame(['user.name' => null], $this->lastActivity()->attribute_changes->get('attributes')); + + $user = User::query()->firstOrFail(); + $projected->update(['user_id' => $user->getKey()]); + + $this->assertSame([ + 'attributes' => ['user.name' => $user->name], + 'old' => ['user.name' => null], + ], $this->lastActivity()->attribute_changes->all()); + } + + public function testProjectedMorphRelationNeedsItsTypeToRecordARelatedValue(): void + { + Model::preventAccessingMissingAttributes(); + $article = new class extends Article { + public function target(): MorphTo + { + return $this->morphTo('target', 'status', 'user_id', 'id'); + } + }; + $user = User::query()->firstOrFail(); + $article->newQuery()->whereKey($user->getKey())->update([ + 'name' => 'source article', + 'status' => $user->getMorphClass(), + 'user_id' => $user->getKey(), + ]); + $complete = $article->newQuery()->findOrFail($user->getKey()); + $projected = $article->newQuery()->select('id', 'user_id')->findOrFail($user->getKey()); + + $idOnly = $article->newQuery()->select('id')->findOrFail($user->getKey()); + $this->assertSame(['target.name' => null], ChangeDetector::resolveRelatedAttribute($idOnly, 'target.name')); + + $expected = ['target.name' => $user->name]; + $this->assertSame($expected, ChangeDetector::resolveRelatedAttribute($complete, 'target.name')); + $this->assertSame(['target.name' => null], ChangeDetector::resolveRelatedAttribute($projected, 'target.name')); + $projected->setRelation('target', $user); + $this->assertSame($expected, ChangeDetector::resolveRelatedAttribute($projected, 'target.name')); + } + + public function testNullableDirectRelationRetainsConfiguredKey(): void + { + $article = Article::query()->create(['name' => 'subject']); + + $this->assertSame( + ['user.name' => null], + ChangeDetector::resolveRelatedAttribute($article, 'user.name'), + ); + } + + public function testNullableIntermediateRelationRetainsEveryConfiguredSegment(): void + { + $article = Article::query()->create(['name' => 'subject']); + + $this->assertSame( + ['user.latest_article.name' => null], + ChangeDetector::resolveRelatedAttribute($article, 'user.latest_article.name'), + ); + } + + public function testDirtyRelationChangesPairCurrentNullWithOldValueUnderOneKey(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['user.latest_article.name']) + ->logOnlyDirty() + ->dontLogEmptyChanges(); + } + }; + + $user = User::query()->create(['name' => 'owner']); + // The relation must select the other article, not depend on a timestamp tie. + Article::query()->create([ + 'name' => 'related article', + 'user_id' => $user->getKey(), + 'created_at' => '2026-01-02 00:00:00', + ]); + $article = $articleClass::query()->create([ + 'name' => 'subject', + 'user_id' => $user->getKey(), + 'created_at' => '2026-01-01 00:00:00', + ]); + + $article = $article->fresh(); + $article->preventsLazyLoading = true; + $article->setAttribute('user_id', null); + Relation::noConstraintsForRelation(fn () => $article->save()); + + $this->assertSame([ + 'attributes' => [ + 'user.latest_article.name' => null, + ], + 'old' => [ + 'user.latest_article.name' => 'related article', + ], + ], $this->getLastActivity()?->attribute_changes?->toArray()); + } + + public function testNonnullMultilevelRelationRetainsConfiguredAliasSpelling(): void + { + $user = User::query()->create(['name' => 'owner']); + $article = Article::query()->create([ + 'name' => 'subject', + 'user_id' => $user->getKey(), + ]); + + $this->assertSame( + ['user.latest_article.name' => 'subject'], + ChangeDetector::resolveRelatedAttribute($article, 'user.latest_article.name'), + ); + } + + public function testDynamicRelationResolverSupportsAliasSpelling(): void + { + $articleClass = new class extends Article {}; + $articleClass::resolveRelationUsing( + 'dynamicUser', + static fn (Article $article) => $article->belongsTo(User::class, 'user_id'), + ); + + $user = User::query()->create(['name' => 'owner']); + $article = $articleClass::query()->create([ + 'name' => 'subject', + 'user_id' => $user->getKey(), + ]); + + $this->assertSame( + ['dynamic_user.name' => 'owner'], + ChangeDetector::resolveRelatedAttribute($article, 'dynamic_user.name'), + ); + } + + public function testBaseModelMethodIsNeverInvokedAsARelation(): void + { + $article = Article::query()->firstOrFail(); + + try { + ChangeDetector::resolveRelatedAttribute($article, 'delete.name'); + $this->fail('Expected an invalid relation path.'); + } catch (InvalidArgumentException $exception) { + $this->assertStringContainsString('delete.name', $exception->getMessage()); + } + + $this->assertNotNull($article->fresh()); + } + + public function testCustomMethodReturningAScalarIsRejectedAsARelation(): void + { + $article = new class extends Article { + public function author(): string + { + return 'editor'; + } + }; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('::author], which does not return an Eloquent relation.'); + ChangeDetector::resolveRelatedAttribute($article, 'author.name'); + } + + public function testUndefinedRelationThrowsPreciseException(): void + { + $article = Article::query()->create(['name' => 'subject']); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Activity log attribute [missing.name] references undefined relation [' + . Article::class . '::missing].', + ); + + ChangeDetector::resolveRelatedAttribute($article, 'missing.name'); + } + + public function testToManyRelationThrowsPreciseException(): void + { + $user = User::query()->create(['name' => 'owner']); + Article::query()->create([ + 'name' => 'related article', + 'user_id' => $user->getKey(), + ]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Activity log attribute [articles.name] must traverse singular Eloquent relations; [' + . Collection::class . '] returned by [' . User::class . '::articles].', + ); + + ChangeDetector::resolveRelatedAttribute($user, 'articles.name'); + } +} + +class ActivityLogPublicItem +{ + public int|string $n; + + /** @param array{n: int|string} $values */ + public function __construct(array $values) + { + $this->n = $values['n']; + } +} + +/** @implements Arrayable */ +class ActivityLogArrayableItem implements Arrayable +{ + /** @param array{n: int|string} $values */ + public function __construct(private array $values) + { + } + + public function toArray(): array + { + return $this->values; + } +} + +/** + * @implements CastsAttributes, ArrayObject> + */ +class ActivityLogArrayResponseCast implements CastsAttributes +{ + public function get(Model $model, string $key, mixed $value, array $attributes): ArrayObject + { + return new ArrayObject( + json_decode($value, true, flags: JSON_THROW_ON_ERROR), + ArrayObject::ARRAY_AS_PROPS, + ); + } + + /** + * @return array + */ + public function set(Model $model, string $key, mixed $value, array $attributes): array + { + return [$key => json_encode($value, JSON_THROW_ON_ERROR)]; + } +} + +/** + * @implements CastsAttributes, ArrayObject> + */ +class ActivityLogStringResponseCast implements CastsAttributes +{ + public function get(Model $model, string $key, mixed $value, array $attributes): ArrayObject + { + return new ArrayObject( + json_decode($value, true, flags: JSON_THROW_ON_ERROR), + ArrayObject::ARRAY_AS_PROPS, + ); + } + + public function set(Model $model, string $key, mixed $value, array $attributes): string + { + return json_encode($value, JSON_THROW_ON_ERROR); + } +} + +/** + * @implements CastsAttributes, ArrayObject> + */ +class ActivityLogCountingCast implements CastsAttributes +{ + /** @var array */ + protected static array $setCalls = []; + + public function get(Model $model, string $key, mixed $value, array $attributes): ArrayObject + { + return new ArrayObject( + json_decode($value, true, flags: JSON_THROW_ON_ERROR), + ArrayObject::ARRAY_AS_PROPS, + ); + } + + public function set(Model $model, string $key, mixed $value, array $attributes): string + { + $modelId = spl_object_id($model); + static::$setCalls[$modelId] = (static::$setCalls[$modelId] ?? 0) + 1; + + return json_encode($value, JSON_THROW_ON_ERROR); + } + + /** + * Get setter calls for one model instance. + */ + public static function callsFor(Model $model): int + { + return static::$setCalls[spl_object_id($model)] ?? 0; + } + + /** + * Reset the test counters. + */ + public static function reset(): void + { + static::$setCalls = []; + } +} diff --git a/tests/ActivityLog/Traits/DetectsChangesTest.php b/tests/ActivityLog/Traits/DetectsChangesTest.php new file mode 100644 index 000000000..4f348e90c --- /dev/null +++ b/tests/ActivityLog/Traits/DetectsChangesTest.php @@ -0,0 +1,1985 @@ +article = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text']); + } + }; + + $this->assertSame(0, Activity::query()->count()); + } + + /** + * Reset the test clock and fixture database. + */ + protected function tearDownInCoroutine(): void + { + try { + CarbonImmutable::setTestNow(null); + } finally { + parent::tearDownInCoroutine(); + } + } + + public function testCanStoreTheValuesWhenCreatingAModel(): void + { + $this->createArticle(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => null, + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testDetectsChangesForDateIntervalAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'interval' => IntervalCasts::class, + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'interval']) + ->logOnlyDirty(); + } + }; + + $article = $articleClass::create([ + 'name' => 'Hamburg', + 'interval' => CarbonInterval::minute(), + ]); + + $article->update(['name' => 'New name', 'interval' => CarbonInterval::month()]); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'New name', + 'interval' => '1 month', + ], + 'old' => [ + 'name' => 'Hamburg', + 'interval' => '1 minute', + ], + ]; + + // test case when intervals changing from interval to another + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testDetectsChangesForNullDateIntervalAttributes(): void + { + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'interval' => IntervalCasts::class, + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll() + ->dontLogIfAttributesChangedOnly(['created_at', 'updated_at', 'deleted_at']) + ->logOnlyDirty(); + } + }; + + $nullIntevalArticle = $articleClass::create([ + 'name' => 'Hamburg', + ]); + + $nullIntevalArticle->update(['name' => 'New name', 'interval' => CarbonInterval::month()]); + + $expectedChangesForNullInterval = [ + 'attributes' => [ + 'name' => 'New name', + 'interval' => '1 month', + ], + 'old' => [ + 'name' => 'Hamburg', + 'interval' => null, + ], + ]; + $this->assertEquals($expectedChangesForNullInterval, $this->getLastActivity()->attribute_changes->toArray()); + + $intervalArticle = $articleClass::create([ + 'name' => 'Hamburg', + 'interval' => CarbonInterval::month(), + ]); + + $intervalArticle->update(['name' => 'New name', 'interval' => null]); + + $expectedChangesForInterval = [ + 'attributes' => [ + 'name' => 'New name', + 'interval' => null, + ], + 'old' => [ + 'name' => 'Hamburg', + 'interval' => '1 month', + ], + ]; + + $this->assertEquals($expectedChangesForInterval, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheRelationValuesWhenUpdatingAModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'user.name']); + } + }; + + $user = User::create([ + 'name' => 'user name', + ]); + + $article = $articleClass::create([ + 'name' => 'original name', + 'text' => 'original text', + 'user_id' => $user->id, + ]); + + $article->name = 'updated name'; + $article->text = 'updated text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'updated name', + 'text' => 'updated text', + 'user.name' => 'user name', + ], + 'old' => [ + 'name' => 'original name', + 'text' => 'original text', + 'user.name' => 'user name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreAnEmptyRelationWhenUpdatingAModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'user.name']); + } + }; + + $user = User::create([ + 'name' => 'user name', + ]); + + $article = $articleClass::create([ + 'name' => 'original name', + 'text' => 'original text', + ]); + + $article->name = 'updated name'; + $article->text = 'updated text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'updated name', + 'text' => 'updated text', + 'user.name' => null, + ], + 'old' => [ + 'name' => 'original name', + 'text' => 'original text', + 'user.name' => null, + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenUpdatingAModel(): void + { + $article = $this->createArticle(); + + $article->name = 'updated name'; + $article->text = 'updated text'; + + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'updated name', + 'text' => 'updated text', + ], + 'old' => [ + 'name' => 'my name', + 'text' => null, + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreDirtyChangesOnly(): void + { + $article = $this->createDirtyArticle(); + + $article->name = 'updated name'; + + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'updated name', + ], + 'old' => [ + 'name' => 'my name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreDirtyChangesForSwappingValues(): void + { + $article = $this->createDirtyArticle(); + + $originalName = $article->name; + $originalText = $article->text; + + $article->text = $originalName; + $article->name = $originalText; + + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => $originalText, + 'text' => $originalName, + ], + 'old' => [ + 'name' => $originalName, + 'text' => $originalText, + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenUpdatingARelatedModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'user.name']); + } + }; + + $user = User::create([ + 'name' => 'a name', + ]); + + $anotherUser = User::create([ + 'name' => 'another name', + ]); + + $article = $articleClass::create([ + 'name' => 'name', + 'text' => 'text', + 'user_id' => $user->id, + ]); + + $article->user()->associate($anotherUser)->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'name', + 'text' => 'text', + 'user.name' => 'another name', + ], + 'old' => [ + 'name' => 'name', + 'text' => 'text', + 'user.name' => 'a name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenUpdatingASnakeCaseRelatedModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'snakeUser.name']); + } + + /** + * Get the snake-case user relation. + * + * @return BelongsTo + */ + public function snake_user(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } + }; + + $user = User::create([ + 'name' => 'a name', + ]); + + $anotherUser = User::create([ + 'name' => 'another name', + ]); + + $article = $articleClass::create([ + 'name' => 'name', + 'text' => 'text', + 'user_id' => $user->id, + ]); + + $article->user()->associate($anotherUser)->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'name', + 'text' => 'text', + 'snakeUser.name' => 'another name', + ], + 'old' => [ + 'name' => 'name', + 'text' => 'text', + 'snakeUser.name' => 'a name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenUpdatingACamelCaseRelatedModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'camel_user.name']); + } + + /** + * Get the camel-case user relation. + * + * @return BelongsTo + */ + public function camelUser(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } + }; + + $user = User::create([ + 'name' => 'a name', + ]); + + $anotherUser = User::create([ + 'name' => 'another name', + ]); + + $article = $articleClass::create([ + 'name' => 'name', + 'text' => 'text', + 'user_id' => $user->id, + ]); + + $article->user()->associate($anotherUser)->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'name', + 'text' => 'text', + 'camel_user.name' => 'another name', + ], + 'old' => [ + 'name' => 'name', + 'text' => 'text', + 'camel_user.name' => 'a name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenUpdatingACustomCaseRelatedModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'Custom_Case_User.name']); + } + + /** + * Get the custom-case user relation. + * + * @return BelongsTo + */ + public function Custom_Case_User(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } + }; + + $user = User::create([ + 'name' => 'a name', + ]); + + $anotherUser = User::create([ + 'name' => 'another name', + ]); + + $article = $articleClass::create([ + 'name' => 'name', + 'text' => 'text', + 'user_id' => $user->id, + ]); + + $article->user()->associate($anotherUser)->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'name', + 'text' => 'text', + 'Custom_Case_User.name' => 'another name', + ], + 'old' => [ + 'name' => 'name', + 'text' => 'text', + 'Custom_Case_User.name' => 'a name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheDirtyChangesWhenUpdatingARelatedModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'user.name']) + ->logOnlyDirty(); + } + }; + + $user = User::create([ + 'name' => 'a name', + ]); + + $anotherUser = User::create([ + 'name' => 'another name', + ]); + + $article = $articleClass::create([ + 'name' => 'name', + 'text' => 'text', + 'user_id' => $user->id, + ]); + + $article->user()->associate($anotherUser)->save(); + + $expectedChanges = [ + 'attributes' => [ + 'user.name' => 'another name', + ], + 'old' => [ + 'user.name' => 'a name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenSavingAMultilevelRelatedModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'user.latest_article.name']) + ->logOnlyDirty(); + } + }; + + $user = User::create([ + 'name' => 'a name', + ]); + + // Make the first article the user's latest without relying on equal timestamps. + $articleClass::create([ + 'name' => 'name #1', + 'text' => 'text #1', + 'user_id' => $user->id, + 'created_at' => '2026-01-02 00:00:00', + ]); + + $articleClass::create([ + 'name' => 'name #2', + 'text' => 'text #2', + 'user_id' => $user->id, + 'created_at' => '2026-01-01 00:00:00', + ]); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'name #2', + 'text' => 'text #2', + 'user.latest_article.name' => 'name #1', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testWillStoreNoChangesWhenNotLoggingAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly([]); + } + }; + + $article = new $articleClass; + + $article->name = 'updated name'; + + $article->save(); + + $this->assertEquals(collect(), $this->getLastActivity()->attribute_changes); + } + + public function testWillStoreTheValuesWhenDeletingTheModel(): void + { + $article = $this->createArticle(); + + $article->delete(); + + $expectedChanges = collect([ + 'old' => [ + 'name' => 'my name', + 'text' => null, + ], + ]); + + $this->assertEquals('deleted', $this->getLastActivity()->description); + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes); + } + + public function testWillStoreTheValuesWhenDeletingTheModelWithSoftDeletes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + use SoftDeletes; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text']); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->save(); + + $article->delete(); + + $expectedChanges = collect([ + 'old' => [ + 'name' => 'my name', + 'text' => null, + ], + ]); + + $this->assertEquals('deleted', $this->getLastActivity()->description); + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes); + + $article->forceDelete(); + + $expectedChanges = collect([ + 'old' => [ + 'name' => 'my name', + 'text' => null, + ], + ]); + + $activities = $article->activitiesAsSubject; + + $this->assertCount(3, $activities); + $this->assertEquals('deleted', $this->getLastActivity()->description); + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes); + } + + public function testCanStoreTheChangesOfCollectionCastedProperties(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = ['json' => 'collection']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['json']) + ->logOnlyDirty(); + } + }; + + $article = $articleClass::create([ + 'json' => ['value' => 'original'], + ]); + + $article->json = collect(['value' => 'updated']); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'json' => [ + 'value' => 'updated', + ], + ], + 'old' => [ + 'json' => [ + 'value' => 'original', + ], + ], + ]; + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesOfArrayCastedProperties(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = ['json' => 'array']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['json']) + ->logOnlyDirty(); + } + }; + + $article = $articleClass::create([ + 'json' => ['value' => 'original'], + ]); + + $article->json = collect(['value' => 'updated']); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'json' => [ + 'value' => 'updated', + ], + ], + 'old' => [ + 'json' => [ + 'value' => 'original', + ], + ], + ]; + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesOfJsonCastedProperties(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = ['json' => 'json']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['json']) + ->logOnlyDirty(); + } + }; + + $article = $articleClass::create([ + 'json' => ['value' => 'original'], + ]); + + $article->json = collect(['value' => 'updated']); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'json' => [ + 'value' => 'updated', + ], + ], + 'old' => [ + 'json' => [ + 'value' => 'original', + ], + ], + ]; + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseNothingAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->dontLogFillable(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->save(); + + $expectedChanges = []; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseTextAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['text']) + ->dontLogFillable(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'text' => 'my text', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseFillableAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logFillable(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => null, + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseBothFillableAndLogAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $fillable = ['name']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['text']) + ->logFillable(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => 'my text', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseWildcardForLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'id' => $article->id, + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseWildcardWithRelation(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['*', 'user.name']); + } + }; + + $user = User::create([ + 'name' => 'user name', + ]); + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + + $article = $articleClass::create([ + 'name' => 'article name', + 'text' => 'article text', + 'user_id' => $user->id, + ]); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $article->id, + 'name' => 'article name', + 'text' => 'article text', + 'user_id' => $user->id, + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + 'user.name' => 'user name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseWildcardWhenUpdatingModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll() + ->logOnlyDirty(); + } + }; + + $user = User::create([ + 'name' => 'user name', + ]); + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $article = $articleClass::create([ + 'name' => 'article name', + 'text' => 'article text', + 'user_id' => $user->id, + ]); + + $article->name = 'changed name'; + CarbonImmutable::setTestNow(CarbonImmutable::create(2018, 1, 1, 12, 0, 0)); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'changed name', + 'updated_at' => '2018-01-01T12:00:00.000000Z', + ], + 'old' => [ + 'name' => 'article name', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesWhenABooleanFieldChangesFromFalseToNull(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'text' => 'boolean', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll() + ->logOnlyDirty(); + } + }; + + $user = User::create([ + 'name' => 'user name', + ]); + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $article = $articleClass::create([ + 'name' => 'article name', + 'text' => false, + 'user_id' => $user->id, + ]); + + $article->text = null; + CarbonImmutable::setTestNow(CarbonImmutable::create(2018, 1, 1, 12, 0, 0)); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'text' => null, + 'updated_at' => '2018-01-01T12:00:00.000000Z', + ], + 'old' => [ + 'text' => false, + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertSame($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseIgnoredAttributesWhileUpdating(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll() + ->logExcept(['name', 'updated_at']); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $article->id, + 'created_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + $article->update(['name' => 'excluded', 'text' => 'included']); + $changes = $this->lastActivity()->attribute_changes->all(); + $this->assertSame('included', $changes['attributes']['text']); + $this->assertNull($changes['old']['text']); + $this->assertArrayNotHasKey('name', $changes['attributes']); + $this->assertArrayNotHasKey('name', $changes['old']); + } + + public function testCanUseUnguardedAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $guarded = ['text', 'json']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logUnguarded() + ->logExcept(['id', 'created_at', 'updated_at', 'deleted_at']); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my new text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testWillStoreNoChangesWithWildcardGuardAndLogUnguarded(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $guarded = ['*']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logUnguarded(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my new text'; + $article->save(); + + $this->assertEquals([], $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanLogUnguardedAttributesWhenModelIsGloballyUnguarded(): void + { + // Model without explicit $fillable or $guarded + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logUnguarded() + ->logExcept(['id', 'created_at', 'updated_at', 'deleted_at']); + } + }; + + // Globally unguard all models + Model::unguard(); + + try { + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => 'my text', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } finally { + // Re-guard models + Model::reguard(); + } + } + + public function testCanUseHiddenAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $hidden = ['text']; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text']); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => 'my text', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseOverloadedAttributesAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'description']); + } + + public function setDescriptionAttribute(mixed $value): void + { + $this->attributes['json'] = json_encode( + ['description' => $value], + JSON_THROW_ON_ERROR, + ); + } + + public function getDescriptionAttribute(): mixed + { + return Arr::get( + json_decode($this->attributes['json'], true, flags: JSON_THROW_ON_ERROR), + 'description', + ); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->description = 'my description'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => 'my text', + 'description' => 'my description', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseMutatedAttributesAsLoggableAttributes(): void + { + $userClass = new class extends User { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll(); + } + + public function setNameAttribute(string $value): void + { + $this->attributes['name'] = strtoupper($value); + } + }; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $user = new $userClass; + $user->name = 'my name'; + $user->text = 'my text'; + $user->save(); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $user->id, + 'name' => 'MY NAME', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + + $user->name = 'my name 2'; + $user->save(); + + $expectedChanges = [ + 'old' => [ + 'id' => $user->id, + 'name' => 'MY NAME', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + 'attributes' => [ + 'id' => $user->id, + 'name' => 'MY NAME 2', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseAccessorsAsLoggableAttributes(): void + { + $userClass = new class extends User { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll(); + } + + public function getNameAttribute(string $value): string + { + return strtoupper($value); + } + }; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $user = new $userClass; + $user->name = 'my name'; + $user->text = 'my text'; + $user->save(); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $user->id, + 'name' => 'MY NAME', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + + $user->name = 'my name 2'; + $user->save(); + + $expectedChanges = [ + 'old' => [ + 'id' => $user->id, + 'name' => 'MY NAME', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + 'attributes' => [ + 'id' => $user->id, + 'name' => 'MY NAME 2', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseEncryptedAttributesAsLoggableAttributes(): void + { + $userClass = new class extends User { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + protected array $encryptable = ['name', 'text']; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text']); + } + + public function getAttributeValue(string $key): mixed + { + $value = parent::getAttributeValue($key); + + if (in_array($key, $this->encryptable, true)) { + $value = decrypt($value); + } + + return $value; + } + + public function setAttribute(string|int $key, mixed $value): mixed + { + if (in_array($key, $this->encryptable, true)) { + $value = encrypt($value); + } + + return parent::setAttribute($key, $value); + } + }; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $user = new $userClass; + $user->name = 'my name'; + $user->text = 'my text'; + $user->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => 'my text', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + + $user->name = 'my name 2'; + $user->save(); + + $expectedChanges = [ + 'old' => [ + 'name' => 'my name', + 'text' => 'my text', + ], + 'attributes' => [ + 'name' => 'my name 2', + 'text' => 'my text', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseCastedAttributesAsLoggableAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'price' => 'float', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text', 'price']) + ->logOnlyDirty(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->price = '9.99'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + 'text' => 'my text', + 'price' => 9.99, + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + $this->assertSame($expectedChanges, $changes); + $this->assertIsFloat($changes['attributes']['price']); + + $article->price = 19.99; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'price' => 19.99, + ], + 'old' => [ + 'price' => 9.99, + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + $this->assertSame($expectedChanges, $changes); + $this->assertIsFloat($changes['attributes']['price']); + } + + public function testCanUseNullableDatesAsLoggableAttributes(): void + { + $userClass = new class extends User { + use LogsActivity; + use SoftDeletes; + + protected array $fillable = ['name', 'text']; + + protected array $dates = [ + 'created_at', + 'updated_at', + 'deleted_at', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll(); + } + }; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $user = new $userClass; + $user->name = 'my name'; + $user->text = 'my text'; + $user->save(); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $user->getKey(), + 'name' => 'my name', + 'text' => 'my text', + 'created_at' => '2017-01-01T12:00:00.000000Z', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseCustomDateCastsAsLoggableAttributes(): void + { + $userClass = new class extends User { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + protected array $casts = [ + 'created_at' => 'date:d.m.Y', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll(); + } + }; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $user = new $userClass; + $user->name = 'my name'; + $user->text = 'my text'; + $user->save(); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $user->getKey(), + 'name' => 'my name', + 'text' => 'my text', + 'created_at' => '01.01.2017', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanUseCustomImmutableDateCastsAsLoggableAttributes(): void + { + $userClass = new class extends User { + use LogsActivity; + + protected array $fillable = ['name', 'text']; + + protected array $casts = [ + 'created_at' => 'immutable_date:d.m.Y', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll(); + } + }; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $user = new $userClass; + $user->name = 'my name'; + $user->text = 'my text'; + $user->save(); + + $expectedChanges = [ + 'attributes' => [ + 'id' => $user->getKey(), + 'name' => 'my name', + 'text' => 'my text', + 'created_at' => '01.01.2017', + 'updated_at' => '2017-01-01T12:00:00.000000Z', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testCanStoreTheChangesOfJsonAttributes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => 'collection', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'json->data']) + ->logOnlyDirty(); + } + }; + + $article = new $articleClass; + $article->json = ['data' => 'test']; + $article->name = 'I am JSON'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'I am JSON', + 'json' => [ + 'data' => 'test', + ], + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + + $this->assertSame($expectedChanges, $changes); + } + + public function testWillNotStoreChangesToUntrackedJson(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => 'collection', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'json->data']) + ->logOnlyDirty(); + } + }; + + $article = new $articleClass; + $article->json = ['unTracked' => 'test']; + $article->name = 'a name'; + $article->save(); + + $article->name = 'I am JSON'; + $article->json = ['unTracked' => 'different string']; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'I am JSON', + ], + 'old' => [ + 'name' => 'a name', + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + + $this->assertSame($expectedChanges, $changes); + } + + public function testWillReturnNullForAMissingJsonAttribute(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => 'collection', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'json->data->missing']) + ->logOnlyDirty(); + } + }; + + $jsonToStore = []; + + $article = new $articleClass; + $article->json = $jsonToStore; + $article->name = 'I am JSON'; + $article->save(); + + data_set($jsonToStore, 'data.missing', 'I wasn\'t here'); + + $article->json = $jsonToStore; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'json' => [ + 'data' => [ + 'missing' => 'I wasn\'t here', + ], + ], + ], + 'old' => [ + 'json' => [ + 'data' => [ + 'missing' => null, + ], + ], + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + + $this->assertSame($expectedChanges, $changes); + } + + public function testWillReturnAnArrayForASubkeyInAJsonAttribute(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => 'collection', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'json->data']) + ->logOnlyDirty(); + } + }; + + $jsonToStore = [ + 'data' => [ + 'data_a' => 1, + 'data_b' => 2, + 'data_c' => 3, + 'data_d' => 4, + 'data_e' => 5, + ], + ]; + + $article = new $articleClass; + $article->json = $jsonToStore; + $article->name = 'I am JSON'; + $article->save(); + + data_set($jsonToStore, 'data.data_c', 'I Got The Key'); + + $article->json = $jsonToStore; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'json' => [ + 'data' => [ + 'data_a' => 1, + 'data_b' => 2, + 'data_c' => 'I Got The Key', + 'data_d' => 4, + 'data_e' => 5, + ], + ], + ], + 'old' => [ + 'json' => [ + 'data' => [ + 'data_a' => 1, + 'data_b' => 2, + 'data_c' => 3, + 'data_d' => 4, + 'data_e' => 5, + ], + ], + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + + $this->assertSame($expectedChanges, $changes); + } + + public function testWillAccessBeyondLevelOneInAJsonAttribute(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => 'collection', + ]; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'json->data->can->go->how->far']) + ->logOnlyDirty(); + } + }; + + $jsonToStore = []; + // data_set($jsonToStore, 'data.can.go.how.far', 'Data'); + + $article = new $articleClass; + $article->json = $jsonToStore; + $article->name = 'I am JSON'; + $article->save(); + + data_set($jsonToStore, 'data.can.go.how.far', 'This far'); + + $article->json = $jsonToStore; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'json' => [ + 'data' => [ + 'can' => [ + 'go' => [ + 'how' => [ + 'far' => 'This far', + ], + ], + ], + ], + ], + ], + 'old' => [ + 'json' => [ + 'data' => [ + 'can' => [ + 'go' => [ + 'how' => [ + 'far' => null, + ], + ], + ], + ], + ], + ], + ]; + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + + $this->assertSame($expectedChanges, $changes); + } + + public function testCanExcludeAttributesGloballyViaConfiguration(): void + { + config()->set('activity-log.default_except_attributes', ['text']); + + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text']); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + $article->save(); + + $expectedChanges = [ + 'attributes' => [ + 'name' => 'my name', + ], + ]; + + $this->assertEquals($expectedChanges, $this->getLastActivity()->attribute_changes->toArray()); + } + + public function testMergesConfiguredDefaultExclusionsWithModelExclusions(): void + { + config()->set('activity-log.default_except_attributes', ['text']); + + $articleClass = new class extends Article { + use LogsActivity; + + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logAll() + ->logExcept(['name']); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->text = 'my text'; + + CarbonImmutable::setTestNow(CarbonImmutable::create(2017, 1, 1, 12, 0, 0)); + $article->save(); + + $changes = $this->getLastActivity()->attribute_changes->toArray(); + + // both 'name' (from logExcept) and 'text' (from config) should be excluded + $this->assertArrayNotHasKey('name', $changes['attributes']); + $this->assertArrayNotHasKey('text', $changes['attributes']); + $this->assertArrayHasKey('id', $changes['attributes']); + } + + /** + * Create an article that logs only dirty name and text attributes. + */ + protected function createDirtyArticle(): Article + { + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name', 'text']) + ->logOnlyDirty(); + } + }; + + $article = new $articleClass; + $article->name = 'my name'; + $article->save(); + + return $article; + } + + /** + * Get the latest activity changes as an array. + * + * @return array + */ + protected function lastChanges(): array + { + $activity = $this->getLastActivity(); + + $this->assertNotNull($activity); + $this->assertNotNull($activity->attribute_changes); + + return $activity->attribute_changes->toArray(); + } +} diff --git a/tests/ActivityLog/Traits/LogsActivityTest.php b/tests/ActivityLog/Traits/LogsActivityTest.php new file mode 100644 index 000000000..75a126244 --- /dev/null +++ b/tests/ActivityLog/Traits/LogsActivityTest.php @@ -0,0 +1,762 @@ +article = new class extends Article { + use LogsActivity; + use SoftDeletes; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + }; + + $this->user = new class extends User { + use LogsActivity; + use SoftDeletes; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + }; + + $this->assertSame(0, Activity::query()->count()); + } + + public function testWillLogTheCreationOfTheModel(): void + { + $article = $this->createArticle(); + $activity = $this->lastActivity(); + + $this->assertSame(1, Activity::query()->count()); + $this->assertInstanceOf($this->article::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + } + + public function testCanSkipLoggingModelEventsIfAskedTo(): void + { + $article = new $this->article; + $article->disableLogging(); + $article->setAttribute('name', 'my name'); + $article->save(); + + $this->assertSame(0, Activity::query()->count()); + $this->assertNull($this->getLastActivity()); + } + + public function testCanSwitchOnActivityLoggingAfterDisablingIt(): void + { + $article = new $this->article; + $article->disableLogging(); + $article->setAttribute('name', 'my name'); + $article->save(); + + $article->enableLogging(); + $article->setAttribute('name', 'my new name'); + $article->save(); + + $activity = $this->lastActivity(); + + $this->assertSame(1, Activity::query()->count()); + $this->assertInstanceOf($this->article::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame('updated', $activity->description); + $this->assertSame('updated', $activity->event); + } + + public function testCanSkipLoggingIfAskedToForUpdateMethod(): void + { + $article = new $this->article; + $article->disableLogging()->update(['name' => 'How to log events']); + + $this->assertSame(0, Activity::query()->count()); + $this->assertNull($this->getLastActivity()); + } + + public function testCanExcludeSpecificEventsUsingDoNotRecordEvents(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected static array $doNotRecordEvents = ['created']; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + }; + + $article = new $articleClass; + $article->setAttribute('name', 'my name'); + $article->save(); + + $this->assertSame(0, Activity::query()->count()); + + $article->setAttribute('name', 'updated name'); + $article->save(); + + $this->assertSame(1, Activity::query()->count()); + $this->assertSame('updated', $this->lastActivity()->event); + } + + public function testWillLogAnUpdateOfTheModel(): void + { + $article = $this->createArticle(); + $article->setAttribute('name', 'changed name'); + $article->save(); + + $activity = $this->lastActivity(); + + $this->assertSame(2, Activity::query()->count()); + $this->assertInstanceOf($this->article::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame('updated', $activity->description); + $this->assertSame('updated', $activity->event); + } + + public function testWillLogTheReplicationOfAModelWithSoftDeletes(): void + { + $article = $this->createArticle(); + $replicatedArticle = $this->article::query()->findOrFail($article->getKey())->replicate(); + $replicatedArticle->save(); + $activities = Activity::query()->orderBy('id')->get(); + + $this->assertCount(2, $activities); + $this->assertTrue($activities->every( + fn (Activity $activity): bool => $activity->event === 'created' + && $activity->description === 'created' + && $activity->subject_type === $this->article::class + && in_array($activity->subject_id, [$article->getKey(), $replicatedArticle->getKey()], true), + )); + $this->assertSame($article->getKey(), $activities->first()?->subject_id); + $this->assertSame($replicatedArticle->getKey(), $activities->last()?->subject_id); + } + + public function testWillLogTheDeletionOfAModelWithoutSoftDeletes(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['name']); + } + }; + + $article = new $articleClass; + $article->setAttribute('name', 'my name'); + $article->save(); + + $this->assertSame('created', $this->lastActivity()->description); + $this->assertSame('created', $this->lastActivity()->event); + + $article->delete(); + $activity = $this->lastActivity(); + + $this->assertSame('deleted', $activity->description); + $this->assertArrayHasKey('old', $activity->attribute_changes); + $this->assertSame('my name', $activity->attribute_changes['old']['name']); + $this->assertArrayNotHasKey('attributes', $activity->attribute_changes); + $this->assertSame('deleted', $activity->event); + } + + public function testWillLogTheDeletionOfAModelWithSoftDeletes(): void + { + $article = $this->createArticle(); + $article->delete(); + $activity = $this->lastActivity(); + + $this->assertSame(2, Activity::query()->count()); + $this->assertSame($this->article::class, $activity->subject_type); + $this->assertSame($article->getKey(), $activity->subject_id); + $this->assertSame('deleted', $activity->description); + $this->assertSame('deleted', $activity->event); + + $article->forceDelete(); + $activity = $this->lastActivity(); + + $this->assertSame(3, Activity::query()->count()); + $this->assertSame('deleted', $activity->description); + $this->assertSame('deleted', $activity->event); + $this->assertNull($article->fresh()); + } + + public function testWillLogTheRestoringOfAModelWithSoftDeletes(): void + { + $article = $this->createArticle(); + $article->delete(); + $article->restore(); + $activity = $this->lastActivity(); + + $this->assertSame(3, Activity::query()->count()); + $this->assertSame($this->article::class, $activity->subject_type); + $this->assertSame($article->getKey(), $activity->subject_id); + $this->assertSame('restored', $activity->description); + $this->assertSame('restored', $activity->event); + } + + public function testCanFetchAllActivityForAModel(): void + { + $article = $this->createArticle(); + $article->setAttribute('name', 'changed name'); + $article->save(); + + $this->assertCount(2, $article->activitiesAsSubject); + } + + public function testCanFetchSoftDeletedModels(): void + { + config()->set('activity-log.include_soft_deleted_subjects', true); + $article = $this->createArticle(); + $article->setAttribute('name', 'changed name'); + $article->save(); + $article->delete(); + + $activity = $this->lastActivity(); + + $this->assertCount(3, $article->activitiesAsSubject); + $this->assertSame($this->article::class, $activity->subject_type); + $this->assertSame($article->getKey(), $activity->subject_id); + $this->assertSame('deleted', $activity->description); + $this->assertSame('deleted', $activity->event); + $this->assertSame('changed name', $activity->subject?->getAttribute('name')); + } + + public function testCanFetchSubjectWithoutSoftDeletesWhenConfigIsEnabled(): void + { + config()->set('activity-log.include_soft_deleted_subjects', true); + + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + }; + + $article = new $articleClass; + $article->setAttribute('name', 'test article'); + $article->save(); + + $subject = Activity::query()->firstOrFail()->subject; + + $this->assertNotNull($subject); + $this->assertSame('test article', $subject->getAttribute('name')); + } + + public function testCanLogActivityToLogNamedInTheModel(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->useLogName('custom_log'); + } + }; + + $article = new $articleClass; + $article->setAttribute('name', 'my name'); + $article->save(); + + $this->assertSame('custom_log', $this->lastActivity()->log_name); + } + + public function testWillNotLogAnUpdateIfOnlyIgnoredAttributesChanged(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->dontLogIfAttributesChangedOnly(['text', 'updated_at']); + } + }; + + $article = new $articleClass; + $article->setAttribute('name', 'my name'); + $article->save(); + $article->setAttribute('text', 'ignore me'); + $article->save(); + $activity = $this->lastActivity(); + + $this->assertSame(1, Activity::query()->count()); + $this->assertInstanceOf($articleClass::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + } + + public function testWillNotFailIfAskedToReplaceFromAnEmptyAttribute(): void + { + $model = new class extends Article { + use LogsActivity; + use SoftDeletes; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->setDescriptionForEvent( + static fn (string $eventName): string => ":causer.name {$eventName}", + ); + } + }; + + $entity = new $model; + $entity->save(); + $entity->setAttribute('name', 'my name'); + $entity->save(); + $activities = $entity->activitiesAsSubject; + + $this->assertCount(2, $activities); + $this->assertSame($entity->getKey(), $activities[0]->subject?->getKey()); + $this->assertSame($entity->getKey(), $activities[1]->subject?->getKey()); + $this->assertSame(':causer.name created', $activities[0]->description); + $this->assertSame(':causer.name updated', $activities[1]->description); + } + + public function testCanLogActivityOnSubjectByTheSameCauser(): void + { + $user = $this->loginWithFakeUser(); + $user->setAttribute('name', 'LogsActivity Name'); + $user->save(); + $activity = $this->lastActivity(); + + $this->assertSame(1, Activity::query()->count()); + $this->assertInstanceOf($this->user::class, $activity->subject); + $this->assertSame($user->getKey(), $activity->subject?->getKey()); + $this->assertSame($user->getKey(), $activity->causer?->getKey()); + $this->assertCount(1, $user->activitiesAsSubject); + $this->assertCount(1, $user->activitiesAsCauser); + } + + public function testCanLogActivityWhenAttributesAreChangedWithTap(): void + { + $model = new class extends Article { + use LogsActivity; + + protected array $properties = [ + 'property' => [ + 'subProperty' => 'value', + ], + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $properties = $this->properties; + $properties['event'] = $eventName; + $activity->setAttribute('properties', collect($properties)); + $activity->setAttribute('created_at', CarbonImmutable::yesterday()->startOfDay()); + } + }; + + $entity = new $model; + $entity->save(); + $activity = $entity->activitiesAsSubject()->firstOrFail(); + + $this->assertInstanceOf(Collection::class, $activity->properties); + $this->assertSame('value', $activity->getProperty('property.subProperty')); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + $this->assertSame( + CarbonImmutable::yesterday()->startOfDay()->format('Y-m-d H:i:s'), + $activity->created_at?->format('Y-m-d H:i:s'), + ); + } + + public function testCanLogActivityWhenDescriptionIsChangedWithTap(): void + { + $model = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $activity->setAttribute('description', 'my custom description'); + } + }; + + $entity = new $model; + $entity->save(); + + $this->assertSame( + 'my custom description', + $entity->activitiesAsSubject()->firstOrFail()->description, + ); + } + + public function testCanLogActivityWhenEventIsChangedWithTap(): void + { + $model = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + $activity->setAttribute('event', 'my custom event'); + } + }; + + $entity = new $model; + $entity->save(); + + $this->assertSame( + 'my custom event', + $entity->activitiesAsSubject()->firstOrFail()->event, + ); + } + + public function testWillOnlyCallBeforeActivityLoggedOnce(): void + { + $model = new class extends Article { + use LogsActivity; + + public static int $tapCallCount = 0; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults(); + } + + /** + * Modify the activity before it is logged. + */ + public function beforeActivityLogged(Activity $activity, string $eventName): void + { + ++self::$tapCallCount; + } + }; + + $model::$tapCallCount = 0; + (new $model)->save(); + + $this->assertSame(1, $model::$tapCallCount); + } + + public function testWillNotSubmitLogWhenThereAreNoChanges(): void + { + $model = new class extends Article { + use LogsActivity; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['text']) + ->dontLogEmptyChanges() + ->logOnlyDirty(); + } + }; + + $entity = new $model(['text' => 'test']); + $entity->save(); + + $this->assertSame(1, Activity::query()->count()); + + $entity->setAttribute('name', 'my name'); + $entity->save(); + + $this->assertSame(1, Activity::query()->count()); + } + + public function testWillSubmitALogWithJsonChanges(): void + { + $model = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'json' => 'collection', + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['text', 'json->data']) + ->dontLogEmptyChanges() + ->logOnlyDirty(); + } + }; + + $entity = new $model([ + 'text' => 'test', + 'json' => [ + 'data' => 'oldish', + ], + ]); + $entity->save(); + + $this->assertSame(1, Activity::query()->count()); + + $entity->setAttribute('json', [ + 'data' => 'chips', + 'irrelevant' => 'should not be', + ]); + $entity->save(); + + $this->assertSame(2, Activity::query()->count()); + $this->assertSame([ + 'attributes' => [ + 'json' => [ + 'data' => 'chips', + ], + ], + 'old' => [ + 'json' => [ + 'data' => 'oldish', + ], + ], + ], $this->lastActivity()->attribute_changes->toArray()); + } + + public function testWillLogTheRetrievalOfTheModel(): void + { + $article = Issue733::query()->create(['name' => 'my name']); + $retrieved = Issue733::query()->whereKey($article->getKey())->first(); + + $this->assertTrue($article->is($retrieved)); + + $activity = $this->lastActivity(); + + $this->assertInstanceOf($article::class, $activity->subject); + $this->assertTrue($article->is($activity->subject)); + $this->assertSame('retrieved', $activity->description); + } + + public function testWillNotLogCastedAttributeWhenRawValuesAreUsed(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'name' => 'encrypted', + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name']) + ->useAttributeRawValues(['name']); + } + }; + + $article = new $articleClass; + $article->setAttribute('name', 'my name'); + $article->save(); + $activity = $this->lastActivity(); + + $this->assertInstanceOf($articleClass::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame($article->getRawOriginal('name'), $activity->attribute_changes['attributes']['name']); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + } + + public function testCanBeSerialized(): void + { + $model = ArticleWithLogDescriptionClosure::query()->create(['name' => 'foo']); + + $this->assertIsString(serialize($model)); + } + + public function testCanSerializeAndUnserializeLogOptionsWithADescriptionClosure(): void + { + $options = LogOptions::defaults() + ->setDescriptionForEvent( + static fn (string $eventName): string => "Article was {$eventName}", + ); + + $unserialized = unserialize(serialize($options)); + + $this->assertInstanceOf(LogOptions::class, $unserialized); + $this->assertSame('Article was created', ($unserialized->descriptionForEvent)('created')); + $this->assertSame('Article was updated', ($unserialized->descriptionForEvent)('updated')); + } + + public function testLogsNonBackedEnumCastedAttribute(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'status' => NonBackedEnum::class, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['status']); + } + }; + + $article = new $articleClass; + $article->setAttribute('status', NonBackedEnum::Draft); + $article->save(); + $activity = $this->lastActivity(); + + $this->assertInstanceOf($articleClass::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame('Draft', $activity->attribute_changes['attributes']['status']); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + } + + public function testLogsIntBackedEnumCastedAttribute(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'status' => IntBackedEnum::class, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['status']); + } + }; + + $article = new $articleClass; + $article->setAttribute('status', IntBackedEnum::Published); + $article->save(); + $activity = $this->lastActivity(); + + $this->assertInstanceOf($articleClass::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame(1, $activity->attribute_changes['attributes']['status']); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + } + + public function testLogsStringBackedEnumCastedAttribute(): void + { + $articleClass = new class extends Article { + use LogsActivity; + + protected array $casts = [ + 'status' => StringBackedEnum::class, + ]; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults()->logOnly(['status']); + } + }; + + $article = new $articleClass; + $article->setAttribute('status', StringBackedEnum::Draft); + $article->save(); + $activity = $this->lastActivity(); + + $this->assertInstanceOf($articleClass::class, $activity->subject); + $this->assertSame($article->getKey(), $activity->subject?->getKey()); + $this->assertSame('draft', $activity->attribute_changes['attributes']['status']); + $this->assertSame('created', $activity->description); + $this->assertSame('created', $activity->event); + } +} diff --git a/tests/Inertia/BroadcastPropsTest.php b/tests/Inertia/BroadcastPropsTest.php index 09df48930..b285bc3a9 100644 --- a/tests/Inertia/BroadcastPropsTest.php +++ b/tests/Inertia/BroadcastPropsTest.php @@ -54,7 +54,7 @@ public function toArray(Request $request): array } /** - * @implements Arrayable + * @implements Arrayable */ class BroadcastOrderSummary implements Arrayable { diff --git a/tests/Integration/ActivityLog/Database/ActivityLogMigrationDatabaseTest.php b/tests/Integration/ActivityLog/Database/ActivityLogMigrationDatabaseTest.php new file mode 100644 index 000000000..49d7ba09a --- /dev/null +++ b/tests/Integration/ActivityLog/Database/ActivityLogMigrationDatabaseTest.php @@ -0,0 +1,83 @@ +app->make(DatabaseManager::class)->connection(); + $driver = $connection->getDriverName(); + [$jsonType, $morphType] = match ($driver) { + 'mysql' => ['json', 'bigint'], + 'mariadb' => ['longtext', 'bigint'], + 'pgsql' => ['jsonb', 'int8'], + }; + + $this->assertActivityLogDatabaseEngine($connection, $driver); + $schema = $connection->getSchemaBuilder(); + $schema->dropIfExists('activity_log'); + SchemaBuilder::defaultMorphKeyType('int'); + + try { + $this->migration()->up(); + + $columns = []; + + foreach ($schema->getColumns('activity_log') as $column) { + $columns[$column['name']] = $column; + } + + $this->assertSame($morphType, $columns['subject_id']['type_name']); + $this->assertSame($morphType, $columns['causer_id']['type_name']); + $this->assertTrue($columns['subject_id']['nullable']); + $this->assertTrue($columns['causer_id']['nullable']); + $this->assertSame($jsonType, $columns['attribute_changes']['type_name']); + $this->assertSame($jsonType, $columns['properties']['type_name']); + + $indexes = []; + + foreach ($schema->getIndexes('activity_log') as $index) { + if (! $index['primary']) { + $indexes[$index['name']] = $index['columns']; + } + } + + ksort($indexes); + + $this->assertSame([ + 'activity_log_causer' => ['causer_type', 'causer_id'], + 'activity_log_created_at_id_index' => ['created_at', 'id'], + 'activity_log_name_created_at_id_index' => ['log_name', 'created_at', 'id'], + 'activity_log_subject' => ['subject_type', 'subject_id'], + ], $indexes); + + $this->migration()->down(); + $this->assertFalse($schema->hasTable('activity_log')); + } finally { + $schema->dropIfExists('activity_log'); + SchemaBuilder::defaultMorphKeyType('int'); + } + } + + /** + * Load the publish-only activity log migration. + */ + protected function migration(): Migration + { + return require dirname(__DIR__, 4) + . '/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php'; + } +} diff --git a/tests/Integration/ActivityLog/Database/ActivityLogRefreshLockingTest.php b/tests/Integration/ActivityLog/Database/ActivityLogRefreshLockingTest.php new file mode 100644 index 000000000..39d69e4d3 --- /dev/null +++ b/tests/Integration/ActivityLog/Database/ActivityLogRefreshLockingTest.php @@ -0,0 +1,180 @@ +app->make(DatabaseManager::class); + $primary = $database->connection(); + $primaryName = $primary->getName(); + $driver = $primary->getDriverName(); + $table = 'activity_log_refresh_lock'; + $competitorName = 'activity_log_competitor'; + config(["database.connections.{$competitorName}" => $primary->getConfig()]); + $competitor = $database->connection($competitorName); + + $this->assertInstanceOf(Connection::class, $primary); + $this->assertInstanceOf(Connection::class, $competitor); + $this->assertActivityLogDatabaseEngine($primary, $driver); + $this->assertActivityLogDatabaseEngine($competitor, $driver); + + $schema = $primary->getSchemaBuilder(); + $schema->dropIfExists($table); + + $migration = require dirname(__DIR__, 4) + . '/src/activity-log/database/publish/2026_08_04_000000_create_activity_log_table.php'; + + try { + $migration->up(); + $schema->create($table, static function (Blueprint $table): void { + $table->id(); + $table->string('name'); + }); + + $subject = new RefreshLockingArticle; + $subject->setConnection($primaryName); + $subject->setTable($table); + $subject->setAttribute('name', 'initial value'); + RefreshLockingArticle::withoutEvents( + static fn (): bool => $subject->save(), + ); + + $statementCompleted = new Channel(1); + $competitorAttempting = new Channel(1); + $competitorFinished = new Channel(1); + $listenerRan = false; + $competitorFinishedBeforeRefresh = null; + $primary->listen(function (QueryExecuted $event) use ( + $primaryName, + $table, + $statementCompleted, + $competitorAttempting, + $competitorFinished, + &$listenerRan, + &$competitorFinishedBeforeRefresh, + ): void { + if ($listenerRan + || $event->connectionName !== $primaryName + || ! str_starts_with(strtolower(ltrim($event->sql)), 'update ') + || ! str_contains(strtolower($event->sql), strtolower($table))) { + return; + } + + $listenerRan = true; + $statementCompleted->push(true); + + if ($competitorAttempting->pop(2.0) !== true) { + throw new RuntimeException('The competing writer did not start.'); + } + + $competitorFinishedBeforeRefresh = $competitorFinished->pop(0.001) !== false; + }); + + parallel([ + 'primary' => function () use ($primary, $subject): void { + $primary->transaction(static function () use ($subject): void { + $subject->setAttribute('name', 'first writer'); + $subject->save(); + }); + }, + 'competitor' => function () use ( + $competitor, + $table, + $subject, + $statementCompleted, + $competitorAttempting, + $competitorFinished, + ): void { + if ($statementCompleted->pop(2.0) !== true) { + throw new RuntimeException('The first update statement did not complete.'); + } + + $competitor->beforeExecuting(static function (string $sql) use ($competitorAttempting): void { + if (str_starts_with(strtolower(ltrim($sql)), 'update ')) { + $competitorAttempting->push(true); + } + }); + $competitor->table($table) + ->where('id', $subject->getKey()) + ->update(['name' => 'second writer']); + $competitorFinished->push(true); + }, + ]); + + $activity = Activity::query()->firstOrFail(); + + $this->assertTrue($listenerRan); + $this->assertFalse($competitorFinishedBeforeRefresh); + $this->assertSame( + 'second writer', + $competitor->table($table)->where('id', $subject->getKey())->value('name'), + ); + $this->assertSame( + 'first writer', + $activity->attribute_changes['attributes']['name'], + ); + $this->assertSame( + 'initial value', + $activity->attribute_changes['old']['name'], + ); + } finally { + $schema->dropIfExists($table); + $migration->down(); + $database->purge($competitorName); + } + } +} + +#[Unguarded] +class RefreshLockingArticle extends Model +{ + use LogsActivity; + + public bool $timestamps = false; + + /** + * Get the activity logging options for this model. + */ + public function getActivityLogOptions(): LogOptions + { + return LogOptions::defaults() + ->logOnly(['name']) + ->logOnlyDirty() + ->dontLogEmptyChanges() + ->refreshBeforeLogging(); + } +} diff --git a/tests/Integration/ActivityLog/Fixtures/InteractsWithActivityLogDatabases.php b/tests/Integration/ActivityLog/Fixtures/InteractsWithActivityLogDatabases.php new file mode 100644 index 000000000..a851ef6a6 --- /dev/null +++ b/tests/Integration/ActivityLog/Fixtures/InteractsWithActivityLogDatabases.php @@ -0,0 +1,37 @@ +assertSame($driver, $connection->getDriverName()); + + $version = (string) $connection->scalar('select version()'); + + match ($driver) { + 'mysql' => $this->assertStringNotContainsString( + 'mariadb', + strtolower($version), + ), + 'mariadb' => $this->assertStringContainsString( + 'mariadb', + strtolower($version), + ), + 'pgsql' => $this->assertStringContainsString( + 'postgresql', + strtolower($version), + ), + }; + } +} diff --git a/tests/Integration/Database/EloquentMorphToTouchesTest.php b/tests/Integration/Database/EloquentMorphToTouchesTest.php index c86de87ad..38a0f38b0 100644 --- a/tests/Integration/Database/EloquentMorphToTouchesTest.php +++ b/tests/Integration/Database/EloquentMorphToTouchesTest.php @@ -4,6 +4,7 @@ namespace Hypervel\Tests\Integration\Database\EloquentMorphToTouchesTest; +use Hypervel\Database\Eloquent\Casts\AsArrayObject; use Hypervel\Database\Eloquent\Model; use Hypervel\Database\Eloquent\Relations\MorphTo; use Hypervel\Database\Schema\Blueprint; @@ -27,6 +28,7 @@ protected function afterRefreshingDatabase(): void Schema::create('comments', function (Blueprint $table) { $table->increments('id'); $table->nullableMorphs('commentable'); + $table->text('settings')->nullable(); }); Post::create(); @@ -43,6 +45,44 @@ public function testNotNull(): void $this->assertCount(2, DB::getQueryLog()); } + public function testProjectedMorphIdCannotReadOrTouchTheSourceRow(): void + { + $post = Post::firstOrFail(); + $comment = new Comment; + $settings = '{ "mode": "live" }'; + $comment->setAttribute('settings', $settings); + $comment->commentable()->associate($post); + $comment->save(); + $partial = Comment::query()->select('id', 'commentable_id', 'settings')->findOrFail($comment->getKey()); + $partial->mergeCasts(['settings' => AsArrayObject::class]); + $this->assertSame('live', $partial->settings['mode']); + $this->assertSame($partial->getKey(), $post->getKey()); + + DB::enableQueryLog(); + $this->assertNull($partial->commentable); + $partial->commentable()->touch(); + $this->assertSame([], DB::getQueryLog()); + $this->assertNull($partial->commentable()->value('id')); + + Model::preventAccessingMissingAttributes(); + try { + $violations = []; + Model::handleMissingAttributeViolationUsing(static function (Model $model, string $key) use (&$violations): void { + $violations[] = $key; + }); + $default = $partial->commentable()->withDefault(['label' => 'unknown'])->getResults(); + $this->assertSame('unknown', $default->label); + $this->assertSame(['commentable_type'], $violations); + $this->assertSame($settings, $partial->rawSettings()); + + $partial->commentable()->associate($post); + $this->assertTrue($post->is($partial->commentable)); + } finally { + Model::handleMissingAttributeViolationUsing(null); + Model::preventAccessingMissingAttributes(false); + } + } + public function testNull(): void { DB::enableQueryLog(); @@ -59,6 +99,14 @@ class Comment extends Model protected array $touches = ['commentable']; + /** + * Read the stored JSON without writing back the cached cast. + */ + public function rawSettings(): string + { + return $this->attributes['settings']; + } + /** * Get the model that owns the comment. */ diff --git a/types/ActivityLog/Facade.php b/types/ActivityLog/Facade.php new file mode 100644 index 000000000..9ecafedaf --- /dev/null +++ b/types/ActivityLog/Facade.php @@ -0,0 +1,15 @@ +', ActivityLog::when(true)); +assertType(ActivityLogger::class, ActivityLog::when(true, fn ($logger): ActivityLogger => $logger->event('created'))); +assertType('42', ActivityLog::withoutLogging(fn (): int => 42)); +assertType('42', ActivityLog::defaultCauser(null, fn (): int => 42));