ia-php-laravel
Modern PHP 8.4 and Laravel patterns: architecture, Eloquent, migrations, queues, testing. Use when working with Laravel, Eloquent, Blade, artisan, or building/testing a framework-based PHP app. Not for php-src internals, standalone PHP libraries, or general PHP language discussio
Install
npx skills add https://github.com/iliaal/whetstone/tree/master/plugins/whetstone/skills/ia-php-laravel
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install iliaal-whetstone@llmmart
git clone https://github.com/iliaal/whetstone.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole iliaal/whetstone collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
PHP & Laravel Development
Scoped to framework-level PHP. Work on php-src internals or a native PHP extension is C, not PHP: the ia-c-systems skill covers it, including the Zend API conventions (gen_stub arginfo, the request-scoped allocator, custom object handlers, .phpt).
Working rules
- Keep simple CRUD simple; extract cross-model orchestration only when it has a concrete use.
- Validate and authorize at request boundaries; serialize through explicit resources and validate third-party responses.
- Preserve deployed migration history, queued payload compatibility, and concurrent writes.
- Verify cache compilation, queue execution, and HTTP behavior through their real entrypoints when those paths change.
Code Style
declare(strict_types=1)in every file- Happy path last -- guards and errors first, success at the end. Early returns, no
else. - Comments explain why, never what. Never comment tests. If code needs a "what" comment, rename or restructure.
- No single-letter variables --
$exceptionnot$e,$requestnot$r ?stringnotstring|null. Always specifyvoid. Import classnames, never inline FQN.- Widening one parameter to
?Tobliges auditing every call site that forwards the same value -- the sibling call still declaresstring, andnullthrows aTypeErrorthere even with nodeclare(strict_types=1), because coercive mode never coercesnullinto a scalar. Strictness is decided by the file the CALL is written in, never by the callee's file. Full mechanism in common-pitfalls.md. - Validation uses array notation
['required', 'email']for easier custom rule classes - PHPStan level 8+ (
phpstan analyse --level=8); aim for 9 on new projects.@phpstan-type/@phpstan-paramfor generic collection types. The missing-iterable-value-type check lands at level 6 (and every level above it), so any project at 8+ inherits it: use the generic form on every iterable --@return Collection<int, User>,@param array<int, MyObject>-- and array-shape notationarray{first: SomeClass, second: SomeClass}for fixed-key returns; a bareCollectionorarraywill not clear it.
Discipline
- Simplicity first -- every change as simple as possible, minimal code impact
- Only touch what's necessary -- no unrelated changes
- No hacky workarounds -- if a fix feels wrong, step back and implement the clean solution
- New abstraction requires 3+ usage sites; otherwise inline it
- No empty catch blocks -- log or rethrow, never swallow
- Verify before declaring done:
./vendor/bin/phpstan analyse --level=8 && ./vendor/bin/phpunitwith zero warnings - Checkpoint per stage, not only at the end:
migrate:statusafter a migration,route:list --path=<prefix>after routing changes,queue:work --onceafter adding a job,pint --testbefore the PR -- each catches its failure class while the change is small
References
- laravel-ecosystem.md -- Notifications, Task Scheduling, Custom Casts
- testing.md -- PHPUnit essentials, data providers, running tests
- feature-testing.md -- Auth, validation, API, console, DB assertions
- mocking-and-faking.md -- Facade fakes, action mocking, Mockery
- factories.md -- States, relationships, sequences, afterCreating hooks
- production-performance.md -- OPcache, JIT, preloading, deploy caches
- common-pitfalls.md -- event-layer bypasses, FK cascades, pivot writes, resource and request-shape traps
- pitfalls-deep.md -- afterCommit alternatives, observer desync, jsonb race, savepoints, validation-rule internals
Task-specific references
Read the relevant reference before implementing or reviewing the matching behavior:
- For PHP features, controller/action design, routing, resources, or external APIs: framework-patterns.md.
- For migrations, Eloquent writes, casts, queues, job payloads, or production startup: persistence-and-jobs.md.
- For PHPUnit work or changes affecting events, serialization, validation, or lifecycle behavior: testing-and-pitfalls.md.
Existing specialized references, when the corresponding topic applies:
Files (whetstone)
-
references
-
common-pitfalls.md 19.9 KB
# Laravel Common Pitfalls — mechanism and fix Mechanism and fix for the one-line entries in SKILL.md's Common Pitfalls list, plus the request-lifecycle and resource entries linked from Laravel Architecture and API Resources. Entries whose SKILL.md bullet links to `pitfalls-deep.md` are documented there instead; nothing is repeated across the two files. ## Model events and observers ### Query-builder update() bypasses the event layer `Model::query()->where(...)->update([...])` and `Relation::update()` are query-builder writes: no model events fire, so observers, `Auditable` traits and `static::saving` / `static::updating` hooks are all bypassed. Anything those hooks enforce -- an audit row, a search-index sync, a derived-column refresh -- is silently void on that path. Fix: `lockForUpdate()` + `save()` inside a transaction keeps events firing; take the raw mass update only with an explicit `// intentionally bypasses <Observer>` comment naming what is skipped. ### FK cascades and the Eloquent event layer are different layers `->cascadeOnDelete()` is a database constraint. The two failures are mirror images and both are silent. **The cascade fires and the event layer does not.** The database removes the children itself, Eloquent never loads or deletes them, no `deleted` event fires, and no observer, `Auditable` trait, search sync or storage cleanup runs for them -- while the parent's own delete IS audited, so the log looks populated and contains no record of what the cascade took with it. The tell in review: a sibling path in the same codebase deleting children row by row with a comment explaining why. That comment is the codebase saying it depends on model events, so every FK cascade in that family is a hole in whatever the events enforce. **The cascade does not fire at all when the parent soft-deletes.** `SoftDeletes` intercepts `delete()` at the model layer and rewrites it as `UPDATE ... SET deleted_at = ...`; `ON DELETE CASCADE` only fires on real `DELETE` SQL. The parent row stays alive, the children's FK still points at a live row, and the cascade is a pure no-op for every path that calls `$parent->delete()` -- usually the dominant one. It applies only to the `forceDelete()` minority, with no warning at migration time and no failure at runtime. Same trap in any ORM that overlays soft delete on an SQL referential action. When a change adds a delete path on a parent, answer both: do the children die by cascade or row by row, and does the parent use `SoftDeletes`? `grep` the parent model for `use SoftDeletes;` and classify every `->delete()` / `->forceDelete()` call site. Delete per row inside the transaction wherever an event-layer invariant must hold. On the test side, write cascade assertions as `$parent->forceDelete()`: `forceDelete()` is defined on the base Eloquent `Model`, not only on the trait, so it is safe to write before `SoftDeletes` lands and stays green when the trait arrives from the target branch (verify at the pinned version rather than trusting that). ### Observer deleting() cleanup at parent scope nukes siblings `Storage::deleteDirectory($parent->uploadPath)` in a child's `deleting()` observer wipes storage for every sibling while their rows still point at the deleted keys. Detection: when a single-row `delete()` has an observer, check whether each hook operates at row scope or parent scope. Fix: scope the cleanup to the row's own paths, or move it to an Action that knows the sibling count. ### BelongsToMany pivot writes fire no model events without using() `attach` / `detach` / `sync` / `updateExistingPivot` are query-builder writes -- without `using()`, no pivot model events fire and observers and audit traits record nothing. Fix: make the pivot a real `Pivot` model (`->using(PivotModel::class)`) and write through it with `firstOrCreate(...)->fill([...])->save()`. Qualification for one path: `syncWithoutDetaching([$id => [...]])` is attach-or-UPDATE, not insert-only, and `using()` decides both idempotency and whether events fire. It is `sync($ids, false)` -- the `false` disables detaching and nothing else -- and `attachNew()` routes an already-attached id with a non-empty attribute array to `updateExistingPivot()`. Without `using()` that is an unconditional `UPDATE` plus pivot timestamps and no model events, so re-running with the same value still writes. With `using(CustomPivot::class)` it is dirty-checked through `fill()->isDirty()`, issues no query when unchanged, and DOES fire normal Eloquent events on the pivot subclass. "Is it idempotent?" is answered by `grep -n 'using(' <Model>.php`; "does it clobber?" is answered by the pivot column's value set (a two-case enum has nothing to lose; a `draft`/`verified`/`completed` status does). **`sync()` reads the RAW pivot table, so a relationship-level `where` does not filter it.** `sync()` / `syncWithoutDetaching()` resolve the current attachments through `getCurrentlyAttachedPivots()` -> `newPivotQuery()`, and `newPivotQuery()` is built on `newPivotStatement()` = `$this->query->getQuery()->newQuery()->from($table)` -- a fresh builder inheriting none of the relationship's constraints. It re-applies only `pivotWheres`, `pivotWhereIns` and `pivotWhereNulls` (populated by `wherePivot()` / `wherePivotIn()` / `wherePivotNull()`) plus the parent-key constraint. So a soft-delete filter written as `belongsToMany(...)->whereNull('pivot_table.deleted_at')` does NOT reach sync's current-set query: the soft-deleted row counts as attached, sync skips it, and nothing is re-inserted or revived. That makes "sync resurrects a soft-deleted pivot" a false positive for that shape, and it makes the intended hiding not work for `wherePivot`-style filtering either. Only `wherePivotNull('deleted_at')`, `wherePivot(...)`, or a `using(SoftDeletingPivot)` pivot reaches it. Decide by reading which builder the filter lands on, not by the relationship's apparent semantics. Version caveat: the closure form `wherePivot(fn ($q) => ...)` is recorded into `pivotWheres` (and so reaches `sync()`, `detach()`, and `updateExistingPivot()`) only from Laravel 13.31.0 (framework PR #61488); earlier releases applied the closure to the relationship query and silently dropped it from the pivot query, so on those versions only the scalar `wherePivot($column, $op, $value)` form is safe for this purpose. ## Serialisation and resources ### date:<fmt> cast format reaches toArray(), not JsonResource::resolve() A `date:<fmt>` cast changes `$model->toArray()` and nothing else. A resource returning the raw attribute emits Carbon's ISO 8601 and ignores the cast, so a cast-format change is not a wire-format change unless the path uses `toArray()` directly (Filament, DTO hydration, `json_encode($model)`). Verify with a live reproducer through the real serialisation path before flagging either direction. ### A nested JsonResource wrapping null never runs the child's toArray() `ConditionallyLoadsAttributes::filter()` replaces the whole value on `$value instanceof self && is_null($value->resource)` before `resolve()` reaches the child, so the nested resource serialises to JSON `null` and an overriding `toArray()` that would fatal on a null resource is never entered. `Resource::make($nullable)` and an explicit `$nullable ? Resource::make(...) : null` are byte-identical on the wire. The base-class `is_null($this->resource) => []` guard is not the mechanism and is overridden in every real resource. Probe resource serialisation through the parent's `resolve($request)`. `json_encode(['k' => Child::make(null)])` skips `filter()` entirely and throws, which reads as a production 500 and is not one. ### parent::toArray() in a resource subclass is the parent RESOURCE's whitelist `JsonResource::toArray()` returns `$this->resource->toArray()` -- every non-hidden model attribute -- so `$data = parent::toArray($request)` reads as "this serialises the whole model, and a newly added sensitive column leaks unless it is in `$hidden`". That holds only when the resource extends `JsonResource` or `ResourceCollection` **directly**. When it extends another resource, `parent::` is that resource's `toArray()`, which is usually an explicit field whitelist that never touches the new column -- and the attribute is not serialised at all, regardless of `$hidden`. `parent::` is a call up the class hierarchy, not a synonym for the framework default. Resolve the `extends` chain to the class that actually extends `JsonResource` and read that class's `toArray()`; if any ancestor returns an explicit array literal, the spread stops there. Confirm with a grep for the column name across the resource directory -- zero hits is dispositive. The inverse mistake is just as real, so the rule is symmetric: read the resolved `toArray()`, never infer it from the base class name. ## Validation and request shape ### Nested-array validation accepts scalar elements `'items.*.name' => 'string'` does not enforce that each `items.*` is an array. Scalars pass, and then `$data['items'][0]['name']` yields `null` (a blank row) or a `TypeError` (a 500). Always pair per-key rules with `'items.*' => 'array'`. ### array:a,b restricts which keys may appear and requires none of them `'field' => ['array:a,b']` is a whitelist, not a requirement -- pairing it with per-key `sometimes` rules is the intended shape. The trap is downstream: OpenAPI generators publish that key list as the object's `required` array, so the generated request contract marks every key of a section mandatory while every per-key rule is optional, and a `sometimes|nullable` enum key publishes as required AND non-nullable. Never read a generated `required` list as the endpoint's contract; open the FormRequest. The control that proves the list is evidence about `array:` and not about the endpoint: a sibling field with a bare `array` rule emits no `required` at all. ### Empty arrays and absent keys collapse under empty() or truthiness `empty($data['key']) ? null : ...` as an absence test cannot distinguish `{"key": []}` from a key that was never sent; a plain truthiness check also loses that distinction. `isset()` and `?? null` distinguish an empty array from absence, but conflate an explicit `null` with absence. Use `array_key_exists()` when key presence must remain distinct even for `null`. An `empty()` guard on a Remove / Clear-all affordance can silently skip the emptied collection: 200, nothing written, and a refetch restores what the user deleted. Removing *some* items works, because a non-empty array is not `empty`, so the defect is exactly the remove-all case -- say so, or the report reads as "the whole feature is broken" and cannot be reproduced. Two amplifiers. Form and query encoding genuinely drop empty arrays (`http_build_query(['key' => [], 'other' => 'v'])` is `other=v`), so over `x-www-form-urlencoded` or `multipart/form-data` the empty collection and the absent key are the same bytes and no server-side guard can recover the distinction -- a payload that must carry "explicitly empty" needs a JSON body. And a probe that builds the request with form parameters measures the absent case under an "empty" label, returning the right answer for the wrong reason; a non-empty control passes and proves nothing, because a non-empty array survives encoding. Print the parsed input's own `array_key_exists` verdict and run three rows -- empty, non-empty, genuinely absent. Widening the gate so `[]` means "clear" is a producer-side change, not just a consumer-side one: every upstream hook that can synthesise an empty collection -- `prepareForValidation()`, a normaliser that `merge()`s filtered rows back, a serializer default -- now reaches a destructive branch, and it runs before the validator, so the per-item `required` rules never see those shapes. Sweep the request pipeline for `merge(`, `replace(`, `array_filter`, `?? []` before shipping the one-line fix. ### FormRequest authorize() = true plus a controller-body 404 leaks existence `ValidatesWhenResolvedTrait::validateResolved()` runs `prepareForValidation()`, then `passesAuthorization()`, then validation -- and only then does the controller body run. An ownership check written as `abort_if(...)` / `abort(404)` inside the controller therefore sits *after* validation, so a foreign-but-existing id combined with an invalid body returns 422 while a non-existent id returns 404 at route binding. An authenticated caller separates "belongs to another tenant" from "does not exist" by probing with `{}`. The same shape appears when a FormRequest with no `authorize()` runs an `after()` closure that does a global lookup: it 422s on existence before the controller's `$this->authorize(...)` can 403. Tests mask it almost universally, because the natural "other tenant gets 404" test posts a *valid* payload and the controller check fires. Fix: move the ownership and type check into `FormRequest::authorize()` and override `failedAuthorization()` to `throw new NotFoundHttpException`. Regression test shape: foreign-but-existing id plus an empty body must return 404, not 422. ## Collections ### Collection::unique() compares loosely `Collection::unique($key = null, $strict = false)` defaults to loose comparison: with no key it is `array_unique($items, SORT_REGULAR)`, and with a key it is `in_array($id, $exists, false)`. PHP compares two numeric-looking strings as numbers, so `"00123" == "123"` and `"1e3" == "1000"` collapse to one element. Any dedup, merge or conflict-detection step that leans on `->unique()` to decide "are these the same value?" silently treats distinct identity strings as equal -- a merge-or-throw design that counts distinct values then sees `count() === 1`, concludes there is no conflict, and drops the row that held the other value. Fix: `->uniqueStrict()` (byte equality) for identity columns that can hold numeric-looking values -- ids, phone numbers, ZIPs, licence and visa numbers, any code with leading zeros. Same rule for `array_unique` without `SORT_STRING` and `in_array` without `$strict`. ## Logging and exceptions ### QueryException::getMessage() interpolates raw bindings The message carries the query's raw bindings plus the host and database name, so any log sink or APM that records exception messages leaks parameter values on every failed query. Recent versions add a per-connection `mask_bindings_in_exception_messages` option (env `DB_MASK_BINDINGS`), default off; enable it in production where query exceptions reach logs, after confirming the option exists in the installed version. ## PHP type semantics ### Widening one parameter to ?T obliges auditing every call site that forwards the value The sibling call downstream still declares `string`, and `null` throws a `TypeError` there -- including in a file with no `declare(strict_types=1)`, because coercive mode coerces between scalars and never coerces `null` into one. The PHP 8.1 "passing null to parameter of type string is deprecated" behaviour is internal-functions-only; user functions have thrown on `null` since PHP 7.0. So "no strict_types, it'll coerce" is not a safety net, and the crash lands on the exact null-input case the widening was for. The mode is decided by the file the CALL is written in, never by the file declaring the callee, so "the callee declares strict types, therefore this 500s" is a phantom -- read the caller's first lines. Where the caller is coercive the boundary silently coerces instead of throwing (an object carrying `__toString()` becomes a string), and the follow-up question is whether that string is usable downstream, not whether it threw. `php -r` is coercive; adding `declare(strict_types=1);` to the same snippet reproduces a strict caller, so both modes are one command apart. ## Container lifetimes ### #[Scoped] resets in exactly one place: the queue worker, between jobs `forgetScopedInstances()` has a single caller, so under PHP-FPM `#[Scoped]` and `#[Singleton]` are indistinguishable -- a fresh container per request resets everything anyway -- and Octane does not reset it on the HTTP path unless the app wires it. None of the reset points is a database transaction boundary: a scoped service that fills a memo from rows written inside `DB::transaction()` keeps that memo after the rollback, for the rest of the request or job. Lazy invalidation (`unset` the key, re-query on the next read) is rollback-safe by construction. Converting it to a write-through refill as an optimisation silently trades that away, and no test that never rolls back mid-request will show it. ## Deploy and boot ### A set -e container entrypoint is a fail-fast contract Only put steps in it whose failure should genuinely block traffic. Migrations and `config:cache` qualify. Docs generation, optional caches, and any strict artisan command that exits non-zero on one bad annotation do not: the non-zero exit aborts the entrypoint before php-fpm and the workers start, so the container never boots and every deploy of that image fails. Amplifier to check for: a step that only runs outside local (`if ($this->app->isLocal()) return;`) is green on the author's machine and bricks staging and production only. Move non-critical steps after the workers start, or wrap them so a failure degrades that one feature (a 404 docs page) rather than the service. ### route:cache serializes closure actions rather than rejecting them Laravel 12 `route:cache` no longer throws `LogicException: Uses Closure`. `Route::prepareForSerialization()` hands the action to `SerializableClosure`, which serializes whatever `$this` closed over -- and a closure that captures `$this` from a service provider drags the bound application container in with it, so the cached payload balloons. Verified on Laravel 12.68 it still terminates: it serializes, it does not diverge. Unbounded blowup (`Maximum call stack size / Infinite recursion?`) requires an actual reference cycle, for example the provider storing the closure back onto its own property, which the container then re-serializes on the next pass. Plain closure routes cache fine; group and middleware closures are fine; only serialized ACTION closures matter. Fix: move the handler to an invokable controller, or capture a local `use ($var)` instead of reaching through `$this`. Verify with `php artisan route:cache; echo $?` with the route present and removed. This is the opposite of `config:cache`, which cannot represent a closure at all and aborts the deploy step. ## Migrations ### The migrations row is written after up() returns and outside its transaction `Migrator::runUp()` calls `runMigration()` and then, as a separate statement, `repository->log()`. A process killed in that window leaves a committed-but-unrecorded migration. On a deploy model that runs `migrate --force` at container preboot and can kill the task mid-boot, the migration stays "pending", every subsequent container re-runs `up()`, hits `relation already exists` / `type already exists`, and crash-loops -- bricking every further deploy, not just this one. Fix with an early-return idempotency guard at the top of `up()`: `if (Schema::hasTable('the_main_table')) { return; }`. That single-object guard is a valid proxy for "everything exists" ONLY if the whole body is one transaction; any statement Postgres cannot run inside a transaction is skipped on re-run and ships a partial schema (`ia-postgresql` skill, Migration Safety core rules). ## Outbound HTTP ### Http::timeout() is per redirect hop, not per logical call It becomes `CURLOPT_TIMEOUT_MS` on one curl handle, and Guzzle follows redirects itself -- `RedirectMiddleware` re-invokes the handler per hop with the same options, so each hop gets a fresh full budget. With the default `max` of 5 the ceiling is `(max_redirects + 1) x timeout`: 90s at `timeout(15)`, not 15s. A hanging endpoint IS bounded correctly, because curl aborts the hop and the exception ends the call -- so `rows x timeout` is the right figure for "every request hangs" and the wrong one for a worst case, since six hops each answering just under the timeout reaches `6N`. Anything sized off that aggregate inherits the error: a `withoutOverlapping()` expiry, a queue `$timeout`, a task timeout, an SLO. `Http::fake()` does not model redirect latency, so this is not reproducible in a test. -
factories.md 3.5 KB
# Factory Patterns > When to read: when writing or refactoring Laravel model factories — basic shapes, states, sequences, relationships, and seed-vs-test boundaries. ## Basic Factory ```php class PostFactory extends Factory { public function definition(): array { return [ 'title' => fake()->sentence(), 'slug' => fake()->slug(), 'content' => fake()->paragraphs(3, true), 'published_at' => fake()->dateTimeBetween('-1 year', 'now'), 'user_id' => User::factory(), 'category_id' => Category::factory(), ]; } } ``` ## States Name states as adjectives or past participles -- they describe what the model IS: ```php public function unpublished(): static { return $this->state(fn (array $attributes) => [ 'published_at' => null, ]); } public function published(): static { return $this->state(fn (array $attributes) => [ 'published_at' => now(), ]); } // Usage $post = Post::factory()->unpublished()->create(); ``` ## Relationships ```php // Has many -- creates parent with 3 children $post = Post::factory() ->has(Comment::factory()->count(3)) ->create(); // Belongs to -- creates children for specific parent $posts = Post::factory() ->count(3) ->for($user) ->create(); // Combined $post = Post::factory() ->published() ->for($user) ->has(Comment::factory()->count(3)) ->has(Tag::factory()->count(2)) ->create(); ``` ## afterCreating Hooks For side effects that require a persisted model: ```php public function configure(): static { return $this->afterCreating(function (Post $post) { $post->tags()->attach( Tag::factory()->count(3)->create() ); }); } ``` ## Sequences ```php $users = User::factory() ->count(3) ->sequence( ['role' => 'admin'], ['role' => 'editor'], ['role' => 'viewer'], ) ->create(); ``` ## Usage in Tests ```php // Single model $user = User::factory()->create(); // With overrides $user = User::factory()->create(['email' => 'specific@test.com']); // Multiple $posts = Post::factory()->count(10)->create(); // In-memory (no DB write) $user = User::factory()->make(); ``` Always use `create()` for feature tests (persists to DB). Use `make()` only for unit tests that need a model instance without persistence. ## Factories build the model unguarded `Factory::makeInstance()` wraps `new $model($attributes)` in `Model::unguarded(...)`, so a factory can set a column that `$fillable` would reject and `$guarded` would block. A non-fillable fixture attribute therefore needs a production-writer check; it is not proof of an unreachable row. `$fillable` governs mass assignment, while direct property assignment followed by `save()`, query-builder writes, observers, or database defaults can supply the same value. For any test that pins a guard, a filter, or a "this column decides X" behaviour, compare the factory payload with the model's mass-assignment rules, then trace the actual production writers for mismatches. Compare sibling fixtures using `null` and real values against those write paths. Reject a fixture as unreachable only after establishing that no relevant production path can produce its preconditions; do not discard an assertion solely because an attribute is absent from `$fillable`. The neighbouring question is the same one in the other direction: for every precondition the fixture supplies, name the production actor that supplies it. "Nothing does" is the finding. -
feature-testing.md 6.4 KB
# Feature Testing Patterns > When to read: when writing Laravel feature tests for HTTP, auth, session, file upload, or other request-cycle scenarios. ## Authentication Testing ```php public function test_authenticated_user_can_access_endpoint(): void { $user = User::factory()->create(); $this->actingAs($user) ->getJson('/api/profile') ->assertOk() ->assertJson(['data' => ['id' => $user->id]]); } public function test_guest_receives_401(): void { $this->getJson('/api/profile')->assertUnauthorized(); } // Sanctum with specific abilities public function test_user_with_wrong_ability_gets_403(): void { $user = User::factory()->create(); Sanctum::actingAs($user, ['view-posts']); $this->postJson('/api/posts', ['title' => 'Test']) ->assertForbidden(); } ``` ## Authorization Testing ```php public function test_user_cannot_delete_others_posts(): void { $user = User::factory()->create(); $post = Post::factory()->create(); // different user $this->actingAs($user) ->deleteJson("/api/posts/{$post->id}") ->assertForbidden(); } public function test_admin_can_delete_any_post(): void { $admin = User::factory()->admin()->create(); $post = Post::factory()->create(); $this->actingAs($admin) ->deleteJson("/api/posts/{$post->id}") ->assertNoContent(); $this->assertDatabaseMissing('posts', ['id' => $post->id]); } ``` ## Validation Testing ```php public function test_post_requires_title_and_content(): void { $user = User::factory()->create(); $this->actingAs($user) ->postJson('/api/posts', []) ->assertUnprocessable() ->assertJsonValidationErrors(['title', 'content']); } ``` ### assertJsonValidationErrors passes on ANY error for the field `assertJsonValidationErrors(['phone'])` asserts only that `phone` appears as an errored key. It does not check which rule produced the message, and Laravel stops at the first failing rule for an attribute -- so a fixture that trips an earlier format rule satisfies a test named `test_..._validates_unique_phone`. Deleting the rule under test leaves the test green, and the suite reads as coverage of a rule it never reaches. The second source escapes a rule-chain read entirely: the competing rejection is application code throwing `ValidationException::withMessages(['field' => ...])` further down the request -- a service-layer floor, a domain guard, a controller precondition. It is not in the FormRequest, so reading `rules()` finds nothing, and it lands on the identical key. Three steps, in order: 1. Confirm the fixture would PASS every rule earlier in the chain than the one under test. 2. Delete the rule and re-run. Still green means the rule is not under test. Do this mechanically rather than by reading, whenever a `ValidationException` exists anywhere on the path. 3. Tighten to the message form -- `assertJsonValidationErrors(['field' => 'must not be greater than'])`, which substring-matches the message -- and prove it discriminates in both directions: green with the rule present, red with it deleted. The failure output names the guard that was really answering. Reviewer tell, free to run: when a change adds both a validation rule and a service-layer guard that reject on the same key, the new rule's test almost certainly cannot see it. ## API Response Structure ```php public function test_returns_paginated_posts(): void { Post::factory()->count(30)->create(); $this->getJson('/api/posts') ->assertOk() ->assertJsonStructure([ 'data' => [['id', 'title', 'content', 'created_at']], 'meta' => ['total', 'current_page', 'last_page'], ]) ->assertJsonCount(15, 'data'); } ``` ## Fluent JSON Assertions For complex API responses, use `AssertableJson`: ```php use Illuminate\Testing\Fluent\AssertableJson; public function test_user_api_response_shape(): void { $user = User::factory()->create(); $this->actingAs($user) ->getJson('/api/profile') ->assertJson(fn (AssertableJson $json) => $json->has('data', fn ($j) => $j->where('id', $user->id) ->where('email', $user->email) ->whereType('created_at', 'string') ->etc() ) ); } ``` ## Database Assertions ```php public function test_creates_record_with_correct_attributes(): void { $user = User::factory()->create(); $this->actingAs($user) ->postJson('/api/posts', ['title' => 'Test', 'body' => 'Content']); $this->assertDatabaseHas('posts', [ 'title' => 'Test', 'user_id' => $user->id, ]); } public function test_soft_deletes_record(): void { $post = Post::factory()->create(); $this->actingAs($post->user) ->deleteJson("/api/posts/{$post->id}"); $this->assertSoftDeleted('posts', ['id' => $post->id]); } ``` ## N+1 Query Count Testing ```php public function test_index_avoids_n_plus_one(): void { Post::factory()->count(10)->create(); $this->expectsDatabaseQueryCount(2); // 1 posts + 1 users (eager loaded) $this->getJson('/api/posts')->assertOk(); } ``` ## Console / Artisan Command Testing ```php public function test_inspire_command_succeeds(): void { $this->artisan('inspire')->assertSuccessful(); } public function test_command_output(): void { $this->artisan('greet', ['name' => 'Taylor']) ->expectsOutput('Hello, Taylor!') ->assertSuccessful(); } public function test_interactive_command(): void { $this->artisan('make:user') ->expectsQuestion('What is the name?', 'John') ->expectsQuestion('What is the email?', 'john@example.com') ->expectsConfirmation('Are you sure?', 'yes') ->expectsOutput('User created!') ->assertSuccessful(); } public function test_scheduled_command_runs_daily(): void { $events = collect(app(Schedule::class)->events()) ->filter(fn ($e) => str_contains($e->command, 'backup:run')); $this->assertCount(1, $events); $this->assertSame('0 0 * * *', $events->first()->expression); } ``` ## Debugging Helpers ```php // Show full exception stack trace instead of HTTP error response $this->withoutExceptionHandling()->get('/broken'); // Follow redirects automatically $this->followingRedirects()->post('/login', $creds)->assertSee('Dashboard'); // Skip specific middleware for testing $this->withoutMiddleware(ThrottleRequests::class)->get('/api/posts'); ``` -
framework-patterns.md 8 KB
# Framework and boundary patterns ## Modern PHP (8.4) Use when applicable -- no explanatory comments for these in generated code: - Readonly classes/properties for immutable data; constructor promotion with readonly - Enums with methods and interfaces for domain constants - Match expressions over switch - First-class callable syntax `$fn = $obj->method(...)` - Fibers for cooperative async when Swoole/ReactPHP not available - DNF types `(Stringable&Countable)|null` for complex constraints - Property hooks: `public string $name { get => strtoupper($this->name); set => trim($value); }` - Asymmetric visibility: `public private(set) string $name` -- public read, private write - `new` without parentheses in chains: `new MyService()->handle()` - `array_find()`, `array_any()`, `array_all()` -- native array search/check without closures wrapping Collection ## Laravel Architecture - **Escalate structure only when it pays for itself.** Simple CRUD → a fat Eloquent model + Form Request is correct; do not add layers. Reach for an **Action class** when an operation crosses model boundaries or gains a 3rd caller. Extract a **non-Eloquent domain object** only when a business rule needs testing without booting the DB, or protects an invariant the model can't. Default down the ladder, not up -- an unused abstraction is a defect, not foresight. - **Thin controllers** -- only validate, call service/action, return response. Domain behavior (scopes, accessors, relationships) lives in models; cross-cutting orchestration in service classes. - **Never call `env()` outside `config/`.** Wherever `php artisan config:cache` has run (the deploy sequence requires it, so typically production), every `env()` call outside a config file returns `null` -- silently, with no error. Read through `config('services.github.token')` and put third-party credentials in `config/services.php` rather than inventing a new config file. - **A closure inside a `config/*.php` file breaks `config:cache`.** The cache file is written with `var_export`, which cannot represent a closure, so a hook registered as `fn ($event) => ...` works locally and aborts the deploy step with `Your configuration files are not serializable`. Register callables as `[SomeClass::class, 'method']` arrays. This is the opposite of `route:cache`, which serializes closure actions rather than rejecting them (Routing, below). - **Service classes** for business logic with readonly DI: `__construct(private readonly PaymentService $payments)` - **`#[Scoped]` resets in exactly one place in the framework: the queue worker, between jobs** -- never at a transaction boundary, so a memo filled inside `DB::transaction()` survives the rollback for the rest of the request or job. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). - **Action classes** (single-purpose invokable) for operations crossing service boundaries - **Form Requests** for all validation -- never inline in controllers, never inside services. Add `toDto()` so services receive typed, pre-validated data; internal code trusts that input was validated at the boundary. - **An ownership check in the controller body runs AFTER validation, so a foreign-but-existing id plus an invalid payload returns 422 while a non-existent id returns 404 -- an existence oracle.** Move it into `FormRequest::authorize()` with `failedAuthorization()` throwing `NotFoundHttpException`; the natural "other tenant gets 404" test posts a valid payload and cannot see it. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). - Conditional validation: `Rule::requiredIf()`, `sometimes`, `exclude_if` - **`'field' => ['array:a,b']` restricts which keys may appear; it requires none of them** -- but OpenAPI generators publish that key list as the object's `required` array, so never read a generated `required` list as the endpoint's contract. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). - **Events + Listeners** for side effects (notifications, logging, cache invalidation) -- not in services. Name events past-tense in business terms (`OrderPlaced`, not `OrderRecordUpdated`). Carry IDs and changed facts in the payload, **not the full Eloquent model** -- `SerializesModels` re-fetches by key when a queued listener runs, so a model passed in-memory goes stale (same desync class as the observer/stale-copy pitfall below). - Feature folder organization over type-based past ~20 models ## Routing - Scoped route model binding to prevent cross-tenant access: `Route::scopeBindings()->group(fn() => ...)` - `Route::model('conversation', AiConversation::class)` for custom binding resolution - API resource routes: `Route::apiResource('posts', PostController::class)` -- index/store/show/update/destroy without create/edit - **Laravel 12 `route:cache` serializes closure actions instead of throwing `LogicException: Uses Closure`**, so a closure capturing `$this` from a service provider drags the bound container into the cached payload. It balloons but still terminates; unbounded blowup needs a real reference cycle. Fix: an invokable controller, or `use ($var)` instead of `$this`. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). ## API Resources - `whenLoaded()` for relationships -- prevents N+1 in responses - `when()` / `mergeWhen()` for permission-based fields; `whenPivotLoaded()` for pivot data - `withResponse()` for custom headers, `with()` for metadata (version, pagination) - **`parent::toArray($request)` calls the parent RESOURCE's `toArray()`, not the framework's attribute spread.** It spreads every model attribute only when the class extends `JsonResource` directly; through an ancestor resource returning an explicit array literal the column is never serialised, `$hidden` or not. Resolve the `extends` chain before claiming either. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). - **A nested `JsonResource` wrapping `null` serialises to JSON `null`, and the child's `toArray()` never runs** -- `filter()` replaces the value before `resolve()` reaches the child, so `Resource::make($nullable)` and an explicit ternary are byte-identical on the wire. Probe through the parent's `resolve($request)`, never `json_encode()`. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). ## API Design - **Contract-first**: define the API Resource (response contract) and Form Request (input contract) before writing the controller. - Never return raw models or `toArray()` from controllers -- Resources control exactly what's serialized. Every observable field, ordering, or timing becomes a caller dependency (Hyrum's Law). - **Add, don't modify**: new fields/endpoints over changing or removing existing ones. Deprecate first (`@deprecated` in OpenAPI/docblock), remove in a later version. - **Consistent envelope**: `{ "success": bool, "data": ..., "error": null, "meta": {} }`. Normalize `ValidationException`, `ModelNotFoundException`, `AuthorizationException`, and application errors to `{ "success": false, "error": { "code": "...", "message": "..." } }` in the exception handler -- callers build error handling once. - **Isolate third-party SDKs behind an adapter class.** Catch vendor exceptions (`GuzzleHttp\Exception\ClientException`, `Stripe\Exception\*`) inside the adapter and rethrow as domain exceptions (`PaymentFailedException`) -- never let a Guzzle/Stripe exception bubble into a controller or service. - **Never return the raw vendor object** (`Stripe\Charge`, a Guzzle `Response`) from an adapter -- map it to a DTO first. Otherwise every vendor field becomes a caller dependency (Hyrum's Law), same as returning raw models on egress. - **Third-party responses are untrusted data**: validate shape and content through the DTO before use in logic or rendering. Inject the specific client/credentials the adapter needs, not the whole config or container. - **`Http::timeout($n)` is per redirect hop, not per logical call** -- Guzzle re-invokes the handler per hop with the same options, so the ceiling is `(max_redirects + 1) x timeout`: 90s at `timeout(15)`. Anything sized off that aggregate inherits the error (lock expiries, queue `$timeout`, SLOs). Full mechanism in [common-pitfalls.md](./common-pitfalls.md). -
laravel-ecosystem.md 7 KB
# Laravel Ecosystem Patterns > When to read: when reaching for ecosystem features — notifications, queues, broadcasting, vector search, scheduling, file storage, mail — and needing the canonical Laravel approach. ## Notifications Multi-channel dispatch -- mail, SMS, Slack, database -- from a single notification class. ```php // Create: php artisan make:notification OrderShipped class OrderShipped extends Notification implements ShouldQueue { use Queueable; public function via(object $notifiable): array { // Channel selection per user preference return $notifiable->prefers_sms ? ['vonage'] : ['mail', 'database']; } public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->subject('Order Shipped') ->line("Order #{$this->order->id} has shipped.") ->action('Track Order', url("/orders/{$this->order->id}")); } public function toArray(object $notifiable): array { // Stored in `notifications` table for in-app display return ['order_id' => $this->order->id, 'status' => 'shipped']; } } // Dispatch $user->notify(new OrderShipped($order)); // Bulk (uses queue automatically) Notification::send($users, new OrderShipped($order)); ``` - Always implement `ShouldQueue` -- notifications are side effects, never block the request - Use `toArray()` for database channel -- powers in-app notification feeds - Read: `$user->unreadNotifications`, mark: `$notification->markAsRead()` - Rate limit with `ShouldBeUnique` to prevent notification spam ## Broadcasting Server-side drivers in Laravel 13: Reverb (first-party WebSocket server, `php artisan install:broadcasting --reverb`), Pusher Channels, Ably, plus `log` for local debugging and `null` for tests. All three real-time drivers speak the Pusher channel protocol to Echo over a persistent WebSocket. - **Mercure driver** (`MercureBroadcaster`, merged into the 13.x branch after 13.31.0; confirm the installed release ships `Illuminate\Broadcasting\Broadcasters\MercureBroadcaster` before depending on it, and expect the published docs to lag). Transport is Server-Sent Events: the app publishes updates over HTTP to a Mercure hub (a standalone hub, or FrankenPHP's built-in one, which needs no `url`), and browsers subscribe with `EventSource`, so the application stack runs no WebSocket server process. Channel authorization is a JWT the hub validates (`secret`/`subscribe_secret` config; the hub multiplexes every joined channel over one connection under one token), `private-encrypted-*` channels are end-to-end encrypted with an `encryption_key` the hub never sees, and presence channels are never encrypted because member payloads go through the hub's subscription API. ## Vector Search - **Vector search** (Laravel 13, needs the Laravel AI SDK): `whereVectorSimilarTo('embedding', $queryEmbeddingOrText, minSimilarity: 0.4)` filters by cosine similarity (0.0-1.0) and orders most-similar first (`order: false` disables that); `selectVectorDistance(..., as: 'distance')`, `whereVectorDistanceLessThan()`, and `orderByVectorDistance()` expose raw distance. A string argument is embedded on the fly; pass a pre-computed array to skip the provider call. Supported on PostgreSQL with `pgvector` (`Schema::ensureVectorExtensionExists()`, `$table->vector('embedding', dimensions: 1536)->index()`), MariaDB 11.7+, and MongoDB via the Laravel MongoDB package; not MySQL or SQLite. ## Task Scheduling Define recurring tasks in `routes/console.php`: ```php // Artisan commands $schedule->command('reports:generate')->dailyAt('02:00')->withoutOverlapping(); $schedule->command('cache:prune-stale-tags')->hourly(); // Closures for simple tasks $schedule->call(fn () => DB::table('sessions')->where('last_active', '<', now()->subDay())->delete()) ->daily() ->name('cleanup-sessions') ->withoutOverlapping(); // Queue jobs $schedule->job(new ProcessDailyMetrics)->dailyAt('01:00'); ``` Key methods: - `->withoutOverlapping()` -- prevent concurrent runs (uses cache lock) - `->onOneServer()` -- run only on one server in multi-server setup - `->evenInMaintenanceMode()` -- critical tasks that must run during `php artisan down` - `->runInBackground()` -- don't block scheduler for long tasks - `->emailOutputOnFailure('ops@example.com')` -- alert on failures - Requires system cron: `* * * * * cd /path && php artisan schedule:run >> /dev/null 2>&1` ## Custom Casts Value objects for model attributes -- encapsulate formatting, validation, and behavior. ```php class Money implements CastsAttributes { public function get(Model $model, string $key, mixed $value, array $attributes): Money { return new MoneyValue( amount: (int) $value, currency: $attributes['currency'] ?? 'USD' ); } public function set(Model $model, string $key, mixed $value, array $attributes): array { return ['price' => $value->amount, 'currency' => $value->currency]; } } // Usage on model protected function casts(): array { return ['price' => Money::class]; } ``` Built-in casts to prefer over manual accessors: - `AsEncryptedCollection::class` -- encrypt JSON columns at rest - `AsEnumCollection::class` -- array of enums stored as JSON - `AsStringable::class` -- fluent string operations on attribute - Enum casts: `'status' => OrderStatus::class` -- automatic PHP enum <-> DB value - Encrypted cast: `'api_token' => 'encrypted'` -- transparent encrypt/decrypt for sensitive fields ## Security Hardening ### Session - `SESSION_HTTP_ONLY=true`, `SESSION_SAME_SITE=strict` in `.env` - Regenerate session on login: `$request->session()->regenerate()` in auth controller - `SESSION_LIFETIME` -- set appropriate timeout (120 min default is often too long) ### Security Headers Middleware ```php class SecurityHeaders { public function handle($request, Closure $next) { $response = $next($request); $response->headers->set('X-Frame-Options', 'DENY'); $response->headers->set('X-Content-Type-Options', 'nosniff'); $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin'); $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); $response->headers->set('Content-Security-Policy', "default-src 'self'"); return $response; } } ``` Register in `bootstrap/app.php` middleware stack. ### Password Validation ```php Password::min(12)->letters()->mixedCase()->numbers()->symbols() ``` ### Signed URLs `URL::temporarySignedRoute('download', now()->addMinutes(30), ['file' => $id])` with `signed` middleware for tamper-proof temporary access. ### File Uploads - Validate MIME type: `'file' => ['required', 'mimes:pdf,docx', 'max:10240']` - Store outside public disk: `$request->file('doc')->store('documents', 's3')` - Never trust the original filename ### Dependency Audit `composer audit` -- check for known CVEs in dependencies. Run in CI. ### Logging PII Never log raw user data. Use `[REDACTED]` pattern for sensitive fields in log context. -
mocking-and-faking.md 10.5 KB
# Mocking and Faking Fake facades BEFORE the action that triggers them. Assert AFTER. ## Queue Faking ```php public function test_dispatches_job_on_post_creation(): void { Queue::fake(); $user = User::factory()->create(); $this->actingAs($user) ->postJson('/api/posts', ['title' => 'Test', 'body' => 'Content']); Queue::assertPushed(ProcessPost::class, fn ($job) => $job->post->title === 'Test'); Queue::assertPushed(ProcessPost::class, 1); // exact count } ``` ## Event Faking ```php public function test_fires_event_on_publish(): void { Event::fake([PostPublished::class]); $post = Post::factory()->create(); $post->publish(); Event::assertDispatched(PostPublished::class, fn ($e) => $e->post->id === $post->id); } ``` ## Notification Faking ```php public function test_sends_notification_to_post_author(): void { Notification::fake(); $post = Post::factory()->create(); $post->approve(); Notification::assertSentTo($post->user, PostApproved::class); } ``` ## Mail Faking ```php public function test_sends_welcome_email(): void { Mail::fake(); $this->postJson('/api/register', [ 'email' => 'new@example.com', 'password' => 'secret123', ]); Mail::assertSent(WelcomeMail::class, fn ($mail) => $mail->hasTo('new@example.com')); } ``` ## Storage Faking ```php public function test_uploads_avatar(): void { Storage::fake('public'); $user = User::factory()->create(); $file = UploadedFile::fake()->image('avatar.jpg'); $this->actingAs($user) ->postJson('/api/avatar', ['avatar' => $file]) ->assertOk(); Storage::disk('public')->assertExists("avatars/{$file->hashName()}"); } ``` ## HTTP Faking (External APIs) ```php public function test_fetches_data_from_external_api(): void { Http::fake([ 'api.example.com/*' => Http::response(['data' => ['id' => 1, 'name' => 'Test']], 200), ]); $service = app(ExternalApiService::class); $result = $service->fetchData(); $this->assertSame('Test', $result['name']); Http::assertSent(fn ($request) => $request->url() === 'https://api.example.com/data' && $request->hasHeader('Authorization') ); } ``` Use `Http::preventStrayRequests()` after faking to fail on any unfaked URL -- catches accidental real HTTP calls: ```php Http::fake(['api.example.com/*' => Http::response(['ok' => true])]); Http::preventStrayRequests(); // any other URL throws an exception ``` ## Bus Faking (Batches & Chains) ```php public function test_dispatches_batch(): void { Bus::fake(); $this->postJson('/api/import', ['file' => $file]); Bus::assertBatched(fn ($batch) => $batch->jobs->count() === 10); } public function test_dispatches_chain(): void { Bus::fake(); $this->postJson('/api/process'); Bus::assertChained([ValidateJob::class, ProcessJob::class, NotifyJob::class]); } ``` ## Action Testing with resolve() + swap() For invokable action classes, resolve from the container so DI works. Use `swap()` to replace dependencies with mocks: ```php public function test_processes_order_and_notifies(): void { $user = User::factory()->create(); $order = Order::factory()->for($user)->create(); // Mock dependency action and swap into container $calculateTotal = Mockery::mock(CalculateOrderTotalAction::class); $calculateTotal->shouldReceive('__invoke') ->once() ->with($order) ->andReturn(10000); $this->swap(CalculateOrderTotalAction::class, $calculateTotal); $notifyAction = Mockery::mock(NotifyOrderCreatedAction::class); $notifyAction->shouldReceive('__invoke')->once()->with($order); $this->swap(NotifyOrderCreatedAction::class, $notifyAction); // resolve() pulls from container with mocked dependencies injected $result = resolve(ProcessOrderAction::class)($order); $this->assertSame(10000, $result->total); } ``` Only mock what you own -- for external services (Stripe, etc.), create a service abstraction with a driver pattern and swap the driver config in tests, instead of mocking the SDK directly. ## Mockery (Service Mocking) For non-facade services where DI mocking is needed: ```php public function test_sends_notification_to_active_users(): void { $repository = Mockery::mock(UserRepository::class); $repository->shouldReceive('findActive') ->once() ->andReturn(User::factory()->count(2)->make()); $this->app->instance(UserRepository::class, $repository); $service = app(NotificationService::class); $result = $service->notifyActiveUsers('Important message'); $this->assertSame(2, $result->count()); } ``` Prefer Laravel facade fakes over Mockery when both options exist. Use Mockery for custom services and repository interfaces. ## Time Travel For testing time-dependent logic (expiration, scheduling, "created N days ago"): ```php public function test_marks_overdue_orders(): void { $order = Order::factory()->create(); $this->travel(31)->days(); $this->artisan('orders:mark-overdue')->assertSuccessful(); $this->assertDatabaseHas('orders', [ 'id' => $order->id, 'status' => 'overdue', ]); $this->travelBack(); // reset to real time } public function test_timestamps_match_frozen_time(): void { $this->freezeTime(); $user = User::factory()->create(); $this->assertSame(now()->toDateTimeString(), $user->created_at->toDateTimeString()); } public function test_subscription_expires(): void { $user = User::factory()->create(); $subscription = Subscription::factory()->create([ 'user_id' => $user->id, 'expires_at' => now()->addDays(30), ]); $this->travelTo(now()->addDays(31)); $this->assertTrue($subscription->fresh()->isExpired()); } ``` Available time units: `seconds()`, `minutes()`, `hours()`, `days()`, `weeks()`, `months()`, `years()`. Always call `$this->travelBack()` or use `$this->freezeTime()` to avoid leaking time state between tests. ## Http::assertSent() passes on ANY match `Http::assertSent()` passes when ANY recorded request satisfies the callback -- not every request, and not necessarily the one under test. The common shape, an early `return true` for requests the test does not care about, makes every unrelated request satisfy the whole assertion on its own, so the clause that matters never has to hold. Return `false` for out-of-scope requests, then assert on the single request under test; `assertNotSent` inverts the same way. Prove the assertion is live by mutating the source to violate what it claims to guard and re-running that test alone -- a still-green run means the assertion was never doing anything. Related: after making a straying test hermetic, ask what the live response was doing for the suite; a stray call can be load-bearing coverage, and removing it is a coverage regression disguised as a hygiene fix. ## Mail::fake() does not render the view `Mail::fake()` records mailables without building them, so `assertSent`/`assertQueued` never compiles the Blade view. A renamed view variable, a dropped `Content::with()` key, or a `Storage::disk()->url()` on an unconfigured disk all pass CI and throw on the first real send. Force a render: assert on `(new TheMailable(...))->render()`, or call `$mail->assertSeeInHtml(...)` inside the assertion closure, which renders as a side effect. When a mailable or its template changes, confirm at least one test forces a render -- "there is a test for this email" is not "the template compiles". ## Mail::fake() vs Notification::fake(): different dispatch surfaces `Mail::fake()` swaps the transport; `Notification::fake()` swaps the whole dispatcher. Under `Mail::fake()` the notification pipeline still runs -- channels resolve, `send()` executes, and `NotificationSending` / `NotificationSent` fire, so listeners on those events run. Under `Notification::fake()` nothing dispatches and neither event fires. Switching a test from one to the other to use `assertSentTo()` silently stops every `NotificationSent` listener, so an assertion on that listener's side effect either fails or passes vacuously. When a diff moves a side effect onto such a listener, audit every test asserting it: assert what the caller itself sets under the fake, and cover the listener separately by constructing `new NotificationSent(...)` and calling `handle()`. ## throttle middleware and cache.limiter `throttle` middleware reads `config('cache.limiter')`, not `cache.default`, so `Cache::flush()` does not reset rate-limit counters. With `cache.limiter` hardcoded to a real store, counters go to Redis even when `phpunit.xml` sets `CACHE_STORE=array`, and they accumulate across methods, runs and processes keyed by a constant IP or token -- a later test 429s before reaching its own limit, so the file passes alone and flakes in the suite with "expected 422, received 429". Clear the limiter's own store in `setUp()`: `Cache::store(is_string($s = config('cache.limiter')) ? $s : null)->clear()`. Use `clear()`, not `flush()` (not declared on the `Repository` contract, so PHPStan rejects it), and read the loop bound from the same config the limiter uses instead of a hardcoded literal. ## Mockery cannot mock a readonly class Mockery achieves polymorphism by generating a subclass at runtime. PHP 8.2+ rejects "non-readonly class extends readonly class" at class-load time, so `Mockery::mock(SomeReadonlyDto::class)` dies inside the generated code with `PHP Fatal error: Non-readonly class Mockery_N_SomeReadonlyDto cannot extend readonly class SomeReadonlyDto`. It is a fatal, not a `Mockery\Exception` -- `try`/`catch` does not reach it, the process exits non-zero, and every remaining test in the file is skipped. A `final` class is the friendlier case: Mockery throws a catchable exception naming the problem. Two greps when a test diff adds `Mockery::mock(SomeClass::class)`: is the target declared `readonly class` / `final readonly class`, and is it a DTO or value object (where modern PHP codebases apply `readonly` by default)? Either fires and the file cannot run. Fix by constructing the real object -- DTOs are free and give a stronger test -- or by extracting an interface the readonly class implements and mocking that. `shouldIgnoreMissing()` does not help: the fatal happens during class generation, before any expectation is set. Same shape wherever a mocking library subclasses to intercept: PHP 8.4 asymmetric visibility (`public private(set)`), Java `final` with plain Mockito, C# `sealed` with Moq. Related: `assertSame($carbon, $model->some_date)` always fails, because Eloquent's date cast hydrates a fresh `Carbon` on every access -- compare values (`equalTo()`, `toIso8601String()`), never identity. -
persistence-and-jobs.md 8.8 KB
# Persistence and job patterns ## Migrations - Anonymous class migrations; `snake_case` plural table names matching model convention - Foreign keys: `$table->foreignId('user_id')->constrained()->cascadeOnDelete()`. Always index foreign keys and frequently filtered columns. - Down method: rollback logic or `Schema::dropIfExists()` for new tables - Separate schema and data migrations -- backfills in their own migration file, not mixed with DDL. One deliberate exception: when a single transaction is what closes a rolling-deploy null window, splitting reopens it; the lock-duration trade-off and table-size disposition live in the `ia-postgresql` skill, Migration Safety - Renames/removals use expand-contract: add new column → backfill → switch reads → drop old (full pattern in `ia-postgresql` skill) - Never edit a migration that has run in a shared environment -- write a new one - **Set `public $withinTransaction = false;` for per-row commit/lock-release (resumable backfills) or statements Postgres rejects inside a transaction (`CREATE INDEX CONCURRENTLY`, `ALTER TYPE ... ADD VALUE`).** Otherwise inner `DB::transaction()` loops become savepoints, not independent commits ([pitfalls-deep.md](./pitfalls-deep.md)); no-op on MySQL. - **The `migrations` row is inserted AFTER `up()` returns and outside its transaction**, so a process killed in that window leaves a committed-but-unrecorded migration and every later container re-runs `up()` into `relation already exists` -- a crash loop that bricks all further deploys. Fix: an early-return `Schema::hasTable()` guard at the top of `up()`. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). - `migrate:fresh` resets only the SQL connection -- external stores (DynamoDB, S3, Redis) persist across it, so external-store data migrations re-run on already-migrated data and must be idempotent on a second run. ## Eloquent - `Model::preventLazyLoading(!app()->isProduction())` -- catch N+1 during development - Select only needed columns: `Post::with(['user:id,name'])->select(['id', 'title', 'user_id'])` - Bulk operations at database level: `Post::where('status', 'draft')->update([...])` -- never load into memory to update. `increment()`/`decrement()` for counters. - Composite indexes for common query combinations - `chunk(1000)` for large datasets, lazy collections for memory-constrained processing - Query scopes (`scopeActive`, `scopeRecent`) for reusable constraints - `withCount('comments')` / `withExists('approvals')` -- never load relations just to count - `->when($filter, fn($q) => $q->where(...))` for conditional query building - `DB::transaction(fn() => ...)` -- automatic rollback on exception - `Model::upsert($rows, ['unique_key'], ['update_cols'])` for bulk insert-or-update - **`updateOrCreate($match, $values)` reassigns the primary key on the update branch when `$values` carries a fillable identity column.** On the second call Eloquent runs `fill($values)->save()` and the WHERE uses the ORIGINAL key, so the row's id churns on every redelivery -- the opposite of the idempotency intended. Fix: keep `id` out of `$values`. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - `Prunable` / `MassPrunable` with `prunable()` query for automatic stale record cleanup - `$guarded = []` is a mass assignment vulnerability -- always explicit `$fillable` - **A custom `CastsAttributes` whose `get()` returns an object is cached and merged BACK through `set()` on the next `save()`,** so a tolerant `tryFrom($v) ?? default()` read idiom overwrites the original stored value on any unrelated save. Fix: `public bool $withoutObjectCaching = true;` on the cast; anything preserving the stored value must read `getRawOriginal()`. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **`Builder::value()` and `pluck()` return the CAST attribute; `DB::table(...)->value()` returns the raw column.** A guard like `is_string($v) ? Enum::tryFrom($v) : null` silently returns `null` forever once a `$casts` entry exists -- no error, clean PHPStan, green tests. Grep every `->value()`/`->pluck()` when a diff adds a cast. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **With `Relation::enforceMorphMap()`, a model missing from the map throws `ClassMorphViolationException` -- from the audit layer, which is usually config-gated off under test**, so a new unmapped model passes the whole suite and 500s on the first audited write. The read side is the mirror: every morph write stores the ALIAS, so a hardcoded `where('<rel>_type', 'App\\Models\\Foo')` matches zero rows -- use `(new Foo)->getMorphClass()`. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **`latest()` / `orderByDesc()` on a relation that already declares an order APPENDS to it.** `hasMany(Version::class)->orderBy('created_at')` plus `->latest('created_at')->first()` compiles to `ORDER BY created_at asc, created_at desc` and returns the oldest row; a single-row fixture masks it. Fix: `reorder('created_at', 'desc')`, or a dedicated `latestVersion(): HasOne`. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). ## Queues & Jobs - Batching: `Bus::batch([...])->then()->catch()->finally()->dispatch()`; chaining: `Bus::chain([new Step1, new Step2])->dispatch()` - Rate limiting: `Redis::throttle('api')->allow(10)->every(60)->then(fn() => ...)` - Central routing (Laravel 13): `Queue::route(ProcessPodcast::class, connection: 'redis', queue: 'podcasts')` in a service provider's `boot()` replaces scattered `$connection`/`$queue` properties; the first argument may also be an interface, trait, or parent class, and an array form routes many classes at once. The route is a default only: a per-job `$connection`/`$queue` value (property, or set through `onQueue()`/`onConnection()`) is read first and wins. `Queue::forward('reports', 'reports.fifo', 'sqs')` re-targets an existing queue name without touching jobs or dispatch sites. - **`ShouldBeUnique` prevents duplicate processing -- it is a de-duplication hint, not an at-least-once guarantee.** When the lock is already held, dispatch is silently discarded: no job, no exception, no log line. Fix: check the lock before dispatching where the skip is user-visible; confirm `UniqueJobSkipped` exists in the installed version before relying on it. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **`WithoutOverlapping` folds the job's class name into the lock key, so two job classes sharing a key do NOT serialize against each other** unless both call `->shared()`. A synchronous in-request writer takes no queue middleware, so no lock setting can serialize against it either. Fix: assert real contention (`getLockKey()` across both instances), not the middleware's public property. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **`WithoutOverlapping()->dontRelease()` with no `->expireAfter()` strands the lock forever on a hard kill (SIGKILL, OOM, node loss).** Every subsequent job for that key is then silently discarded, including from a reconciliation command. Fix: set a TTL safely longer than the job's worst-case runtime and keep `dontRelease()` -- the two knobs are orthogonal. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **`Context` cannot bleed between queued jobs -- it is flushed and rehydrated from each job's own dispatch payload before `handle()` runs.** The genuine bleed surface is Octane/Swoole/RoadRunner on the HTTP path, where the repository is an app singleton across requests. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - **Adding a constructor parameter to a `ShouldQueue` job breaks every payload already queued, and a promoted default does not save it** -- `unserialize()` skips the constructor and restores only declaration-level defaults, which a promoted (or `readonly`) property has none of. Fix: a plain property with a declaration-level default, assigned in the constructor body, set to what an already-enqueued payload MEANT. Full mechanism in [pitfalls-deep.md](./pitfalls-deep.md). - Always handle failures -- implement `failed()` on jobs ## Production Resilience - **Fail-fast config validation** in a service provider's `boot()`: missing API keys, invalid DSNs, misconfigured queues crash on startup, not on the first request that hits the code path. - **Health endpoints**: `/health` (shallow, 200 if the process responds) and `/ready` (deep -- checks DB, Redis, critical services). - **A `set -e` container entrypoint is a fail-fast contract -- only put steps there whose failure should genuinely block traffic.** Migrations and `config:cache` qualify; docs generation and optional caches do not, because their non-zero exit aborts the boot before php-fpm and the workers start. Full mechanism in [common-pitfalls.md](./common-pitfalls.md). ## Production Performance OPcache + JIT + preloading configuration and Laravel deploy caches (`config:cache`, `route:cache`, etc.): [production-performance.md](./production-performance.md) -
pitfalls-deep.md 23.6 KB
# Laravel Pitfalls — Deep Reference Extended mechanics and alternative patterns for the Common Pitfalls section of SKILL.md. ## `DB::afterCommit`: closing the post-commit-failure half `DB::afterCommit($closure)` prevents external work (S3, search index, third-party webhook) from running when the transaction rolls back. It does NOT retry the external op when it fails after commit — the closure runs once, exceptions bubble out of the response cycle, the operation drops, and the DB row now advertises a state the external system doesn't reflect. Closing patterns: - **(a) Queued job with retries — the general-purpose default.** Dispatch a queued job with `tries` + exponential backoff + a `failed(Throwable $e)` handler that reverts the DB precondition the job was supposed to make true. Queue retry semantics already model the transient/permanent split. - **(b) External-op-first, then DB.** Perform the external mutation before the DB write, so a DB failure leaves only harmless external residue. Only valid when the op is idempotent on the destination key: `Storage::copy` retries cleanly; `Storage::move` fails on the second attempt because the source is gone. - **(c) Reconciler command.** A scheduled command walks rows with stuck "in-flight" flags and re-drives or reverts them. Reach for this when jobs can be lost entirely (queue driver failure) or the writes originate from multiple code paths. ## Observer-desync mechanics When an observer fires mid-flow (e.g. `Document::deleted` → `$verifiable->update([...])`) and mutates a model the caller is also mutating, the two instances share no state — Eloquent dirty-tracking compares in-memory current vs in-memory original, never the DB. The caller's later `save()` only writes columns it changed, so: - a column the observer cleared stays cleared on disk, and - a column the caller set back to its in-memory original is seen as not-dirty and never re-written. `DB::transaction` doesn't help — this is in-memory state, not isolation. Fixes: `$model->refresh()` in the caller after the triggering event and before its later `save()`, or run the triggering write under `Model::withoutEvents(...)` when the caller owns that column's semantics for the flow. ## jsonb read-modify-write race In `chunkById + json_decode + mutate + json_encode + update`, the window between the SELECT populating `$row->metadata` and the per-row UPDATE is milliseconds — any user save landing in that window is silently overwritten by the migration's stale snapshot. In-place `DB::raw("jsonb_set(metadata, '{path}', ...)")` avoids the read entirely for shallow edits; `lockForUpdate()` inside the chunk serializes with concurrent writers when arbitrary PHP logic is needed. The default decode/encode pattern is only safe during a maintenance window with writes blocked. ## `$withinTransaction` savepoint mechanics (Postgres) Migrations default to `public $withinTransaction = true` — on Postgres/SQLite all of `up()` runs in one outer transaction. A per-row `DB::transaction()` loop inside a data backfill therefore creates nested savepoints, not independent commits: each inner "commit" merely releases a savepoint, nothing is durable until `up()` returns, and row locks accumulate for the whole run. One mid-loop failure rolls back every prior row. MySQL auto-commits DDL, so the flag is a no-op there. ## Eloquent pitfalls ### CastsAttributes get() cache merges back through save() A custom `CastsAttributes` whose `get()` returns an object is cached and merged BACK through `set()` on the next `save()`. `getClassCastableAttributeValue()` parks any object return in `$classCastCache` (a `BackedEnum` is an object, so enums qualify), and `Model::save()` opens with `mergeAttributesFromCachedCasts()`. So the tolerant `tryFrom($v) ?? default()` read idiom -- written precisely so an unrecognised stored value degrades during a rolling deploy instead of throwing -- destroys that value: read the attribute, save the model for any unrelated reason, and the unknown string is rewritten as the default. It degrades on read and corrupts on write, in exactly the scenario it exists for. Fix: `public bool $withoutObjectCaching = true;` on the cast. Anything whose job is preserving the stored value -- an audit recorder, a pre-delete snapshot -- must read `getRawOriginal()`, or it records the normalised fallback and the real value is unrecoverable. ### Builder::value()/pluck() cast vs DB::table raw column `Builder::value()` and `pluck()` return the CAST attribute; `DB::table(...)->value()` returns the raw column. `value()` is `first([$column])` followed by `$result->{$column}`, so the value goes through `getAttribute()` and the cast applies. A guard like `is_string($v) ? Enum::tryFrom($v) : null` therefore returns `null` forever -- no error, no exception, PHPStan clean (`value()` is typed `mixed`, so the narrowing is legal), and green tests, because whatever the guard was meant to reject is now accepted. Accept both shapes: `$v instanceof Enum ? $v : (is_string($v) ? Enum::tryFrom($v) : null)`. The mechanism also fires in reverse -- adding a `$casts` entry for an existing column silently disables every such guard reading it, with no change at any call site for a diff-scoped review to see. When a diff adds a cast, grep every `->value('<column>')` / `->pluck('<column>')` whose result meets `is_string`, `is_int`, a `match`, or a bare `===` against a literal. ### enforceMorphMap() throws only from audit-gated code paths With `Relation::enforceMorphMap()`, a model missing from the map throws `ClassMorphViolationException` from `getMorphClass()` -- and almost nothing calls `getMorphClass()` on an ordinary `create()` except the audit layer, which is usually config-gated off under test. So a new model with no map entry passes the entire suite, including tests that create it, and 500s on the first write in an environment where auditing is on. The throw fires inside whatever transaction the write is in, so one unmapped child model rolls back the parent record, its links and any status transition -- the whole request, not just the audit. Add the map entry in the same commit as the model; with `enforceMorphMap` it is part of the class working at all, and overriding an audit-label method is a separate call site that does not substitute. A green suite is not evidence here: check whether the config flag gating the consumer is false under test. The read side is the mirror and it fails silently instead of loudly. `getMorphClass()` returns the map ALIAS whenever a morph map is registered, so every Eloquent morph write -- `morphTo()->associate()`, a factory's `for<Morph>()`, a resource's own save -- persists the alias, and no row carries the FQCN. A migration, seeder or raw statement written as `DB::table('documents')->where('documentable_type', 'App\\Models\\ProviderDocument')->update([...])` therefore matches zero rows: no error, no exception, a clean "0 rows affected" that reads as "nothing needed changing". Resolve the value instead of typing it -- `(new ProviderDocument)->getMorphClass()` or the map's enum case (`DocumentableMorphType::ProviderDocument->value`). Two greps make it findable: a hardcoded `App\\Models\\` literal inside a `where('*_type', ...)` or `update(['*_type' => ...])` clause, and whether a prior migration already normalised legacy FQCN rows to aliases. ### updateOrCreate() reassigns the primary key when values carries the id `updateOrCreate($match, $values)` is `firstOrCreate($match, $values)` plus, when the row already existed, `$instance->fill($values)->save()`. `fill()` honours `$fillable`, and a base model that lists `'id'` so callers can supply a pre-generated `Str::uuid7()` on create makes the identity column fillable on the update branch too. `save()` then issues `UPDATE ... SET id = <new>, ... WHERE id = <original>`, because `getKeyForSaveQuery()` returns `$this->original[$keyName] ?? $this->getKey()`. So `'id' => (string) Str::uuid7()` in `$values` -- written to make redelivery idempotent -- reassigns the primary key on every redelivery, which is the exact opposite. Either a child FK without `ON UPDATE CASCADE` raises a foreign-key violation and 500s, or the id churns silently and everything holding the old value is orphaned. It survives review because the intent is idempotency, the match key is correct, and an `id` in the values array reads as a create-time concern. The defect fires only on the second delivery, so a happy-path test passes. Fix: never put the identity column in `$values` -- let `HasUuids` generate it on create, where it belongs. Same check for `firstOrCreate` and `updateOrInsert`: when an identity or unique column appears in the second argument, read the model's `$fillable`. Pin it with a redelivery test that calls the action twice with the same match key and asserts the row's key is unchanged, not with a single happy-path call. ### latest()/orderByDesc() on an ordered relation appends `latest($column)` and `orderByDesc($column)` are `orderBy()` calls, and `orderBy()` pushes onto the builder's `$orders` array rather than replacing it. A relation defined as `hasMany(Version::class)->orderBy('created_at')` therefore compiles `->latest('created_at')->first()` to `ORDER BY created_at asc, created_at desc` -- the first key decides, so the call reads as "newest" and returns the OLDEST row. `reorder('created_at', 'desc')` clears the accumulated orders before adding its own and is the direct fix; a dedicated `latestVersion(): HasOne` is better where "the newest one" is a first-class concept. A fixture with one child per parent cannot fail either way, so the defect survives both review and the suite. On review, open the relation definition for every `->latest()` / `->oldest()` / `->orderBy*()` chained onto a relation before `first()`. ### save() drops an assignment equal to the stale original `save()` writes only the dirty attributes, and dirtiness compares the in-memory value against `$original` -- the snapshot taken when the model was loaded, not the current row. Assigning `true` to a model that was loaded as `true` produces an empty dirty set, so the column is left out of the UPDATE entirely and there is no `WHERE` clause that could detect the row moved underneath. Adding row locks to the *other* writers makes it more deterministic rather than less: the unlocked writer computes its dirty set before any lock exists, blocks, then resumes exactly where its column has already been dropped from the statement. Locking some writers of a row and not others is a scheduler for the bug. Fix: `refresh()` or `lockForUpdate()` before the compare, or write a conditional UPDATE carrying the expected prior value in its `WHERE`. ## Queue pitfalls ### ShouldBeUnique silently discards, does not guarantee `ShouldBeUnique` interface to prevent duplicate processing -- it is a de-duplication hint, not an at-least-once guarantee. When the lock is already held the dispatch is **silently discarded**: no job queued, no exception, no log line, and `dispatch()` returns normally. Where the skip is user-visible (a re-clicked "regenerate report" that produces nothing), check the lock before dispatching and surface the state. A `Illuminate\Queue\Events\UniqueJobSkipped` event exists on the `13.x` branch but had not landed in a tagged release as of 13.24 -- confirm it is in the installed version before listening for it. ### WithoutOverlapping lock key includes the job class `WithoutOverlapping` folds the job's class name into the lock key, so two job classes sharing a key do NOT serialize against each other. `getLockKey()` returns `prefix.get_class($job).':'.$key` unless `->shared()` was called, and `->shared()` is per-middleware-instance -- adding it to only the new job is a no-op, and the remedy therefore has to touch the other job's file. A test asserting `$middleware[0]->key` passes either way, since the public property is equal on both jobs and unaffected by `->shared()`; assert `getLockKey($job)` across both instances, or assert real contention. Changing an already-deployed job's key also opens a rolling-deploy window where old and new workers hold different locks. Before trusting the guarantee at all, check whether the other writer is a job: a synchronous in-request writer takes no queue middleware, so no lock setting can serialize against it. ### dontRelease() without expireAfter strands the lock `WithoutOverlapping()->dontRelease()` with no `->expireAfter()` strands the lock on a hard kill. `expiresAfter` defaults to `0`, which builds a cache lock with no TTL, and the lock is released only in the middleware's `finally` -- SIGKILL, the OOM killer, or a node loss skips it. From then on every job for that key hits the lock-held branch and, because `dontRelease()` set `releaseAfter = null`, falls through both branches and is silently discarded: not run, not retried, not failed, no error surfaced. Any reconciliation command that re-dispatches is discarded too, so the backstop silently no-ops. The knobs are orthogonal -- `dontRelease` = no pile-up, `expireAfter` = self-heal -- and defending one does not address the other. Set a TTL safely longer than the job's worst-case runtime and keep `dontRelease()`. ### Context does not bleed between queued jobs `Context` cannot bleed between queued jobs -- it is flushed and rehydrated from each job's own dispatch payload before `handle()` runs. `ContextServiceProvider` dehydrates the dispatcher's context into the payload and calls `Context::hydrate()` on `JobProcessing`; `Repository::hydrate()` runs `flush()` first, every time, including when the payload is `null`. So "this job sets Context and never clears it, the next job inherits it" is not a bug. The genuine bleed surface is Octane/Swoole/RoadRunner on the HTTP path, where the repository is an app singleton and a middleware that sets Context for only some requests leaves it set for a later request that does not overwrite it -- a non-issue under PHP-FPM. Within one job Context is shared for the duration, so a handler serving multiple audiences must re-set it per audience. ### A new constructor parameter breaks payloads already queued A queued job is serialized on dispatch, so a payload written by the old release is revived by the new one. `unserialize()` never runs the constructor: it instantiates from the class entry, applies the *declaration-level* defaults, then overwrites with whatever the payload carries. A promoted constructor property has no declaration-level default -- the default lives on the parameter -- so the new typed property comes back uninitialized and `handle()` throws `Typed property ... must not be accessed before initialization`. `failed_jobs` stores the same stale payload, so retrying the failed job re-throws for the same reason. `readonly` cannot be the fix either, since a readonly property may not declare a default. Use a plain `private`/`protected` property with a declaration-level default and assign it in the constructor body. Only a *new parameter* is exposed: changing a property's visibility or renaming a method is harmless, and rolling the deploy back is clean. Then treat the default as semantics, not syntax -- on a job whose new parameter gates behaviour, every in-flight payload runs the default branch, so set it to what an already-enqueued payload actually meant. ## Concurrency pitfalls ### `Concurrency::run()` leaks hidden Context into the child process environment The process driver passes `'__LARAVEL_CONTEXT' => json_encode(Context::dehydrate())` as an env var to every pooled child process. `dehydrate()` does keep hidden values under a separate `hidden` key (`['data' => ..., 'hidden' => ...]`), but `ProcessDriver` JSON-encodes the whole array into one env var with no filtering, so hidden values travel with the visible ones regardless of the split. Any same-uid process can read that value from `/proc/<pid>/environ` for the child's lifetime, and it shows up in `ps e` too, so a credential stashed via `Context::addHidden()` leaks well beyond the job that set it. Applies from the 13.x context-propagation fix onward; keep credentials out of Context for concurrency work and resolve them inside the closure from config or a secret manager, or use the synchronous driver where the threat model requires it. ## Validation pitfalls ### validated() drops unruled nested array keys `validated()` does not filter the request payload, it rebuilds it from the rule keys. Since Laravel 9 the validator excludes unvalidated array keys by default, so a parent key with sub-key rules is skipped and only the explicitly ruled sub-keys are written into the result. A FormRequest ruling `mapping.first_name` and not `mapping.middle_name` therefore returns a `mapping` array with `middle_name` absent -- no error, no message, and every consumer downstream of `validated()` sees a truncated payload. Unit tests that hand-build the array and call the service directly never cross the FormRequest and cannot see it. `Validator::includeUnvalidatedArrayKeys()` restores the pre-9 behaviour globally, which is the wrong lever for one endpoint: rule every sub-key the consumer reads instead. Whenever a diff adds a field to a nested payload, grep `rules()` for the dotted key and add a feature test that posts the real request body and asserts the stored value. ### Blank-ish strings skip every non-implicit rule A string that trims to empty skips every non-implicit validation rule. `Validator::presentOrRuleIsImplicit` short-circuits on `is_string($value) && trim($value) === ''`, so `" "`, `"\t"`, `"\n"`, `""` bypass `array`, `boolean`, `string`, `max`, `enum` and every custom `ValidationRule` -- only the implicit set (`required*`, `present*`, `missing*`, `filled`, `accepted*`, `declined*`) still fires. This is a property of the VALUE, not of `nullable`. So an `'items.*' => 'array'` guard stops `{"section": "Bob"}` with a 422 and does not stop `{"section": " "}`, which slips past `empty()` too and reaches a handler type-hinted `array` as a `TypeError`. Fix: normalise blank-ish strings to `null` in `prepareForValidation()`, or `is_array()` at the consumer -- adding another rule does nothing, it is skipped for the same reason. Never conclude "the array rule protects this" from a non-blank-scalar 422. ### boolean rule validates but never normalises The `boolean` validation rule validates but never normalises. `1`, `0`, `"1"`, `"0"` all pass, and `validated()` / `input()` return them unchanged, so `$validated['flag'] === true` is false for input the rule accepted -- and a strict compare against a stored default then persists a spurious override that never clears. Test payloads written with real JSON `true`/`false` decode to PHP bools and never expose it. Fix: cast at the read (`(bool) $validated['flag']`) or use `$request->boolean('flag')`, which does cast via `FILTER_VALIDATE_BOOL`. `boolean:strict` is not a built-in rule. ### distinct scope at two wildcard levels `distinct` scopes to the leading explicit path, so at two wildcard levels it compares the whole payload. `'questions.*.options.*.option_key' => ['distinct']` reads as "unique within each question" and is not: `getLeadingExplicitAttributePath()` returns everything before the first asterisk (`questions`), and that subtree is flattened with `Arr::dot()`, so two different questions carrying the same option key are both rejected. `ignore_case` and `strict` change the comparison mode, never the scope; there is no per-parent option. The idiom is correct at one wildcard and silently changes meaning at two. Fix: drop `distinct` and de-dupe per parent in an `after()` closure, flagging every member of a colliding group rather than only the later one, so existing `assertJsonValidationErrors` paths still resolve. ### Exists/Unique self-skip after any message `Exists` and `Unique` self-skip once the attribute has any message; the unprotected value is the one baked into the rule's SCOPE. `hasNotFailedPreviousRuleIfPresenceRule` gates exactly those two rules on `! $this->messages->has($attribute)`, so `['uuid', Rule::exists(...)]` cannot send a malformed UUID to the database, and adding `bail` changes nothing. The real 500 comes from the other side: `Rule::exists('docs', 'id')->where('owner_id', (string) $user->owner?->id)` casts `null` to `''` and compares it against a `uuid` column (Postgres `22P02`). Passing the nullable value through unchanged routes to `whereNull()` and yields a clean 422. Triage discriminator: is the suspect value the attribute being validated, or an argument to the rule? Only the second is exposed. ### Carbon::parse() year-only string pitfall `Carbon::parse('2020')` is today at 20:20, not year 2020 -- a bare 4-digit string parses as `HHMM` time-of-day, breaking `before_or_equal:today` / `after` / `before` on year-only input. Fix: `Carbon::createFromFormat('Y', $year)->startOfYear()` + partial-date-aware rules; when migrating a field's validator type, audit its sibling validators for the same incompatibility. ### Auth guard infinite recursion via report() A custom auth guard whose failure path calls `report()` infinitely recurses, and it is an unauthenticated DoS. Laravel's exception-report context calls `Auth::id()`, which re-enters the same guard mid-resolution, which fails again and reports again: `user() -> catch (Throwable) -> report() -> Handler::context() -> Auth::id() -> user()`. Any middleware calling `$request->user()` on such a route turns a malformed `Authorization: Bearer <garbage>` into an OOM'd worker. It presents as an HTTP-client or JWT-library bug because the fatal crash site moves between runs -- memory is already exhausted, so whichever allocation comes next dies; faking the outbound call just relocates the OOM downstream of the real consumer. Fix in the guard: a `resolving` flag returning `null` on re-entry, plus memoising the null resolution so repeated `user()` calls do not re-run the whole fetch-and-decode. Any resolver whose failure path calls `report()`, logs with auth context, or fires an event touching `Auth::user()` is a candidate. ### Backed enum serialization by case name A backed enum serialises as `E:<len>:"<FQCN>:<CaseName>"` -- the case NAME, never the backing value -- so reordering cases is serialization-safe and renaming or removing one is not. Unserializing a removed case emits a warning and returns `false`; it does NOT raise `Enum::from()`'s `ValueError: X is not a valid backing value`, which is the message people write from memory into comments and MR descriptions. Under Laravel's `HandleExceptions` that warning becomes an `ErrorException`, so a `catch (Throwable)` decoder absorbs it and the entry degrades to a permanent MISS -- one rebuild plus one `report()` per read for the rest of its TTL. The other two shapes are worse because nothing catches them: a newly added promoted property unserializes fine and fires an `Error` at the consumer's first read, and a renamed or moved class warns not at all and serves `__PHP_Incomplete_Class` as a clean HIT. Version the cache key whenever a stored object graph's shape changes. ## Tooling pitfalls ### composer.lock conflicts confined to the content-hash line A `composer.lock` conflict whose only hunk is `content-hash` is not a conflict over packages. The `packages` and `packages-dev` arrays merged cleanly; the two hashes differ because each side computed one from its own `composer.json`, and both are stale against the merged file. Hand-picking either side records a hash that matches neither, and `composer install` then warns the lock is out of date while still installing from it. Verify the union first by grepping `"name"` for every package added, removed, or swapped on either branch, then run `composer update --lock --no-install` -- it recomputes the hash without touching resolution and prints `Nothing to modify in lock file` when the merged arrays were already correct. When both branches edited the same package entries, discard the merge, take the target branch's lock, and re-add the branch's packages with `composer require`. -
production-performance.md 1.1 KB
# Production Performance — OPcache, JIT, Preloading, Laravel caches Load this reference when deploying a PHP/Laravel application to production or optimizing runtime performance. Not relevant for dev or testing. - **OPcache**: enable in production (`opcache.enable=1`), set `opcache.memory_consumption=256`, `opcache.max_accelerated_files=20000`. Validate with `opcache_get_status()`. - **JIT**: enable with `opcache.jit_buffer_size=100M`, `opcache.jit=1255` (tracing). Biggest gains on CPU-bound code (math, loops), minimal impact on I/O-bound Laravel requests. - **Preloading**: `opcache.preload=preload.php` — preload framework classes and hot app classes. Use `composer dumpautoload --classmap-authoritative` in production. - **Laravel-specific**: `php artisan config:cache && php artisan route:cache && php artisan view:cache && php artisan event:cache` — run on every deploy. `composer install --optimize-autoloader --no-dev` for production. `config:cache` is what makes the no-`env()`-outside-`config/` rule load-bearing: after it runs, any `env()` call elsewhere returns `null`. -
testing-and-pitfalls.md 9.8 KB
# Testing and pitfall checklist ## Testing (PHPUnit) ### Diagnosing failing tests 1. Run the single failing test in isolation (`phpunit --filter test_name`) before reading app code. 2. Passes solo but fails in the suite → suspect shared state: container singletons, statics, `Carbon::setTestNow()` residue, DB state leaking between tests. A `private static` memo is the sharp case -- process-scoped, so no rollback reaches it; reset it through reflection rather than deleting it ([testing.md](./testing.md)). 3. Diff expected vs actual output before hypothesizing a cause. 4. Decide explicitly: test-bug or code-bug. Name which before editing either. 5. Never weaken an assertion to make it pass. `MissingAttributeException` after `create()` usually means strict mode (`Model::shouldBeStrict()`) plus a factory omitting a column with a DB default -- Eloquent never re-reads that default. The silent case (a freshly created instance rendering JSON `null` for a required field) is worse than the thrown one. Fix on the model (`protected $attributes = [...]`), not the factory. Full mechanism in [testing.md](./testing.md). ### Patterns - **Feature tests** (`tests/Feature/`): HTTP through the full stack (`getJson()`, `postJson()`) -- default for anything touching routes, controllers, or models. **Unit tests** (`tests/Unit/`): isolated services, actions, value objects. - `RefreshDatabase` for full migration reset per test; `DatabaseTransactions` for transaction-wrap (faster, no migration testing); `DatabaseMigrations` to run and rollback per test - Model factories for all test data -- never raw `DB::table()` inserts - **Factories build the model inside `Model::unguarded()`, so a fixture can set a column `$fillable` rejects** -- investigate mismatches against actual production writers, including direct assignment, query-builder writes, observers, and database defaults. Absence from `$fillable` alone does not prove a fixture unreachable. Full mechanism in [factories.md](./factories.md). - One behavior per test. Name with `test_` prefix: `test_user_can_update_own_profile` - Assert both response status AND side effects (DB state, jobs, notifications): `assertDatabaseHas` / `assertDatabaseMissing` - `actingAs($user)` for auth, `Sanctum::actingAs($user, ['ability'])` for API auth - Fake facades BEFORE the action: `Queue::fake()` → act → `Queue::assertPushed(...)`; same for `Http::fake(['host/*' => Http::response(...)])` → `Http::assertSent(...)` - `Gate::forUser($user)->allows('update', $post)` for authorization assertions - **`assertJsonValidationErrors(['field'])` passes on ANY error for that field**, so an earlier rule in the chain -- or a service-layer `ValidationException::withMessages()` on the same key -- satisfies a test named for the rule under test. Fix: assert the message form (`['field' => 'must not be greater than']`) and delete the rule to prove which guard answered. Full mechanism in [feature-testing.md](./feature-testing.md). - **Mockery cannot mock a `readonly` class** -- it generates a non-readonly subclass, which PHP 8.2+ rejects at class-load time, so the file dies with a FATAL (not a catchable exception) before any assertion runs. Fix: construct the real object (DTOs are free) or mock an interface it implements. Full mechanism in [mocking-and-faking.md](./mocking-and-faking.md). - **`Http::assertSent()` passes when ANY recorded request satisfies the callback -- not every request, and not necessarily the one under test.** An early `return true` for out-of-scope requests makes every unrelated request satisfy the whole assertion on its own. Fix: return `false` for out-of-scope requests, then assert on the single request under test. Full mechanism in [mocking-and-faking.md](./mocking-and-faking.md). - **`Mail::fake()` records mailables without building them, so `assertSent`/`assertQueued` never compiles the Blade view** -- a broken template still passes CI. Fix: force a render (`(new TheMailable(...))->render()` or `assertSeeInHtml()`) in at least one test per mailable. Full mechanism in [mocking-and-faking.md](./mocking-and-faking.md). - **`Mail::fake()` swaps only the transport (the notification pipeline still runs); `Notification::fake()` swaps the whole dispatcher and neither `NotificationSending` nor `NotificationSent` fires.** Switching fakes to reach `assertSentTo()` silently kills listeners on those events. Fix: audit and cover those listeners separately. Full mechanism in [mocking-and-faking.md](./mocking-and-faking.md). - **`throttle` middleware reads `config('cache.limiter')`, not `cache.default`, so `Cache::flush()` does not reset rate-limit counters** and tests can flake in the suite while passing alone. Fix: clear the limiter's own store in `setUp()` (`Cache::store(config('cache.limiter'))->clear()`). Full mechanism in [mocking-and-faking.md](./mocking-and-faking.md). - **`force="true"` on a `phpunit.xml` `<env>` entry pins `getenv()`/`$_ENV`, not Laravel's `env()`** -- both surfaces need pinning because `config()` reads `env()` while a raw SDK falls through to its own `getenv()` chain. Fix: set both `<env force="true">` and `<server>` entries. Full mechanism in [testing.md](./testing.md). - **`afterCommit` callbacks DO fire under `RefreshDatabase`** -- the belief they're deferred forever is false, but post-commit DURABILITY still isn't observable since the commit under test is a savepoint. Fix: test deferral behavior directly; verify durability claims separately. Full mechanism in [testing.md](./testing.md). - **Every parallel worker running `RefreshDatabase` needs its own database** -- `artisan test --parallel` provisions one per worker, a manual `phpunit` fan-out does not, and concurrent `migrate:fresh` races leave the shared DB half-migrated. Fix: confirm no other `phpunit` process is running before launching a suite; set `DB_DATABASE` per process for intentional overlap. Full mechanism (including Postgres `max_locks_per_transaction`) in [testing.md](./testing.md). - **`withToken('fake')` sets a header; it does not stub a custom guard**, so every other path still resolves through the real guard. Fix: use `actingAs($user, '<guard>')` when the intent is "this request is authenticated". Full mechanism in [testing.md](./testing.md). - Coverage target: 80%+ with `pcov` or `XDEBUG_MODE=coverage` in CI Generic test discipline (anti-patterns, mock rules, rationalization resistance): `ia-writing-tests` skill. Laravel testing deep dives: see References below. ## Common Pitfalls Real production footguns, invisible to PHPStan and feature tests alone. Mechanism and fix for each: [common-pitfalls.md](./common-pitfalls.md), except where the bullet links elsewhere. - **Query-builder `update()`** -- `Model::query()->where(...)->update([...])` and `Relation::update()` fire no model events, so observers and audit traits are bypassed. - **A database-level FK cascade** -- fires no Eloquent events, and is a pure no-op when the parent uses `SoftDeletes`, because the trait rewrites `delete()` as an `UPDATE`. - **Observer `deleting()` cleanup at parent scope** -- wipes every sibling's storage on a single-row delete. - **`BelongsToMany` pivot writes** -- `attach`/`detach`/`sync`/`updateExistingPivot` fire no pivot model events without `using()`, and `sync()` reads the RAW pivot table, so a relationship-level `where` never filters it. - **`chunkById + json_decode + mutate + json_encode + update`** -- loses any concurrent write to a jsonb column between the SELECT and the UPDATE ([pitfalls-deep.md](./pitfalls-deep.md)). - **`date:<fmt>` cast format** -- reaches `$model->toArray()` only, never `JsonResource::resolve()`. - **A string that trims to empty** -- skips every non-implicit validation rule, `nullable` or not ([pitfalls-deep.md](./pitfalls-deep.md)). - **An empty array versus an absent key** -- `empty()` and truthiness conflate them, so a Clear-all save can become a silent no-op. `isset()` and `?? null` distinguish `[]` from absence, but conflate `null` with absence; use `array_key_exists()` when null presence matters. Form encoding can drop empty arrays on the wire too. - **Nested-array validation** -- `'items.*.name'` rules do not stop `items.*` from being a scalar; always pair with `'items.*' => 'array'`. - **`validated()`** -- rebuilds a nested key from its ruled sub-keys only and drops the rest ([pitfalls-deep.md](./pitfalls-deep.md)). - **The `boolean` rule** -- validates but never normalises, so `=== true` is false for input it accepted ([pitfalls-deep.md](./pitfalls-deep.md)). - **`distinct` at two wildcard levels** -- compares the whole payload, not per-parent ([pitfalls-deep.md](./pitfalls-deep.md)). - **`Exists` / `Unique` self-skip after any message** -- so `bail` does not protect the query, and the exposed value is the rule's SCOPE argument ([pitfalls-deep.md](./pitfalls-deep.md)). - **`DB::afterCommit`** -- prevents run-on-rollback; it does NOT retry a post-commit failure ([pitfalls-deep.md](./pitfalls-deep.md)). - **An observer writing a model the caller also holds** -- leaves a stale in-memory copy that the caller's later `save()` re-clobbers ([pitfalls-deep.md](./pitfalls-deep.md)). - **`Collection::unique()`** -- compares loosely, so `"00123"` and `"123"` collapse and a dedup or merge guard silently drops data; use `uniqueStrict()`. - **`QueryException::getMessage()`** -- interpolates raw bindings plus host and database into the message. - **`Carbon::parse('2020')`** -- is today at 20:20, not the year 2020 ([pitfalls-deep.md](./pitfalls-deep.md)). - **A custom auth guard whose failure path calls `report()`** -- infinitely recurses; an unauthenticated DoS ([pitfalls-deep.md](./pitfalls-deep.md)). - **A backed enum serialises as the case NAME** -- so renaming or removing a case breaks unserialization silently ([pitfalls-deep.md](./pitfalls-deep.md)). - **A `composer.lock` conflict confined to `content-hash`** -- is not a lock conflict; recompute it, never hand-pick a side ([pitfalls-deep.md](./pitfalls-deep.md)). -
testing.md 8 KB
# Testing Laravel (PHPUnit) Use PHPUnit with Laravel's testing helpers. Every test file starts with `declare(strict_types=1)`. ## PHPUnit Essentials ```php <?php declare(strict_types=1); namespace Tests\Feature; use App\Models\{User, Post}; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; final class PostTest extends TestCase { use RefreshDatabase; public function test_authenticated_user_can_create_post(): void { $user = User::factory()->create(); $response = $this->actingAs($user) ->postJson('/api/posts', ['title' => 'New Post', 'body' => 'Content']); $response->assertCreated() ->assertJson(['data' => ['title' => 'New Post']]); $this->assertDatabaseHas('posts', [ 'title' => 'New Post', 'user_id' => $user->id, ]); } } ``` ## Data Providers Data providers for boundary/validation testing: ```php #[DataProvider('titleLengthProvider')] public function test_validates_title_length(string $title, bool $valid): void { $user = User::factory()->create(); $response = $this->actingAs($user) ->postJson('/api/posts', ['title' => $title, 'body' => 'Content']); $valid ? $response->assertCreated() : $response->assertUnprocessable(); } public static function titleLengthProvider(): array { return [ 'too short' => ['AB', false], 'minimum valid' => ['ABC', true], 'maximum valid' => [str_repeat('A', 255), true], 'too long' => [str_repeat('A', 256), false], ]; } ``` ## Running Tests For large test suites, call PHPUnit directly to avoid artisan's memory overhead: ```bash ./vendor/bin/phpunit # all tests (direct, lower memory) ./vendor/bin/phpunit --filter=PostTest # by name ./vendor/bin/paratest --processes=auto # parallel via ParaTest (what artisan test --parallel wraps) ./vendor/bin/phpunit --coverage-text --min=80 # with coverage threshold php artisan test # small suites or quick runs php -d memory_limit=1G artisan test # if artisan needed on large suites ``` ## Strict-mode MissingAttributeException from factories Test throws `MissingAttributeException` → strict mode (`Model::shouldBeStrict()`) + factory omits a column with a DB default. Eloquent does not re-read database-level defaults after an INSERT that omitted the column, so the attribute is ABSENT from the instance `create()` returns. The loud failure is the lucky case: `preventAccessingMissingAttributes()` bypasses on `$this->wasRecentlyCreated` in every environment, so a provisioning endpoint that creates the record and renders that same instance in one request emits JSON `null` for the field with nothing thrown, violating a `required` non-nullable OpenAPI field on every such response. The suite cannot reach the silent case: either the factory sets the column, so the attribute exists, or `actingAs()` clears `wasRecentlyCreated` and the read throws. Fix on the model rather than the factory -- `protected $attributes = ['notification_channel' => NotificationChannel::Email]` -- so every creation path carries it; an enum instance is safe as the default, and this does not blunt strict mode, because `newFromBuilder()` calls `setRawAttributes(..., true)` and replaces the defaults wholesale. Adding the column to the factory or `->refresh()` after create fixes only that one call site. ## Environment variable pinning in phpunit.xml `force="true"` on a `phpunit.xml` `<env>` entry pins `getenv()` and `$_ENV`, not Laravel's `env()`. `PhpHandler::handleEnvVariables()` never writes `$_SERVER`, and phpdotenv's default adapter order puts `ServerConstAdapter` before `EnvConstAdapter` -- so `env()`, and every `config/*.php` that reads it, still resolves the inherited process value. The PHP CLI's default `variables_order=GPCS` is what put that value in `$_SERVER`. The two surfaces have different consumers in one request: `config()` reads `env()`, while an SDK constructed without explicit credentials falls through to its own `getenv()` chain. Pin both; `<server>` is written unconditionally, so `force` on it is redundant rather than required: ```xml <env name="AWS_ACCESS_KEY_ID" value="testing" force="true"/> <server name="AWS_ACCESS_KEY_ID" value="testing"/> ``` A variable that is set but EMPTY is not `false` to `getenv()`, so a non-forced `<env>` entry skips it and the empty value survives the pin. ## afterCommit callbacks under RefreshDatabase `afterCommit` callbacks DO fire under `RefreshDatabase` -- the belief that the trait's wrapping transaction defers them forever is false and spreads through test comments justifying weaker assertions. `beginDatabaseTransaction()` installs `Illuminate\Foundation\Testing\DatabaseTransactionsManager`, which skips the wrapping transaction when deciding applicability and runs the callback immediately when no inner transaction is open. So deferral IS testable under the trait: wrap the call in a nested `DB::transaction()` and assert the callback runs on release and is dropped on rollback -- the two cases genuinely differ, so the negative assertion is not vacuous. What is NOT observable under the trait is post-commit DURABILITY: the commit under test is a savepoint. Split the question before choosing (generic form in `ia-writing-tests`). ## Parallel worker database isolation Every parallel worker running `RefreshDatabase` needs its own database, and so does every hand-launched `phpunit`. `artisan test --parallel` creates `<db>_test_<token>` per worker; a manual fan-out of `vendor/bin/phpunit` processes does not, so concurrent `migrate:fresh` runs race and leave the shared database half-migrated. The signature is schema-level, not assertion-level -- `relation "users" already exists`, `table "cache" does not exist`, `relation "migrations" does not exist` -- in files the change never touched, so it reads as a regression in the code under review. Before launching a suite, confirm no other `phpunit` is running (`ps ax | grep -c '[p]hpunit'`) rather than trusting any external lock; set `DB_DATABASE` per process when runs must overlap. Postgres also needs `max_locks_per_transaction` well above the default 64 -- `migrate:fresh` drops every table in one CASCADE transaction and exhausts the shared lock table around 8 workers. Any other shared store (Redis, an external-store emulator) needs a per-worker prefix or DB index too. ## withToken() does not stub a custom guard `withToken('fake')` sets a header; it does not stub a custom guard. Mocking the action that ONE middleware uses to turn a token into a user leaves every other path -- a second middleware calling `$request->user()`, exception rendering, audit context -- resolving through the real guard, which will fetch keys over HTTP and decode the fake token for real. Use `actingAs($user, '<guard>')` when the intent is "this request is authenticated", and treat a test that only mocks the resolution action as covering that action, not auth. ## Static memos outlive every database rollback A class caching a resolved model in a `private static` holds it for the lifetime of the PHP process -- one request under PHP-FPM, one whole suite under PHPUnit -- so `RefreshDatabase`, `DatabaseTransactions`, and an explicit rollback all leave it populated. The signature is a test that passes in isolation and fails in the suite while asserting an *absence*: the memo was filled by an earlier test's row, that row is gone, and the subject under test still resolves it. Do not delete the memo to fix the test; a per-request cache is correct production behaviour and removing it re-introduces the query the memo exists to avoid. Clear it for that one test through reflection in `setUp()`: ```php $property = new ReflectionProperty(TenantResolver::class, 'resolved'); $property->setValue(null, null); ``` Any static holding an Eloquent model, a container binding, or a config-derived value has the same exposure; grep the class under test for `static $` before accepting "passes alone, fails in the suite" as a database-isolation problem.
-
-
SKILL.md 4.8 KB
--- name: ia-php-laravel class: language description: >- Modern PHP 8.4 and Laravel patterns: architecture, Eloquent, migrations, queues, testing. Use when working with Laravel, Eloquent, Blade, artisan, or building/testing a framework-based PHP app. Not for php-src internals, standalone PHP libraries, or general PHP language discussion. paths: "**/*.php" --- # PHP & Laravel Development Scoped to framework-level PHP. Work on php-src internals or a native PHP extension is C, not PHP: the `ia-c-systems` skill covers it, including the Zend API conventions (`gen_stub` arginfo, the request-scoped allocator, custom object handlers, `.phpt`). ## Working rules - Keep simple CRUD simple; extract cross-model orchestration only when it has a concrete use. - Validate and authorize at request boundaries; serialize through explicit resources and validate third-party responses. - Preserve deployed migration history, queued payload compatibility, and concurrent writes. - Verify cache compilation, queue execution, and HTTP behavior through their real entrypoints when those paths change. ## Code Style - `declare(strict_types=1)` in every file - Happy path last -- guards and errors first, success at the end. Early returns, no `else`. - Comments explain *why*, never *what*. Never comment tests. If code needs a "what" comment, rename or restructure. - No single-letter variables -- `$exception` not `$e`, `$request` not `$r` - `?string` not `string|null`. Always specify `void`. Import classnames, never inline FQN. - **Widening one parameter to `?T` obliges auditing every call site that forwards the same value** -- the sibling call still declares `string`, and `null` throws a `TypeError` there even with no `declare(strict_types=1)`, because coercive mode never coerces `null` into a scalar. Strictness is decided by the file the CALL is written in, never by the callee's file. Full mechanism in [common-pitfalls.md](./references/common-pitfalls.md). - Validation uses array notation `['required', 'email']` for easier custom rule classes - PHPStan level 8+ (`phpstan analyse --level=8`); aim for 9 on new projects. `@phpstan-type` / `@phpstan-param` for generic collection types. The missing-iterable-value-type check lands at **level 6** (and every level above it), so any project at 8+ inherits it: use the generic form on every iterable -- `@return Collection<int, User>`, `@param array<int, MyObject>` -- and array-shape notation `array{first: SomeClass, second: SomeClass}` for fixed-key returns; a bare `Collection` or `array` will not clear it. ## Discipline - Simplicity first -- every change as simple as possible, minimal code impact - Only touch what's necessary -- no unrelated changes - No hacky workarounds -- if a fix feels wrong, step back and implement the clean solution - New abstraction requires 3+ usage sites; otherwise inline it - No empty catch blocks -- log or rethrow, never swallow - Verify before declaring done: `./vendor/bin/phpstan analyse --level=8 && ./vendor/bin/phpunit` with zero warnings - Checkpoint per stage, not only at the end: `migrate:status` after a migration, `route:list --path=<prefix>` after routing changes, `queue:work --once` after adding a job, `pint --test` before the PR -- each catches its failure class while the change is small ## References - [laravel-ecosystem.md](./references/laravel-ecosystem.md) -- Notifications, Task Scheduling, Custom Casts - [testing.md](./references/testing.md) -- PHPUnit essentials, data providers, running tests - [feature-testing.md](./references/feature-testing.md) -- Auth, validation, API, console, DB assertions - [mocking-and-faking.md](./references/mocking-and-faking.md) -- Facade fakes, action mocking, Mockery - [factories.md](./references/factories.md) -- States, relationships, sequences, afterCreating hooks - [production-performance.md](./references/production-performance.md) -- OPcache, JIT, preloading, deploy caches - [common-pitfalls.md](./references/common-pitfalls.md) -- event-layer bypasses, FK cascades, pivot writes, resource and request-shape traps - [pitfalls-deep.md](./references/pitfalls-deep.md) -- afterCommit alternatives, observer desync, jsonb race, savepoints, validation-rule internals ## Task-specific references Read the relevant reference before implementing or reviewing the matching behavior: - For PHP features, controller/action design, routing, resources, or external APIs: [framework-patterns.md](./references/framework-patterns.md). - For migrations, Eloquent writes, casts, queues, job payloads, or production startup: [persistence-and-jobs.md](./references/persistence-and-jobs.md). - For PHPUnit work or changes affecting events, serialization, validation, or lifecycle behavior: [testing-and-pitfalls.md](./references/testing-and-pitfalls.md). Existing specialized references, when the corresponding topic applies: -
SPEC.md 4.4 KB
# ia-php-laravel Specification ## Intent `ia-php-laravel` is a `language`-class skill (stack-specific patterns and idioms). Modern PHP 8.4 and Laravel patterns: architecture, Eloquent, queues, testing. Use when working with Laravel, Eloquent, Blade, artisan, PHPUnit, PHPStan, or building/testing PHP applications with frameworks. Not for PHP internals (php-src) or general PHP language discussion. ## Scope In scope: - Behaviors described in `SKILL.md` and routed via the should_trigger phrasings in `distillery/tests/fixtures/triggers/ia-php-laravel.jsonl`. - Updates to runtime behavior, structure, trigger precision, references, and validation. Out of scope: - Acting as the runtime instructions themselves (those live in `SKILL.md`). - Trigger phrasings already covered by adjacent `ia-*` skills (`validate-plugin` flags >70% description overlap as DUPLICATE_TRIGGER). - <!-- to fill in: domain-specific exclusions when the skill drifts --> ## Trigger Context - Class: `language` - Hook regex: `plugins/whetstone/hooks/skill-patterns.sh` -> `SKILL_PATTERNS[ia-php-laravel]` - Common requests (from fixture should_trigger): - "add a new Laravel controller for user profiles" - "fix the Eloquent query performance" - "create a blade template for the dashboard" - Should not trigger for (from fixture should_not_trigger): - "write a React component for the settings page" - "optimize the PostgreSQL query plan" - "write a Python CLI tool for data import" ## Source And Evidence Model Authoritative sources: - `SKILL.md` -- runtime instructions and reference routing. - `references/*.md` -- bundled supplementary content (6 file(s)). - `distillery/tests/fixtures/triggers/ia-php-laravel.jsonl` -- positive and negative trigger phrasings under regression test. - `plugins/whetstone/hooks/skill-patterns.sh` -- regex pattern that fires this skill. - `distillery/.eval-data/ia-php-laravel/` -- harvested session examples (when present). Data that must not be stored in this skill or its references: - Secrets, credentials, tokens. - Machine-specific filesystem paths (`/home/...`, `/Users/...`, `~/ai/...`). The validator (`MACHINE_PATH_LEAK`) flags these as HIGH. - Private URLs, customer data, or unredacted personal information. ### Coverage matrix | Dimension | Status | Evidence | |---|---|---| | Trigger fixtures | complete | distillery/tests/fixtures/triggers/ia-php-laravel.jsonl (>=5 should_trigger, >=5 should_not_trigger) | | Hook regex pattern | complete | plugins/whetstone/hooks/skill-patterns.sh (`SKILL_PATTERNS[ia-php-laravel]`) | | Reference architecture | complete | 6 file(s) under references/ | | Real-usage signal | <!-- populated by harvest-sessions when sessions exist --> | distillery/.eval-data/ia-php-laravel/ (created by harvest-sessions) | ## Evaluation Lightweight (run on every change): ```bash python3 distillery/scripts/distiller.py validate-plugin --component ia-php-laravel python3 distillery/scripts/distiller.py test-triggers --skill ia-php-laravel ``` Deeper (when behavior risk warrants): ```bash python3 distillery/scripts/distiller.py dspy-eval ia-php-laravel python3 distillery/scripts/distiller.py diagnose-negatives ia-php-laravel ``` Acceptance gates: - `validate-plugin --component ia-php-laravel` returns 0 HIGH findings. - `test-triggers --skill ia-php-laravel` returns F1 = 1.0 with floors of 5 should_trigger and 5 should_not_trigger. - For dspy-eval, the composite score does not regress against the most recent saved baseline (see `distillery/.eval-data/ia-php-laravel/history.json`). ## Known Limitations <!-- to fill in over time as drift surfaces. Default rule: any time diagnose-negatives surfaces a recurring failure pattern, document it here so future maintainers understand the trade-off the current implementation accepts. --> ## Maintenance Notes - Update `SKILL.md` when the runtime workflow, branch conditions, or output contract changes. - Update this `SPEC.md` when intent, scope, evidence model, evaluation gates, or maintenance expectations change. - Update the trigger fixture when adding new positive phrasings, removing stale ones, or expanding scope (the 5/5 floor is a hard validator gate). - Update the hook regex in `skill-patterns.sh` whenever fixture positives expose a missed phrasing; verify F1 = 1.0 with `eval-triggers` before committing. - Run the full release pipeline via `/release` -- never bump versions or update CHANGELOG.md from a per-skill edit.
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.