Repository navigation
Add the Activity Log package - #804
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
|
@cubic-dev-ai review |
@binaryfire I have started the AI code review. It will take a few minutes to complete. |
PR Summary by QodoAdd Activity Log package
AI Description
Merge Risk
|
Code Review by Qodo
1. Canceled jobs lose buffered activities
|
[High impact] The reviewed changes appear safe to merge. SummaryAdds optional database-backed activity logging with fluent builders, model-event logging, coroutine-owned buffers, cleanup, and documentation.
Reviews (5) · Last reviewed commit: "Use Eloquent cast serialization for sele..." · Reviewed by Greptile |
There was a problem hiding this comment.
10 issues found across 70 files
Confidence score: 3/5
- In
CauserResolver.php,causedBy($user)can record the default service account instead of the supplied user. Check for an explicit$subjectbefore returning$causerOverride. ActivityLogMigrationTest.phpexpects SQLite-specific JSON and ID types, so the tests can fail on other configured database drivers. Derive these expectations from the active driver or assert driver-neutral properties.- In
Activity.php,subject()andcauser()can query the audit connection instead of the target model's connection when the activity model uses a dedicated audit connection. Resolve morph targets on their own configured or default connection. - In
LogActivityAction.php,method_exists()can find a protected or privatebeforeActivityLoggedhook that this class cannot call, causing logging to fail with anError. Check the hook's visibility before invoking it.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/activity-log/src/Support/ChangeDetector.php">
<violation number="1" location="src/activity-log/src/Support/ChangeDetector.php:54">
P2: Dotted relation attributes bypass the same storage formatting used for direct attributes. A related custom-date cast is therefore logged with default JSON date formatting rather than its configured format; apply `formatAttributeValue()` (or a shared equivalent) to the related leaf value before storing it.</violation>
</file>
<file name="src/activity-log/src/Facades/ActivityLog.php">
<violation number="1" location="src/activity-log/src/Facades/ActivityLog.php:44">
P3: These facade annotations omit the `HigherOrderWhenProxy` returned by `ActivityLogger::when()` and `unless()` when called without a callback. Include the proxy type so IDEs and static analyzers expose the supported higher-order chaining API.</violation>
</file>
<file name="src/activity-log/src/Actions/LogActivityAction.php">
<violation number="1" location="src/activity-log/src/Actions/LogActivityAction.php:101">
P2: `method_exists()` does not verify that the hook is callable from this class, so a protected or private `beforeActivityLogged` method causes activity logging to fail with an `Error`. Check the reflected method visibility (and skip inaccessible hooks) before invoking it.</violation>
<violation number="2" location="src/activity-log/src/Actions/LogActivityAction.php:169">
P2: Mark this worker-wide reset as `#[BootOrTestsOnly]`, matching `ActivityLogManager::flushMacros()`. Without the marker, runtime code can clear callbacks while active requests are using the registry, and the test-only reset is not classified consistently.</violation>
</file>
<file name="src/activity-log/src/Support/ActivityBuffer.php">
<violation number="1" location="src/activity-log/src/Support/ActivityBuffer.php:190">
P2: Buffered persistence bypasses Eloquent lifecycle events, so custom Activity models behave differently when buffering is enabled. A model `creating` hook can reject or modify an activity during immediate writes but is silently skipped here; preserve that contract or explicitly restrict and document buffered models.</violation>
</file>
<file name="tests/ActivityLog/Database/ActivityLogMigrationTest.php">
<violation number="1" location="tests/ActivityLog/Database/ActivityLogMigrationTest.php:48">
P2: This assertion only matches SQLite metadata. Parameterize the expected ID type by the active driver (or assert the driver-neutral auto-increment/primary-key properties) so the migration test passes on MySQL, MariaDB, and PostgreSQL.</violation>
<violation number="2" location="tests/ActivityLog/Database/ActivityLogMigrationTest.php:56">
P2: These expected types are SQLite-specific. Derive the expected JSON type from the active driver/configuration instead of requiring `text` for every database.</violation>
</file>
<file name="src/activity-log/src/Support/CauserResolver.php">
<violation number="1" location="src/activity-log/src/Support/CauserResolver.php:34">
P1: Check for an explicit `$subject` before returning `$causerOverride`; `causedBy($user)` currently records the default service account instead of the supplied user.</violation>
</file>
<file name="src/activity-log/src/Support/ActivityLogger.php">
<violation number="1" location="src/activity-log/src/Support/ActivityLogger.php:158">
P2: Normalize `properties` to a collection before calling `put()`; a contract-compliant custom activity model with an array cast throws on `withProperty()`.</violation>
</file>
<file name="src/activity-log/src/Models/Activity.php">
<violation number="1" location="src/activity-log/src/Models/Activity.php:62">
P2: Resolve morph targets on their own configured or default connection; an activity model on a dedicated audit connection can otherwise make `subject()` and `causer()` query the audit database for target rows.</violation>
</file>
Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack
View guided diff | Turn on auto-fix | Re-trigger cubic
| */ | ||
| public function resolve(Model|int|string|null $subject = null): ?Model | ||
| { | ||
| if ($this->causerOverride !== null) { |
There was a problem hiding this comment.
P1: Check for an explicit $subject before returning $causerOverride; causedBy($user) currently records the default service account instead of the supplied user.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/activity-log/src/Support/CauserResolver.php, line 34:
<comment>Check for an explicit `$subject` before returning `$causerOverride`; `causedBy($user)` currently records the default service account instead of the supplied user.</comment>
<file context>
@@ -0,0 +1,165 @@
+ */
+ public function resolve(Model|int|string|null $subject = null): ?Model
+ {
+ if ($this->causerOverride !== null) {
+ return $this->causerOverride;
+ }
</file context>
There was a problem hiding this comment.
Spatie documents defaultCauser() as overriding the causer for all activities in its scope, and its resolver checks that override before the supplied subject. We kept that precedence and made it explicit in the guide. causedByAnonymous() still gives an individual entry an anonymous causer.
| * @method static ActivityLogger|TResult when(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) | ||
| * @method static ActivityLogger|TResult unless(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) |
There was a problem hiding this comment.
P3: These facade annotations omit the HigherOrderWhenProxy returned by ActivityLogger::when() and unless() when called without a callback. Include the proxy type so IDEs and static analyzers expose the supported higher-order chaining API.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/activity-log/src/Facades/ActivityLog.php, line 44:
<comment>These facade annotations omit the `HigherOrderWhenProxy` returned by `ActivityLogger::when()` and `unless()` when called without a callback. Include the proxy type so IDEs and static analyzers expose the supported higher-order chaining API.</comment>
<file context>
@@ -0,0 +1,62 @@
+ * @method static TResult withoutLogging(Closure(): TResult $callback)
+ * @method static void beforeLogging(Closure(ActivityContract&Model): void $callback)
+ * @method static ActivityLogManager|TResult defaultCauser(Model|int|string|null $causer, (Closure(): TResult)|null $callback = null)
+ * @method static ActivityLogger|TResult when(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
+ * @method static ActivityLogger|TResult unless(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null)
+ * @method static void macro(string $name, object|callable $macro)
</file context>
| * @method static ActivityLogger|TResult when(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) | |
| * @method static ActivityLogger|TResult unless(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) | |
| * @method static ActivityLogger|\Hypervel\Support\HigherOrderWhenProxy<ActivityLogger, bool>|TResult when(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) | |
| * @method static ActivityLogger|\Hypervel\Support\HigherOrderWhenProxy<ActivityLogger, bool>|TResult unless(Closure|mixed|null $value = null, callable|null $callback = null, callable|null $default = null) |
There was a problem hiding this comment.
The facade now uses the typed manager/logger mixin for conditional methods. This preserves the higher-order proxy and callback types that a generated mixed return would lose. A PHPStan fixture checks the facade call.
Bind buffered inserts and transaction callbacks to the connection that owns the activity. Flush eligible rows in call order across savepoints, keep each coroutine's buffer independent, and preserve per-statement hooks and binary bindings. Read cleanup batches from the writer. Use the model's extraction overrides for both sides of a change. Keep raw values intact, distinguish typed JSON values, and handle partial models and explicitly selected relationships. Track actual restores so ordinary updates and restore events each produce the intended history. Preserve explicit and preassigned causers during nested lookups, restore logging status after callbacks, and support backed-enum log names. Update the generated facade and its type coverage, declare the Composer helper conflict, and document connection selection and buffering behavior. Exercise these paths in package and integration tests, including scoped connections, real queue-worker completion, and competing database writes.
|
@cubic-dev-ai review |
@binaryfire I have started the AI code review. It will take a few minutes to complete. |
There was a problem hiding this comment.
3 issues found across 72 files
Confidence score: 3/5
DetectsChangesRegressionTest.phpleaves Eloquent’s missing-attribute protection enabled, so later tests can fail on partial model access depending on suite order. Restore the setting after the test.ActivityLoggerTest.phppasses aBackedEnumtoActivity::inLog(), which only acceptsstring|array, so the enum-scope test throws aTypeErrorbefore querying. Update the fixture scope to accept the enum.LogOptions.phphardcodesLogOptionsindefaults(), so calling the factory on a subclass loses that subclass type and behavior. Use late static binding.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="tests/ActivityLog/Traits/DetectsChangesRegressionTest.php">
<violation number="1" location="tests/ActivityLog/Traits/DetectsChangesRegressionTest.php:832">
P2: These tests enable Eloquent’s worker-wide missing-attribute protection but never restore it, making the suite order-dependent and causing later tests or test classes to throw on partial model access unexpectedly. Save the prior flag and restore it in a `finally` block (or reset it in the activity-log teardown).</violation>
</file>
<file name="tests/ActivityLog/Support/ActivityLoggerTest.php">
<violation number="1" location="tests/ActivityLog/Support/ActivityLoggerTest.php:235">
P2: This enum-scope assertion passes a `BackedEnum` to the test fixture’s `Activity::inLog()`, whose signature only accepts `string|array`; PHP throws a `TypeError` before the query executes. Update the fixture scope to match the production model’s backed-enum support and normalize enum values.</violation>
</file>
<file name="src/activity-log/src/Support/LogOptions.php">
<violation number="1" location="src/activity-log/src/Support/LogOptions.php:45">
P2: `defaults()` hardcodes the base class, so calling it through a `LogOptions` subclass silently returns a `LogOptions` instance and loses subclass behavior. Use late static binding so this public factory remains extensible.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
|
|
||
| public function testPartialUpdateRefreshDocumentsUnavailableOldValues(): void | ||
| { | ||
| Model::preventAccessingMissingAttributes(); |
There was a problem hiding this comment.
P2: These tests enable Eloquent’s worker-wide missing-attribute protection but never restore it, making the suite order-dependent and causing later tests or test classes to throw on partial model access unexpectedly. Save the prior flag and restore it in a finally block (or reset it in the activity-log teardown).
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/ActivityLog/Traits/DetectsChangesRegressionTest.php, line 832:
<comment>These tests enable Eloquent’s worker-wide missing-attribute protection but never restore it, making the suite order-dependent and causing later tests or test classes to throw on partial model access unexpectedly. Save the prior flag and restore it in a `finally` block (or reset it in the activity-log teardown).</comment>
<file context>
@@ -0,0 +1,1317 @@
+
+ public function testPartialUpdateRefreshDocumentsUnavailableOldValues(): void
+ {
+ Model::preventAccessingMissingAttributes();
+ $articleClass = new class extends Article {
+ use LogsActivity;
</file context>
There was a problem hiding this comment.
The PHPUnit extension already calls Model::flushState() after each test. That resets the missing-attribute flag, including when the test throws.
| $article->name = 'example'; | ||
| $article->save(); | ||
|
|
||
| $this->assertSame('0', Activity::inLog(IntBackedEnum::Draft)->sole()->log_name); |
There was a problem hiding this comment.
P2: This enum-scope assertion passes a BackedEnum to the test fixture’s Activity::inLog(), whose signature only accepts string|array; PHP throws a TypeError before the query executes. Update the fixture scope to match the production model’s backed-enum support and normalize enum values.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/ActivityLog/Support/ActivityLoggerTest.php, line 235:
<comment>This enum-scope assertion passes a `BackedEnum` to the test fixture’s `Activity::inLog()`, whose signature only accepts `string|array`; PHP throws a `TypeError` before the query executes. Update the fixture scope to match the production model’s backed-enum support and normalize enum values.</comment>
<file context>
@@ -0,0 +1,730 @@
+ $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());
</file context>
There was a problem hiding this comment.
This test imports Hypervel’s activity model. Its inLog scope accepts backed enums, and the assertions pass against the fixture database.
| */ | ||
| public static function defaults(): self | ||
| { | ||
| return new self; |
There was a problem hiding this comment.
P2: defaults() hardcodes the base class, so calling it through a LogOptions subclass silently returns a LogOptions instance and loses subclass behavior. Use late static binding so this public factory remains extensible.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/activity-log/src/Support/LogOptions.php, line 45:
<comment>`defaults()` hardcodes the base class, so calling it through a `LogOptions` subclass silently returns a `LogOptions` instance and loses subclass behavior. Use late static binding so this public factory remains extensible.</comment>
<file context>
@@ -0,0 +1,228 @@
+ */
+ public static function defaults(): self
+ {
+ return new self;
+ }
+
</file context>
| return new self; | |
| return new static; |
There was a problem hiding this comment.
The factory matches Spatie’s LogOptions::defaults(), which returns a LogOptions instance. I kept that contract.
A partially selected model can have a foreign ID without its morph type. The temporary relation used for eager loading then points at the source table, where an unrelated row can have the same ID. Mark that relation at construction so lazy reads and touches cannot use the source row. Keep eager loading and custom typed relations on their existing paths. Report an omitted type through the normal strict-mode handler at read time without running unrelated cached cast setters. Use the same marker when collecting activity changes so an unknown target stays out of the audit. Cover projected reads, explicit queries, touches, strict access, and association, including preservation of an unrelated cached JSON value.
Add a Credits section linking to Spatie's Laravel Activity Log and list it in the table of contents, following the other ported package guides.
Keep a selected JSON column or parent path intact when another selector names one of its children. Compare nested cast values by their contents so unrelated updates leave them out of the log and scalar type changes remain visible. Reject invalid relation paths before invoking base model helpers. Use the activity model's insert attributes after preparing timestamps on a snapshot. Custom insert hooks can choose the final columns in either persistence mode while generated IDs stay available to the caller. Respect application transactions inside database tests and flush eligible rows inside the wrapping transaction. If a failed batch leaves rows in memory, let the wrapper discard them on rollback. Cover the write order, failed batch, and finalization against a real transaction manager. Explain the primary key requirement when cleaning keyless activity models and clarify the environment settings and JSON selections in the guide.
|
On the job-attempt flush mentioned in the review summary, Foundation registers an active listener for JobAttempted in registerDeferHandler(). That makes the worker dispatch the event. I verified with a real queue worker that the Activity Log observer writes the buffered row before the attempt returns. |
Let collections serialize their own items when comparing old and new activity values. Reading the raw item list bypassed the collection's Arrayable conversion, and loose object equality could hide a change from a number to a string in a public field. Compare object values through their JSON representation. Keep the fast path for identical values, early exit for arrays, and interval handling. Exercise public-field, Arrayable and JSON-serializable mapped items on both an unrelated update and a change in scalar type. Give both Arrayable test fixtures the return shape their contract expects.
Read the selected value on the model that owns it and honor its cast serializer before comparing or recording changes. A non-backed enum collection can now be audited by case name, including when it is reached through a relation or JSON path. Reuse each JSON root across sibling paths in a snapshot. Let collection roots expose their mapped items in the same form they would record for a whole-column selection. Preserve raw selections and getter overrides. Enum cases and dates returned by getters still use their configured audit formats, while scalar values returned by getters are recorded as supplied.
This adds
hypervel/activity-log, an optional package for recording application activity in a database. An entry can describe an action, the model it affected, who performed it, and any properties the application wants to keep.Models can also use
LogsActivityto record Eloquent events. The model chooses which attributes to log and whether to keep only changes. By default, the logger reads the model as it was at the event. Applications that need database-generated values can opt into a refresh inside the writing transaction.Persistence
Activities are saved immediately by default. Applications can opt into buffering to insert rows in batches. Each coroutine owns its buffer and its current causer. For an activity recorded on a connection with an open transaction, a rollback discards the buffered entry. After commit, a later batch writes it. Applications that need the activity and the domain change to commit together can use immediate writes on the same connection.
Installation and use
Composer discovers the service provider. The application publishes the migration before running it, so it can choose the appropriate morph keys and indexes. The package includes a cleanup command with configurable retention and optional scheduling. The guide covers installation, querying, model events, transaction behavior, and differences from Spatie’s Laravel Activity Log.
Verification
The package tests cover model changes, causer resolution, coroutine isolation, buffer flushing, and rollback. The migration and row-locking tests ran against MySQL, MariaDB, and PostgreSQL. A clean application installed the split package, published and ran the migration, and recorded an activity through the helper.
Note
Add the
hypervel/activity-logpackageActivityEloquent model with query scopes (inLog,causedBy,forSubject,forEvent), theLogsActivity/CausesActivity/HasActivitymodel concerns, a fluentActivityLogger, anactivity()helper, and theActivityLogfacade in ActivityLogManager.phpactivity-log:cleanconsole command and CleanActivityLogAction.php, which deletes old activities in bounded batches, plus a publishable migration and configuration in activity-log.phpcomposer.jsonnow conflicts withspatie/laravel-activitylog, so the two packages cannot be installed together. Also adds small Eloquent changes:SoftDeletes.restore()tracks anisBeingRestored()flag,MorphToplaceholders skip result resolution and touching, andModel.performInsert/performInsertOrIgnorenow sharegetDatabaseAttributesForInsert()in HasAttributes.phpMacroscope summarized 68ab5cf.