diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..7925832
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,8 @@
+/.github export-ignore
+/art export-ignore
+/docs export-ignore
+/tests export-ignore
+/.gitattributes export-ignore
+/.gitignore export-ignore
+/AGENTS.md export-ignore
+/phpunit.xml.dist export-ignore
diff --git a/AGENTS.md b/AGENTS.md
index 46b52e0..17e2693 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,6 +1,5 @@
# Agent Notes
-- Follow the root repository instructions.
- Use `php-guidelines-from-spatie` for PHP changes.
- Keep exceptions package-local under `Skir\Server\Exceptions`.
- Run `vendor/bin/pint --dirty --format agent` after PHP edits.
diff --git a/README.md b/README.md
index 5df9742..285684a 100644
--- a/README.md
+++ b/README.md
@@ -10,11 +10,11 @@
Laravel package for exposing SkirRPC methods from a Laravel application.
-## Why Skir?
+Requires PHP 8.4+, Laravel 13, and Node.js for the Skir compiler.
-[Skir](https://skir.build/) is a modern schema language for defining data models and APIs. You describe your structs, enums, and RPC methods once in `.skir` files, then generate clean, idiomatic, and type-safe code across your stack. Skir includes generators for TypeScript, Python, Java, Go, C#, C++, Kotlin, Rust, Swift, and more, while the PHP generators in this ecosystem bring the same schema-first workflow to Laravel. This gives your backend, frontend, and other services a shared source of truth instead of separately maintained DTOs and API contracts.
+## Why Skir?
-SkirRPC offers many of the same benefits as gRPC—shared method definitions, generated clients and servers, and end-to-end type safety—but runs over standard HTTP requests and integrates with the frameworks you already use. This package brings that workflow to Laravel: generated contracts handle serialization and type information, while your procedures remain ordinary Laravel controllers resolved through the container.
+[Skir](https://skir.build/) is a schema language: you define structs, enums, and RPC methods once and generate typed code for PHP, TypeScript, Python, Go, and other languages. This package serves those methods over SkirRPC from ordinary Laravel controllers.
## Features
@@ -27,7 +27,7 @@ SkirRPC offers many of the same benefits as gRPC—shared method definitions, ge
## Quick start
-Install the server package and one PHP generator. This example uses Simple Data Objects:
+Install the server package and one PHP generator. This example uses Simple Data Objects; see [Generated procedures](docs/generated-procedures.md) for Laravel Data and standard PHP objects:
```bash
composer require php-skir/server std-out/simple-data-objects
@@ -68,7 +68,7 @@ generators:
namespace: Skir
```
-Skir requires every output directory to end in `/skirout`. It owns that directory and may replace or remove files inside it, so keep handwritten application code elsewhere.
+Skir owns the `/skirout` directory and may replace files inside it, so keep handwritten code elsewhere.
Generate the PHP contracts, configure Composer, and refresh the autoloader:
@@ -90,13 +90,15 @@ The `configure-composer` command reads `skir.yml` and adds this PSR-4 mapping to
}
```
-Keep controllers outside `skirout`; the default application-owned namespace is `App\Skir`. Scaffold every generated method and its Form Request with:
+Besides the PHP contracts, the generator writes `skir-server-manifest.json` into its `outDir`. `php artisan skir:make` reads the manifests listed in the `skir-server.manifests` config key, which defaults to `app/Skir/skirout/skir-server-manifest.json`, so this layout needs no configuration. Rerun `npx skir gen` (or pass `--generate`) whenever the schema changes.
+
+Scaffold every generated method and its Form Request into the application-owned `App\Skir` namespace with:
```bash
php artisan skir:make --all
```
-Generated Form Requests deny access by default; define their `authorize()` and `rules()` methods before exposing the procedure. The command prints the route registrations to add. A module controller has this shape:
+Generated Form Requests deny access by default; define their `authorize()` and `rules()` methods before exposing the procedure. Scaffolded controller methods throw a `LogicException` until you implement them. The command prints the route registrations to add. After implementation, a module controller looks like this:
```php
studio();
```
+The API routes file adds the `/api` prefix, so this endpoint serves `/api/skir`. A POST endpoint in `routes/web.php` fails CSRF verification with HTTP 419 unless its URI is excluded. Class strings, `Skir::controller()`, and `Skir::method()` registrations survive `php artisan route:cache`; provider instances do not. See [Routing](docs/routing.md#route-caching).
+
Only public controller methods carrying a `SkirMethod` attribute are registered. The generated enum case identifies the Skir method; the PHP method name does not.
The `studio()` call explicitly enables the endpoint-scoped Studio regardless of the configured default. With the default query key, Studio is available at `/api/skir?studio`. See [Routing and Studio](docs/routing.md#studio) for middleware, authorization, and alternative routing layouts.
diff --git a/art/octopus-laravel.png b/art/octopus-laravel.png
deleted file mode 100644
index 27928aa..0000000
Binary files a/art/octopus-laravel.png and /dev/null differ
diff --git a/art/octopus-laravel.svg b/art/octopus-laravel.svg
deleted file mode 100644
index 0445bd4..0000000
--- a/art/octopus-laravel.svg
+++ /dev/null
@@ -1 +0,0 @@
-
\ No newline at end of file
diff --git a/composer.json b/composer.json
index 51b623b..d88d933 100644
--- a/composer.json
+++ b/composer.json
@@ -7,7 +7,6 @@
"laravel",
"php",
"rpc",
- "serialization",
"skir"
],
"homepage": "https://github.com/php-skir/server",
diff --git a/docs/generated-procedures.md b/docs/generated-procedures.md
index 2452143..63d9a6f 100644
--- a/docs/generated-procedures.md
+++ b/docs/generated-procedures.md
@@ -87,7 +87,7 @@ Controller methods can receive the generated DTO directly or receive a Laravel F
2. `fromArray()` for standard PHP objects;
3. `fromSkirValue()` for another compatible application type.
-Simple Data Objects and Laravel Data therefore run their generated validation when a decoded object payload is injected directly. Standard PHP objects are hydrated through `fromArray()` and do not add semantic Laravel validation. Use a Form Request when a standard PHP payload needs application validation.
+Simple Data Objects and Laravel Data therefore run their generated validation when a decoded object payload is injected directly; a failure returns HTTP 422 `skir_validation_failed` with field errors in `error.details`, the same as a Form Request. Standard PHP objects are hydrated through `fromArray()` and do not add semantic Laravel validation. Use a Form Request when a standard PHP payload needs application validation.
For typed validation, extend `SkirFormRequest` and identify the generated request class:
diff --git a/docs/protocol.md b/docs/protocol.md
index 92d8381..b848f83 100644
--- a/docs/protocol.md
+++ b/docs/protocol.md
@@ -39,9 +39,9 @@ Failures return a JSON error body with a Skir error code:
| Status | Code | When |
| --- | --- | --- |
-| 422 | `skir_invalid_request` | The body is not a valid SkirRPC request, the method name is ambiguous, or the request value does not match the method's request type. |
+| 422 | `skir_invalid_request` | The body is not a valid SkirRPC request, the method name is ambiguous, the request value does not match the method's request type, or it cannot be passed to the controller's request parameter. |
| 404 | `skir_method_not_found` | No method with that name or number is registered on the endpoint. |
-| 422 | `skir_validation_failed` | A Form Request rejected the decoded input. |
+| 422 | `skir_validation_failed` | A Form Request or a validating generated DTO (Laravel Data, Simple Data Objects) rejected the decoded input. |
| 403 | `skir_authorization_failed` | A Form Request's `authorize()` returned `false`. |
| 500 | `skir_invalid_response` | The method returned a value that cannot be serialized as its response type. |
diff --git a/docs/routing.md b/docs/routing.md
index 7342294..01e186e 100644
--- a/docs/routing.md
+++ b/docs/routing.md
@@ -2,6 +2,10 @@
A SkirRPC endpoint is one Laravel route composed from one or more procedure sources. Attribute-based controllers are the primary Laravel-facing workflow, while invokable controllers, generated providers, and manual handlers remain available for other layouts.
+## Where to register endpoints
+
+Register endpoints in `routes/api.php`; on Laravel 13 run `php artisan install:api` to create it. That file's routes are prefixed with `/api`, so `Route::skirRpc('/skir')` there serves `/api/skir`. SkirRPC calls are POST requests without a CSRF token, so an endpoint in `routes/web.php` answers HTTP 419 unless its URI is excluded from CSRF verification, for example with `$middleware->validateCsrfTokens(except: ['skir'])` in `bootstrap/app.php`.
+
## Attributed controllers
Register a controller through `Skir::controller()`:
@@ -130,10 +134,11 @@ Terminable controller middleware is not supported. A Skir method does not pass t
Both ordinary Laravel `FormRequest` classes and `SkirFormRequest` subclasses use Laravel's native container resolution, input preparation, authorization, rules, and after-validation hooks. A `SkirFormRequest` additionally provides the typed `$request->skir()` method described in [Generated procedures](generated-procedures.md#request-hydration-and-validation).
-Failures raised while Laravel resolves these dependencies use SkirRPC error responses rather than Laravel's normal validation redirect or JSON shape:
+Failures raised while Laravel resolves these dependencies, or while a generated DTO parameter is hydrated, use SkirRPC error responses rather than Laravel's normal validation redirect or JSON shape:
-- failed validation returns HTTP `422` with error code `skir_validation_failed` and field errors in `error.details`;
-- failed Form Request authorization returns HTTP `403` with error code `skir_authorization_failed`.
+- failed Form Request validation, and validation thrown by DTO hydration (Laravel Data, Simple Data Objects), returns HTTP `422` with error code `skir_validation_failed` and field errors in `error.details`;
+- failed Form Request authorization returns HTTP `403` with error code `skir_authorization_failed`;
+- a payload that cannot be passed to the request parameter, such as `null` for a non-nullable DTO or Form Request, returns HTTP `422` with error code `skir_invalid_request`.
Exceptions thrown by controller business logic continue through Laravel's normal exception handling.
@@ -162,7 +167,7 @@ Route::skirRpc('/api/skir', [
]);
```
-Each Skir method can be registered only once on an endpoint. Duplicate registrations throw a `SkirServerException` while the route is being built.
+Each Skir method can be registered only once on an endpoint. Duplicate registrations throw a `SkirServerException` while the route is registered. When routes are cached, the endpoint is built on its first call instead, and that call answers with a `skir_duplicate_method` error.
## Invokable controllers
@@ -258,8 +263,6 @@ Route::skirRpc('/api/skir', [
As an inheritance-based alternative, a handwritten class may extend the generated `AbstractSkirProcedures`. That base class is itself a procedure provider, so the handwritten class can be registered directly on the route.
-`RequestContext` remains accepted as a compatibility type in controller methods and manually registered handlers. New code should type-hint `SkirContext`. Generated procedure contracts use `SkirContext` explicitly.
-
## Manual registration
Manual handlers are useful for tests, very small endpoints, or experiments that do not need generated provider classes.
@@ -272,7 +275,7 @@ use Illuminate\Support\Facades\Route;
Route::skirRpc('/api/skir');
```
-Then register a descriptor and handler on the application-wide server:
+Then register a descriptor and handler on the application-wide server from a service provider's `boot()` method:
```php
use Skir\Runtime\MethodDescriptor;
@@ -280,20 +283,31 @@ use Skir\Runtime\Type;
use Skir\Server\SkirContext;
use Skir\Server\SkirServer;
-app(SkirServer::class)->addMethod(
- new MethodDescriptor('Square', 1001, Type::float32(), Type::float32()),
- fn (float $value, SkirContext $context): float => $value * $value,
-);
+public function boot(): void
+{
+ $this->app->make(SkirServer::class)->addMethod(
+ new MethodDescriptor('Square', 1001, Type::float32(), Type::float32()),
+ fn (float $value, SkirContext $context): float => $value * $value,
+ );
+}
```
+Every endpoint registered without providers shares this one application-wide server.
+
The endpoint accepts standard SkirRPC requests, for example the body `Square:1001::5`, and answers with the encoded response value, `25`. See [Wire protocol](protocol.md) for every request form.
-GET requests are also supported. Pass the method and a JSON-encoded request value as query parameters:
+GET requests carry the same string in the query string:
```text
-/api/skir?method=Square&request=5.0
+/api/skir?Square:1001::5
```
+## Route caching
+
+`php artisan route:cache` works for endpoints whose providers are class strings, `Skir::controller()` definitions, or `Skir::method()` definitions that reference a generated method enum. The cached route stores that list, and the endpoint's procedures are built on its first call in each process. Without a route cache, providers are resolved and registered when the route is registered, so configuration errors surface at boot.
+
+Provider instances such as `new AdminProcedures` cannot be stored in the route cache. They work while routes are uncached; once routes are cached, calling the endpoint throws a `LogicException` naming it. Handlers added to the application-wide `SkirServer` in a service provider are unaffected, because service providers still boot when routes are cached.
+
## Studio
Studio is controlled by these settings in `config/skir-server.php`:
@@ -315,7 +329,7 @@ Route::skirRpc('/api/skir', [
])->studio();
```
-Calling `studio()` explicitly enables Studio for that endpoint, regardless of `studio_enabled`. With the default query key, open `/api/skir?studio` with a GET request. Only the query parameter's presence matters; its value is ignored. Studio renders only the procedures registered on that route, so separate endpoints keep separate procedure lists.
+Calling `studio()` explicitly enables Studio for that endpoint, regardless of `studio_enabled`. With the default query key, open `/api/skir?studio` with a GET request. Only the query parameter's presence matters; its value is ignored. Studio renders the procedures registered on that route. Endpoints with providers keep separate procedure lists; endpoints registered without providers all share the application-wide `SkirServer` and list the same procedures.
Set `studio_enabled` to `true` to enable Studio for every SkirRPC route by default. Calling `studio(false)` on a route overrides that global setting and keeps Studio disabled for that endpoint.
diff --git a/docs/superpowers/plans/2026-07-20-laravel-controller-dispatch.md b/docs/superpowers/plans/2026-07-20-laravel-controller-dispatch.md
deleted file mode 100644
index 2fec4f3..0000000
--- a/docs/superpowers/plans/2026-07-20-laravel-controller-dispatch.md
+++ /dev/null
@@ -1,901 +0,0 @@
-# Laravel Controller Dispatch Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Integrate the existing Laravel scaffolding branch, expose decoded Skir payloads through Laravel request bags, and dispatch attributed Skir controllers through Laravel 13 middleware, Form Request, dependency-injection, and controller-action facilities.
-
-**Architecture:** Reuse the existing `feature/laravel-scaffolding` worktree as the integration branch and merge current `main` into it. A method-scoped `Illuminate\Http\Request` will preserve transport context while replacing all input bags with the decoded method payload. A thin `SkirControllerDispatcher` extension plus prepared-procedure contract will seed Skir-specific parameters, let Laravel resolve remaining dependencies, and run controller middleware around the encoded response.
-
-**Tech Stack:** PHP 8.4/8.5, Laravel 13 routing and pipeline components, Orchestra Testbench 11, PHPUnit 12, Skir runtime, Simple Data Objects, Spatie Laravel Data compatibility contracts, Docker Compose.
-
----
-
-## File map
-
-### Existing scaffolding integration
-
-- Modify: `composer.json` — combine current cross-package dependencies with scaffolding runtime dependencies.
-- Modify: `config/skir-server.php` — combine codec and Studio defaults with manifest and scaffolding defaults.
-- Modify: `src/SkirServerServiceProvider.php` — preserve current codec/provider validation while registering scaffolding and dispatch services.
-- Modify: `src/Http/Controllers/SkirRpcController.php` — preserve current transport parsing while moving method execution into the request scope and middleware pipeline.
-- Preserve from branch: `src/Commands/**`, `src/Scaffolding/**`, `src/Http/Requests/SkirFormRequest.php`, `src/Hydration/SkirPayloadHydrator.php`, their stubs, and their tests.
-
-### New dispatch boundaries
-
-- Create: `src/Contracts/PreparesProcedure.php` — optional contract for controller-backed handlers that prepare request-specific middleware and invocation.
-- Create: `src/PreparedProcedure.php` — immutable request-specific middleware plus invocation closure.
-- Create: `src/Http/Requests/SkirMethodRequestScope.php` — clone, sanitize, bind, and restore the decoded method request.
-- Create: `src/Routing/PreparedControllerParameters.php` — ordered seeded parameters and nullable Form Request markers.
-- Create: `src/Routing/SkirControllerDispatcher.php` — thin Laravel dispatcher extension for seeded parameters and scoped validation errors.
-- Modify: `src/RegisteredProcedure.php` — retain preparable handler objects instead of reducing every callable immediately to a closure.
-- Modify: `src/Routing/ControllerProcedureInvoker.php` — prepare Laravel route metadata, middleware, controller instance, and seeded Skir parameters.
-- Modify: `src/Routing/SkirControllerRouteDefinition.php` — resolve the new controller dispatcher dependencies.
-- Modify: `src/Routing/SkirMethodRouteDefinition.php` — do the same for invokable controllers.
-
-### Focused verification
-
-- Create: `tests/Feature/SkirMethodRequestScopeTest.php` — decoded bags, preserved context, and restoration.
-- Create: `tests/Feature/LaravelControllerDispatchTest.php` — native middleware, authorization, DI, contextual attributes, `callAction()`, and response behavior.
-- Modify: `tests/Feature/SkirFormRequestTest.php` — native ordinary and typed Form Request resolution for all DTO factories.
-- Modify: `tests/Feature/NullableControllerRequestTest.php` — nullable authorization and null action semantics through the new dispatcher.
-- Modify: `tests/Feature/ControllerProcedureInvokerTest.php` — direct DTO/context regression coverage.
-- Modify: `tests/Feature/SkirRpcControllerTest.php` — pipeline short-circuiting and encoded-response middleware.
-
-### Documentation
-
-- Modify: `README.md` — concise feature and quick-start references.
-- Create: `docs/scaffolding.md` — move the branch's detailed `skir:make` and `skir:make-request` instructions out of the README.
-- Modify: `docs/generated-procedures.md` — three DTO targets and generation/scaffolding sequence.
-- Modify: `docs/routing.md` — native Laravel controller attributes, decoded request lifecycle, Studio, and limitations.
-
----
-
-### Task 1: Integrate the complete scaffolding branch with current main
-
-**Files:**
-- Modify: `README.md`
-- Modify: `composer.json`
-- Modify: `config/skir-server.php`
-- Modify: `src/Http/Controllers/SkirRpcController.php`
-- Modify: `src/SkirServerServiceProvider.php`
-- Preserve: all files added by `feature/laravel-scaffolding`
-
-- [ ] **Step 1: Verify both source branches and the existing worktree are clean**
-
-Run from the Trackr root:
-
-```bash
-git -C packages/server status --short --branch
-git -C packages/server/.worktrees/laravel-scaffolding status --short --branch
-git -C packages/server rev-list --left-right --count main...feature/laravel-scaffolding
-```
-
-Expected: both worktrees are clean; the existing worktree is on `feature/laravel-scaffolding`; both sides have commits to integrate.
-
-- [ ] **Step 2: Run both pre-merge baselines**
-
-Run from the Trackr root:
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server && vendor/bin/phpunit'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit'
-```
-
-Expected: current `main` reports `OK (97 tests, 251 assertions)` and the scaffolding branch reports its complete suite as passing.
-
-- [ ] **Step 3: Merge current main into the feature worktree**
-
-Run from `packages/server/.worktrees/laravel-scaffolding`:
-
-```bash
-git merge main
-```
-
-Expected conflicts: `README.md`, `config/skir-server.php`, `src/Http/Controllers/SkirRpcController.php`, and `src/SkirServerServiceProvider.php`. Do not abort or discard either history.
-
-- [ ] **Step 4: Resolve the combined package configuration**
-
-Make `config/skir-server.php` contain the current runtime settings and the branch's scaffolding settings:
-
-```php
- env('SKIR_SERVER_STUDIO_ENABLED', false),
- 'studio_query_key' => env('SKIR_SERVER_STUDIO_QUERY_KEY', 'studio'),
- 'codec' => DenseJsonCodec::class,
-
- 'manifests' => [
- base_path('app/Skir/skirout/skir-server-manifest.json'),
- ],
-
- 'generator_command' => ['npx', 'skir', 'gen'],
-
- 'scaffolding' => [
- 'controller_style' => 'module',
- 'controller_namespace' => 'App\\Skir',
- 'single_controller' => 'App\\Skir\\SkirController',
- 'request_namespace' => 'App\\Http\\Requests\\Skir',
- 'form_requests' => true,
- ],
-];
-```
-
-- [ ] **Step 5: Resolve Composer requirements without losing cross-package tests**
-
-The final relevant `composer.json` sections must include the scaffolding runtime dependencies and the existing client development dependency/repository:
-
-```json
-{
- "require": {
- "php": "^8.4",
- "laravel/framework": "^13.0",
- "nikic/php-parser": "^5.8",
- "php-skir/runtime": "^0.1@dev",
- "symfony/process": "^7.4|^8.0"
- },
- "require-dev": {
- "laravel/pint": "^1.29",
- "orchestra/testbench": "^11.0",
- "php-skir/client": "^0.1@dev",
- "phpunit/phpunit": "^12.5",
- "spomky-labs/cbor-php": "^3.2"
- },
- "repositories": [
- {
- "type": "path",
- "url": "../runtime",
- "options": { "symlink": false }
- },
- {
- "type": "path",
- "url": "../client",
- "options": { "symlink": false }
- }
- ]
-}
-```
-
-Keep the existing metadata, autoload, scripts, suggestions, and Composer configuration around these sections unchanged.
-
-- [ ] **Step 6: Resolve the service provider additively**
-
-Preserve the current validated `SkirCodec` binding and route-provider error behavior. Add the scaffolding registrations without replacing them:
-
-```php
-$this->app->singleton(ManifestRepository::class);
-$this->app->bind(GeneratorRunner::class, SymfonyGeneratorRunner::class);
-$this->app->bind(ControllerScaffolding::class, ControllerScaffolder::class);
-```
-
-Preserve command registration:
-
-```php
-if ($this->app->runningInConsole()) {
- $this->commands([
- MakeSkirCommand::class,
- MakeSkirRequestCommand::class,
- ]);
-}
-```
-
-Merge the nested `scaffolding` defaults with configured values in `register()` while leaving `codec`, Studio settings, and provider validation intact.
-
-- [ ] **Step 7: Resolve transport controller and README conflicts conservatively**
-
-Keep current `main`'s explicit JSON object validation and current concise README structure. Preserve the scaffolding branch's PHP runtime classes and commands; detailed command documentation will move to `docs/scaffolding.md` in Task 7.
-
-At this checkpoint, `SkirRpcController` should retain its existing direct invocation. The request scope and middleware pipeline are introduced test-first in later tasks.
-
-- [ ] **Step 8: Refresh the feature worktree dependencies**
-
-Run from the Trackr root:
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && composer update --prefer-stable --prefer-dist --no-interaction --no-progress'
-```
-
-Expected: Composer resolves Laravel 13, PHP Parser, Symfony Process, runtime, client, and test dependencies successfully.
-
-- [ ] **Step 9: Verify and finish the merge commit**
-
-Run:
-
-```bash
-git -C packages/server/.worktrees/laravel-scaffolding diff --check
-git -C packages/server/.worktrees/laravel-scaffolding status --short
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit'
-```
-
-Expected: no unresolved files, no whitespace errors, and the merged suite passes.
-
-Then run from the feature worktree:
-
-```bash
-git add README.md composer.json config/skir-server.php src tests stubs
-git commit
-```
-
-Use the merge message `Merge current server main into Laravel scaffolding` if Git does not retain the default merge message.
-
----
-
-### Task 2: Add the method-scoped decoded Laravel request
-
-**Files:**
-- Create: `src/Http/Requests/SkirMethodRequestScope.php`
-- Create: `tests/Feature/SkirMethodRequestScopeTest.php`
-
-- [ ] **Step 1: Write failing request-scope tests**
-
-Add tests proving that a JSON transport request with outer `method`, `request`, query values, files, headers, route/user/session resolvers, and raw content produces a method request where:
-
-```php
-$this->assertSame([
- 'email' => 'maxim@example.com',
- 'name' => 'Maxim',
-], $methodRequest->all());
-$this->assertSame([], $methodRequest->query->all());
-$this->assertSame([], $methodRequest->files->all());
-$this->assertSame('Bearer token', $methodRequest->header('Authorization'));
-$this->assertSame($transportContent, $methodRequest->getContent());
-$this->assertSame($methodRequest, app('request'));
-```
-
-Add a second test whose callback throws `RuntimeException('dispatch failed')` and assert afterward:
-
-```php
-$this->assertSame($transportRequest, app('request'));
-```
-
-Add scalar and null payload cases and assert that their method request input bags are empty while the callback still receives the original scalar or null separately.
-
-- [ ] **Step 2: Run the focused test and verify failure**
-
-Run from the Trackr root:
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/SkirMethodRequestScopeTest.php'
-```
-
-Expected: FAIL because `SkirMethodRequestScope` does not exist.
-
-- [ ] **Step 3: Implement the request scope**
-
-Create `src/Http/Requests/SkirMethodRequestScope.php`:
-
-```php
-container->make('request');
- $methodRequest = Request::createFrom($transportRequest);
-
- $methodRequest->query->replace([]);
- $methodRequest->request->replace([]);
- $methodRequest->files->replace([]);
- $methodRequest->setJson(new InputBag);
-
- if (is_array($payload)) {
- $methodRequest->replace($payload);
- }
-
- $this->container->instance('request', $methodRequest);
-
- try {
- return $callback($methodRequest, $payload);
- } finally {
- $this->container->instance('request', $originalRequest);
- }
- }
-}
-```
-
-Use a PHPDoc closure signature if Pint or static analysis requires it; do not mutate `$transportRequest`.
-
-- [ ] **Step 4: Run tests and format**
-
-Run:
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/SkirMethodRequestScopeTest.php'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/pint --dirty --format agent'
-```
-
-Expected: request-scope tests pass and Pint reports no remaining changes after formatting.
-
-- [ ] **Step 5: Commit**
-
-Run from the feature worktree:
-
-```bash
-git add src/Http/Requests/SkirMethodRequestScope.php tests/Feature/SkirMethodRequestScopeTest.php
-git commit -m "Scope Laravel requests to decoded Skir payloads"
-```
-
----
-
-### Task 3: Introduce prepared procedures and Laravel controller dispatch
-
-**Files:**
-- Create: `src/Contracts/PreparesProcedure.php`
-- Create: `src/PreparedProcedure.php`
-- Create: `src/Routing/PreparedControllerParameters.php`
-- Create: `src/Routing/SkirControllerDispatcher.php`
-- Modify: `src/RegisteredProcedure.php`
-- Modify: `src/Routing/ControllerProcedureInvoker.php`
-- Modify: `src/Routing/SkirControllerRouteDefinition.php`
-- Modify: `src/Routing/SkirMethodRouteDefinition.php`
-- Create: `tests/Feature/LaravelControllerDispatchTest.php`
-
-- [ ] **Step 1: Write failing native-dispatch tests**
-
-Create controller fixtures that prove:
-
-```php
-#[Middleware(RecordControllerMiddleware::class)]
-final class NativeDispatchController extends Controller
-{
- #[SkirMethod(NativeDispatchMethod::Update)]
- #[Middleware(RecordMethodMiddleware::class)]
- public function update(
- NativePayload $request,
- SkirContext $context,
- NativeDependency $dependency,
- ): NativePayload {
- return new NativePayload("{$request->name}:{$dependency->value}");
- }
-}
-```
-
-Assert class middleware runs before method middleware, the dependency comes from the container, the decoded DTO and context are injected once, and the result is encoded normally. Add a controller extending Laravel's base controller that overrides `callAction()` and assert the override is called.
-
-Add `HasMiddleware` and contextual parameter-attribute fixtures in the same test file. Use Laravel's native `#[Config('app.name')]` or a small test contextual attribute and assert it resolves through the controller dispatcher.
-
-- [ ] **Step 2: Run the focused test and verify failure**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/LaravelControllerDispatchTest.php'
-```
-
-Expected: FAIL because procedures do not expose controller middleware and method dependencies receive the decoded DTO payload.
-
-- [ ] **Step 3: Add the prepared-procedure contract**
-
-Create the contract:
-
-```php
-interface PreparesProcedure
-{
- public function prepare(mixed $request, SkirContext $context): PreparedProcedure;
-}
-```
-
-Create `PreparedProcedure` with a `list` middleware property, a private invocation closure created with `Closure::fromCallable()`, and an `invoke(): mixed` method.
-
-Modify `RegisteredProcedure` so it retains both:
-
-```php
-private Closure $handler;
-private ?PreparesProcedure $preparer;
-```
-
-Its `prepare()` method delegates to the preparer when available and otherwise returns an empty-middleware `PreparedProcedure` wrapping the existing manual handler. Keep `invoke()` for compatibility tests until every internal caller uses `prepare()`.
-
-- [ ] **Step 4: Add prepared controller parameters**
-
-`PreparedControllerParameters` must hold an ordered list of values plus object IDs that represent nullable Form Requests which must become `null` immediately before action invocation:
-
-```php
-final readonly class PreparedControllerParameters
-{
- /**
- * @param list $values
- * @param list $nullObjectIds
- */
- public function __construct(
- public array $values,
- private array $nullObjectIds = [],
- ) {}
-
- /** @param list $values */
- public function restoreNulls(array $values): array
- {
- return array_map(
- fn (mixed $value): mixed => is_object($value)
- && in_array(spl_object_id($value), $this->nullObjectIds, true)
- ? null
- : $value,
- $values,
- );
- }
-}
-```
-
-- [ ] **Step 5: Extend Laravel's controller dispatcher at the parameter seam**
-
-Create `SkirControllerDispatcher extends Illuminate\Routing\ControllerDispatcher`. Its `dispatch()` must follow Laravel 13's implementation but scope validation and authorization translation to dependency resolution:
-
-```php
-public function dispatch(Route $route, $controller, $method): mixed
-{
- try {
- $parameters = $this->resolveParameters($route, $controller, $method);
- } catch (ValidationException $exception) {
- throw SkirServerException::validationFailed($exception->errors());
- } catch (AuthorizationException) {
- throw SkirServerException::authorizationFailed();
- }
-
- $prepared = $route->getAction('skirParameters');
-
- if ($prepared instanceof PreparedControllerParameters) {
- $parameters = $prepared->restoreNulls($parameters);
- }
-
- if (method_exists($controller, 'callAction')) {
- return $controller->callAction($method, $parameters);
- }
-
- return $controller->{$method}(...array_values($parameters));
-}
-```
-
-Override `resolveParameters()` to pass `PreparedControllerParameters::$values` through inherited `resolveClassMethodDependencies()`. Fall back to `parent::resolveParameters()` only when no Skir prepared parameters exist.
-
-- [ ] **Step 6: Refactor controller invocation into preparation**
-
-Make `ControllerProcedureInvoker` implement `PreparesProcedure`. For each request it must:
-
-1. Clone the outer route and replace its action with `ControllerClass@method`.
-2. Resolve one controller instance from that action route.
-3. Build reflected parameters in method order:
- - decoded generated DTO through `SkirPayloadHydrator`;
- - `SkirContext` / `RequestContext`;
- - matching bound outer-route parameters;
- - nullable Form Request authorization marker from the existing resolver;
- - leave ordinary Form Requests and services absent for Laravel.
-4. Store `PreparedControllerParameters` in the synthetic route action.
-5. Resolve `$route->controllerMiddleware()` through `Router::resolveMiddleware()`.
-6. Return `PreparedProcedure` whose closure calls `SkirControllerDispatcher::dispatch()` and normalizes the action response.
-
-Do not reflect Laravel's `Middleware` or `Authorize` attributes in Skir code; the synthetic route must delegate discovery to Laravel.
-
-- [ ] **Step 7: Resolve invokers through the container**
-
-Update both route-definition classes to resolve `ControllerProcedureInvoker` with its controller and method arguments through the application container. Register `SkirControllerDispatcher` in `SkirServerServiceProvider` as a transient binding so it receives Laravel's container.
-
-- [ ] **Step 8: Run focused and regression tests**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/LaravelControllerDispatchTest.php tests/Feature/ControllerProcedureInvokerTest.php tests/Feature/SkirRouteConfigurationTest.php'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/pint --dirty --format agent'
-```
-
-Expected: native dispatch and existing controller-registration tests pass.
-
-- [ ] **Step 9: Commit**
-
-```bash
-git add src/Contracts/PreparesProcedure.php src/PreparedProcedure.php src/RegisteredProcedure.php src/Routing src/SkirServerServiceProvider.php tests/Feature/LaravelControllerDispatchTest.php tests/Feature/ControllerProcedureInvokerTest.php
-git commit -m "Dispatch Skir controllers through Laravel"
-```
-
----
-
-### Task 4: Make Form Requests consume decoded bags for all DTO targets
-
-**Files:**
-- Modify: `src/Http/Requests/SkirFormRequest.php`
-- Modify: `src/Http/Requests/SkirFormRequestResolver.php`
-- Modify: `src/Hydration/SkirPayloadHydrator.php`
-- Modify: `tests/Feature/SkirFormRequestTest.php`
-- Modify: `tests/Feature/NullableControllerRequestTest.php`
-
-- [ ] **Step 1: Replace manual-resolution assertions with native lifecycle assertions**
-
-Add an ordinary Laravel Form Request fixture and a `SkirFormRequest` fixture. In `prepareForValidation()`, merge a trimmed name and record:
-
-```php
-self::$seenInput = $this->all();
-self::$seenRoute = $this->route('tenant');
-self::$seenUser = $this->user()?->getAuthIdentifier();
-self::$seenTrace = $this->header('X-Skir-Trace');
-```
-
-Assert the initial input contains only the decoded method object, never `method`, the outer `request` wrapper, or transport query keys. Assert rules, `after()`, authorization, route/user/session/header access, and prepared input all run through Laravel.
-
-- [ ] **Step 2: Add the three DTO hydration cases**
-
-Use lightweight fixtures exposing the real generator contracts:
-
-```php
-final readonly class SimpleDataObjectFixture
-{
- public static function makeFromSkirPayload(array $payload): self;
-}
-
-final readonly class LaravelDataFixture
-{
- public static function makeFromSkirPayload(array $payload): self;
-}
-
-final readonly class StandardPhpFixture
-{
- public static function fromArray(array $payload): self;
-}
-```
-
-Give each fixture a static counter/factory label and assert `SkirFormRequest::skir()` selects the intended factory once, after Form Request preparation and validation.
-
-- [ ] **Step 3: Run tests and verify the current resolver path fails**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/SkirFormRequestTest.php tests/Feature/NullableControllerRequestTest.php'
-```
-
-Expected before refactoring: the ordinary Form Request test fails because the current invoker rejects it, and the container-binding assertion fails because the transport request is still bound.
-
-- [ ] **Step 4: Reduce the custom resolver to Skir-only nullable behavior**
-
-For non-null object payloads, let Laravel's `ControllerDispatcher` resolve Form Requests from `app('request')`. Keep `SkirFormRequestResolver` only for the nullable-null compatibility path that must run preparation and authorization before supplying `null` to the action.
-
-Change `authorizeNull()` to return the prepared Form Request object so `PreparedControllerParameters` can use its object ID as a temporary dependency marker. Do not call `rules()` or `validateResolved()` for this null path.
-
-Keep exception translation scoped as follows:
-
-- dependency-resolution `ValidationException` -> `skir_validation_failed`;
-- dependency-resolution `AuthorizationException` -> `skir_authorization_failed`;
-- the same exception types thrown inside controller business logic -> Laravel's normal exception handler.
-
-- [ ] **Step 5: Verify DTO and nullable behavior**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/SkirFormRequestTest.php tests/Feature/NullableControllerRequestTest.php tests/Feature/ControllerProcedureInvokerTest.php'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/pint --dirty --format agent'
-```
-
-Expected: all focused tests pass, including preservation of null controller arguments and all three generator factories.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add src/Http/Requests src/Hydration tests/Feature/SkirFormRequestTest.php tests/Feature/NullableControllerRequestTest.php tests/Feature/ControllerProcedureInvokerTest.php
-git commit -m "Resolve Skir Form Requests from decoded input"
-```
-
----
-
-### Task 5: Run procedure middleware around encoded Skir responses
-
-**Files:**
-- Modify: `src/Http/Controllers/SkirRpcController.php`
-- Modify: `tests/Feature/LaravelControllerDispatchTest.php`
-- Modify: `tests/Feature/SkirRpcControllerTest.php`
-- Modify: `tests/Feature/StudioRendererTest.php`
-
-- [ ] **Step 1: Add failing method-level middleware tests**
-
-Add two methods to one controller:
-
-```php
-#[SkirMethod(AccountMethod::Login)]
-public function login(LoginRequest $request): LoginResponse;
-
-#[SkirMethod(AccountMethod::GetMe)]
-#[Middleware('test-auth')]
-public function getMe(SkirContext $context): UserResponse;
-```
-
-Register `test-auth` as a test middleware alias. Assert Login succeeds anonymously, GetMe short-circuits with HTTP 401, and an authenticated GetMe succeeds.
-
-Add middleware that appends `X-Skir-Middleware: applied` after `$next($request)`. Assert the header is present and the middleware receives a Symfony `Response`, not a DTO.
-
-Add `#[Authorize('view-account')]` with a test gate and assert denial and success. Add a Studio GET assertion proving Studio remains visible while protected procedure calls still require middleware.
-
-- [ ] **Step 2: Run focused tests and verify failure**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/LaravelControllerDispatchTest.php tests/Feature/SkirRpcControllerTest.php'
-```
-
-Expected: FAIL because `SkirRpcController` still invokes procedures before running their prepared middleware.
-
-- [ ] **Step 3: Move execution into request scope and Laravel Pipeline**
-
-Inject `Container` and `SkirMethodRequestScope` into `SkirRpcController`. After transport decoding, execute:
-
-```php
-return $this->requestScope->run(
- $request,
- $decodedRequest,
- function (Request $methodRequest, mixed $decodedRequest) use ($codec, $procedure): Response {
- $context = new RequestContext($methodRequest, $procedure->descriptor);
- $prepared = $procedure->prepare($decodedRequest, $context);
-
- return (new Pipeline($this->container))
- ->send($methodRequest)
- ->through($prepared->middleware)
- ->then(fn (): Response => $this->encodeResponse(
- $codec,
- $procedure,
- $prepared->invoke(),
- ));
- },
-);
-```
-
-Extract `encodeResponse()` from the current inline encoding logic. Keep Studio detection and transport decoding outside the method request scope. Leave manual procedures with an empty middleware list.
-
-- [ ] **Step 4: Verify response and Studio behavior**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/LaravelControllerDispatchTest.php tests/Feature/SkirRpcControllerTest.php tests/Feature/StudioRendererTest.php tests/Feature/SkirRpcValidationTest.php'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/pint --dirty --format agent'
-```
-
-Expected: public/protected method tests, response header, authorization, short-circuit response, Studio, and existing validation tests pass.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add src/Http/Controllers/SkirRpcController.php tests/Feature/LaravelControllerDispatchTest.php tests/Feature/SkirRpcControllerTest.php tests/Feature/StudioRendererTest.php
-git commit -m "Run Laravel middleware around Skir procedures"
-```
-
----
-
-### Task 6: Close compatibility and edge-case coverage
-
-**Files:**
-- Modify: `tests/Feature/LaravelControllerDispatchTest.php`
-- Modify: `tests/Feature/SkirFormRequestTest.php`
-- Modify: `tests/Feature/NullableControllerRequestTest.php`
-- Modify: `tests/Feature/SkirRouteConfigurationTest.php`
-
-- [ ] **Step 1: Add missing controller compatibility cases**
-
-Add focused tests for:
-
-- repeatable `#[Middleware]` attributes;
-- class `only` / `except` filters based on the selected PHP method;
-- legacy Laravel base-controller middleware;
-- `HasMiddleware` static declarations;
-- invokable `Skir::method()` controllers;
-- bound route model or enum parameters copied from the outer route;
-- context-only and no-payload procedures;
-- ambiguous multiple direct Skir request parameters producing a package-local exception;
-- middleware not running for manual/generated providers;
-- container request restoration after middleware, validation, hydration, action, and codec exceptions.
-
-- [ ] **Step 2: Run tests and implement only the missing behavior**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/LaravelControllerDispatchTest.php tests/Feature/SkirFormRequestTest.php tests/Feature/NullableControllerRequestTest.php tests/Feature/SkirRouteConfigurationTest.php'
-```
-
-Expected: new tests initially fail at the exact unsupported behavior. Limit production changes to `SkirMethodRequestScope`, `PreparedControllerParameters`, `SkirControllerDispatcher`, or `ControllerProcedureInvoker`, according to which assertion failed; do not add another dispatcher or middleware parser.
-
-- [ ] **Step 3: Format and rerun the focused set**
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/pint --dirty --format agent'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit tests/Feature/LaravelControllerDispatchTest.php tests/Feature/SkirFormRequestTest.php tests/Feature/NullableControllerRequestTest.php tests/Feature/SkirRouteConfigurationTest.php'
-```
-
-Expected: PASS.
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add src tests/Feature
-git commit -m "Cover Laravel controller dispatch edge cases"
-```
-
----
-
-### Task 7: Document scaffolding, DTO targets, middleware, and limitations
-
-**Files:**
-- Modify: `README.md`
-- Create: `docs/scaffolding.md`
-- Modify: `docs/generated-procedures.md`
-- Modify: `docs/routing.md`
-
-- [ ] **Step 1: Preserve a concise README**
-
-Add feature bullets for Laravel-native controller middleware and Form Requests. Link to `docs/scaffolding.md`, `docs/generated-procedures.md`, and `docs/routing.md`. Keep detailed command options and dispatch internals out of the README.
-
-- [ ] **Step 2: Move complete scaffolding instructions into a focused guide**
-
-Document these exact public command shapes in `docs/scaffolding.md`:
-
-```bash
-php artisan skir:make
-php artisan skir:make --all
-php artisan skir:make --module=Account --style=module --with-requests
-php artisan skir:make --method=Account.UpdateMe --style=invokable
-php artisan skir:make --generate --all
-php artisan skir:make-request Account.UpdateMe
-```
-
-Explain generated-owned manifests, application-owned additive controllers/Form Requests, and the requirement to regenerate before scaffolding when schemas change.
-
-- [ ] **Step 3: Document the three DTO paths**
-
-In `docs/generated-procedures.md`, show that:
-
-- Simple Data Objects and Laravel Data use `makeFromSkirPayload()`;
-- standard PHP uses `fromArray()`;
-- `SkirFormRequest::skir()` chooses the correct factory after Laravel validation;
-- direct DTO injection remains available but standard PHP direct hydration does not add semantic validation.
-
-- [ ] **Step 4: Document native controller behavior**
-
-In `docs/routing.md`, include:
-
-```php
-use Illuminate\Routing\Attributes\Controllers\Middleware;
-
-final class AccountController
-{
- #[SkirMethod(AccountSkirMethod::Login)]
- public function login(LoginFormRequest $request): LoginResponseData
- {
- // Public method.
- }
-
- #[SkirMethod(AccountSkirMethod::GetMe)]
- #[Middleware('auth:sanctum')]
- public function getMe(SkirContext $context): UserData
- {
- // Protected method on the same endpoint.
- }
-}
-```
-
-Explain decoded input bags, ordinary and typed Form Requests, `#[Authorize]`, `HasMiddleware`, Studio remaining endpoint-visible, and the explicit terminable-controller-middleware limitation.
-
-- [ ] **Step 5: Verify documentation and commit**
-
-Run:
-
-```bash
-git -C packages/server/.worktrees/laravel-scaffolding diff --check
-rg -n "docs/(scaffolding|generated-procedures|routing)\.md" packages/server/.worktrees/laravel-scaffolding/README.md
-```
-
-Expected: no whitespace errors and every linked guide exists.
-
-Commit from the feature worktree:
-
-```bash
-git add README.md docs/scaffolding.md docs/generated-procedures.md docs/routing.md
-git commit -m "Document Laravel-native Skir controllers"
-```
-
----
-
-### Task 8: Verify, integrate, publish, and confirm the server release
-
-**Files:**
-- Verify: all server package files
-- Modify: only the dispatch, request-scope, tests, or documentation files already named in Tasks 2-7 when their corresponding verification fails
-
-- [ ] **Step 1: Run package formatting and complete verification**
-
-Run from the Trackr root:
-
-```bash
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/pint --dirty --format agent'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && composer validate --strict'
-docker compose run --rm --no-deps app sh -lc 'cd packages/server/.worktrees/laravel-scaffolding && vendor/bin/phpunit'
-git -C packages/server/.worktrees/laravel-scaffolding diff --check
-git -C packages/server/.worktrees/laravel-scaffolding status --short --branch
-```
-
-Expected: Composer is valid, the full merged suite passes, diff checks pass, and the feature worktree is clean.
-
-- [ ] **Step 2: Review the complete feature diff**
-
-Run:
-
-```bash
-git -C packages/server diff --stat main...feature/laravel-scaffolding
-git -C packages/server log --oneline --decorate main..feature/laravel-scaffolding
-```
-
-Confirm the diff contains the previously approved scaffolding work, controller dispatch integration, tests, and docs—without unrelated root-project files.
-
-- [ ] **Step 3: Merge the verified feature branch into local main**
-
-Run from `packages/server`:
-
-```bash
-git merge --no-ff feature/laravel-scaffolding -m "Merge Laravel-native controller dispatch"
-```
-
-Expected: clean merge. Rerun the full Docker PHPUnit command on `packages/server` after the merge.
-
-- [ ] **Step 4: Push main and verify GitHub Actions**
-
-Run:
-
-```bash
-git push origin main
-gh run list --repo php-skir/server --branch main --limit 5
-```
-
-Wait for the new Tests workflow and both PHP 8.4/8.5 jobs to pass. If a workflow fails, inspect it with:
-
-```bash
-gh run view --repo php-skir/server --log-failed "$(gh run list --repo php-skir/server --branch main --limit 20 --json databaseId,conclusion --jq 'map(select(.conclusion == "failure"))[0].databaseId')"
-```
-
-- [ ] **Step 5: Create and publish the patch release**
-
-Verify that `v0.1.3` does not already exist:
-
-```bash
-gh release view v0.1.3 --repo php-skir/server
-```
-
-Expected before release: not found. Then run:
-
-```bash
-git tag -a v0.1.3 -m "v0.1.3"
-git push origin v0.1.3
-gh release create v0.1.3 --repo php-skir/server --verify-tag --generate-notes --title v0.1.3
-```
-
-- [ ] **Step 6: Verify the public release and registry**
-
-Run:
-
-```bash
-gh release view v0.1.3 --repo php-skir/server --json tagName,isDraft,isPrerelease,publishedAt,url
-```
-
-Expected: tag `v0.1.3`, not draft, not prerelease.
-
-Run the fresh Packagist consumer check:
-
-```bash
-docker compose run --rm --no-deps app sh -lc '
-skir_consumer_dir="$(mktemp -d /tmp/php-skir-server-v013.XXXXXX)"
-COMPOSER_HOME="${skir_consumer_dir}/composer-home" composer --working-dir="${skir_consumer_dir}" init --no-interaction --name=php-skir/release-check
-COMPOSER_HOME="${skir_consumer_dir}/composer-home" composer --working-dir="${skir_consumer_dir}" require php-skir/server:^0.1.3 --no-interaction --no-progress
-COMPOSER_HOME="${skir_consumer_dir}/composer-home" composer --working-dir="${skir_consumer_dir}" show php-skir/server
-'
-```
-
-Expected: `versions : * v0.1.3` and no path repository in the generated consumer `composer.json`. If Packagist has not refreshed yet, wait and rerun the same block rather than changing package metadata.
-
-- [ ] **Step 7: Record the handoff state**
-
-Run:
-
-```bash
-git -C packages/server status --short --branch
-git -C packages/server describe --tags --exact-match
-```
-
-Expected: clean `main`, synchronized with `origin/main`, exactly at `v0.1.3`. The next project phase installs this public release into Trackr and implements Sanctum plus the selected Vue/Shadcn app shell.
diff --git a/docs/superpowers/specs/2026-07-20-laravel-controller-dispatch-design.md b/docs/superpowers/specs/2026-07-20-laravel-controller-dispatch-design.md
deleted file mode 100644
index 2510ddd..0000000
--- a/docs/superpowers/specs/2026-07-20-laravel-controller-dispatch-design.md
+++ /dev/null
@@ -1,200 +0,0 @@
-# Laravel Controller Dispatch Design
-
-Date: 2026-07-20
-
-## Goal
-
-Make attributed Skir controllers participate in Laravel 13's normal controller lifecycle without turning `php-skir/server` into a parallel controller framework.
-
-The package will continue to own SkirRPC decoding, generator-specific DTO hydration, `SkirContext` injection, and Skir response encoding. Laravel will own the request input bags, Form Request lifecycle, controller middleware discovery, middleware resolution and execution, method dependency injection, contextual parameter attributes, and controller action dispatch.
-
-The runtime must support all three PHP generator targets used by the package ecosystem:
-
-- `std-out/simple-data-objects` DTOs generated by `skir-simple-data-objects-generator`.
-- Spatie Laravel Data DTOs generated by `skir-laravel-data-generator`.
-- Standard readonly PHP DTOs generated by `skir-php-generator`.
-
-## Current gap
-
-`ControllerProcedureInvoker` currently resolves the controller through the container and calls its method with `ReflectionMethod::invokeArgs()`. Constructor injection works, but this bypasses Laravel's controller route and dispatcher behavior:
-
-- `#[Middleware]` attributes on controller classes and methods.
-- `#[Authorize]`, which is implemented by Laravel as controller middleware.
-- Static middleware declared through `HasMiddleware`.
-- Middleware registered by controllers extending Laravel's base controller.
-- Method dependency injection and contextual parameter attributes.
-- The controller's `callAction()` method.
-- Bound parameters from the outer Laravel route.
-
-This package must consume those Laravel facilities instead of copying their reflection, filtering, alias resolution, dependency resolution, or action invocation rules.
-
-The local `feature/laravel-scaffolding` branch already implements `SkirFormRequest`, generated DTO hydration, Form Request and controller scaffolding commands, manifest handling, and extensive feature coverage. That branch was verified but never merged into the released server package. This feature will integrate the complete scaffolding branch into current `main`, preserve its public scaffolding behavior, and replace its manually orchestrated controller invocation with the Laravel-native lifecycle described here.
-
-## Architecture
-
-The package will compose Laravel's router, route metadata, and middleware pipeline, and add a thin `SkirControllerDispatcher` subclass of Laravel's `ControllerDispatcher`. The subclass is limited to the parameter-resolution seam required to seed decoded Skir values, preserve nullable Form Request arguments, and translate validation or authorization failures raised while Laravel resolves dependencies. It continues to use Laravel's own dependency resolver and `callAction()` convention instead of maintaining a parallel reflection dispatcher.
-
-This controlled Laravel 13 extension is preferable to copying controller middleware discovery or dependency resolution. Focused compatibility tests will fail if a Laravel 13 minor release changes the inherited dispatcher contract.
-
-The dispatch lifecycle will be:
-
-1. `SkirRpcController` decodes the RPC envelope and selects the registered procedure.
-2. The package creates a method-scoped Laravel request whose input bags contain only the decoded Skir method payload.
-3. The method-scoped request is bound as Laravel's current request for the controller lifecycle.
-4. A controller-backed procedure exposes the middleware Laravel associates with its controller class and selected method.
-5. The package resolves that middleware through Laravel's router and runs it through Laravel's pipeline using the method-scoped request.
-6. The pipeline destination creates `SkirContext`, hydrates direct generated DTO parameters, and seeds those values plus matching bound route parameters into controller-action metadata.
-7. Laravel's `ControllerDispatcher` resolves Form Requests and other remaining action dependencies from the method-scoped request, then invokes the action through `callAction()` when the controller provides it.
-8. The package normalizes and encodes the action result into the endpoint's HTTP response.
-9. Controller middleware unwinds around the encoded response, allowing middleware to add headers or otherwise inspect the real HTTP response.
-10. The original container request binding is restored in a `finally` block.
-
-Middleware runs before Form Request validation and generated DTO hydration. Authentication and authorization can therefore reject a request before protected method input is validated or hydrated.
-
-## Method-scoped Laravel request
-
-The method-scoped request will be created from the original transport request so it retains:
-
-- Headers, including bearer tokens and content negotiation.
-- User, route, and session resolvers.
-- Bound route parameters and route attributes.
-- Cookies and server metadata.
-- The original raw request content for transport-level diagnostics.
-
-Before the method-scoped request enters middleware, the package will clear its query, request, file, and JSON input bags. For a decoded object payload, the package will replace the active Laravel input source with that decoded associative array. A nullable null request uses empty input bags while retaining the null Skir value for action parameter resolution. Scalar and enum payloads remain available for direct Skir parameter injection but cannot be represented as Form Request input.
-
-The method-scoped request becomes the container's `request` binding for middleware and controller dispatch. This is required because Laravel creates Form Requests from the currently bound request and executes their normal preparation, authorization, validation, and after-validation hooks while resolving controller dependencies.
-
-`SkirContext::request` and the compatibility `RequestContext::request` will reference the method-scoped request. Their normal Laravel input APIs therefore expose the decoded payload, while `getContent()` retains the original transport bytes.
-
-The original transport request must not be mutated. The container binding must always be restored, including when middleware, validation, authorization, hydration, controller code, or encoding throws. This prevents decoded payload state leaking across procedures or requests in long-running Laravel runtimes.
-
-## Controller action metadata
-
-For every controller-backed Skir procedure, the package will create Laravel route metadata whose action is the actual application controller and method. The metadata is not registered as another public route; it exists only to delegate controller behavior to Laravel.
-
-Laravel's controller middleware discovery will provide:
-
-- Repeatable `#[Middleware]` attributes on classes and methods.
-- `only` and `except` filtering based on the selected PHP method name.
-- `#[Authorize]` because it extends Laravel's middleware attribute.
-- Static `HasMiddleware` declarations.
-- Middleware registered through Laravel's base controller.
-
-The router will resolve aliases, middleware groups, and middleware parameters. The package will not parse strings such as `auth:sanctum` itself.
-
-Studio requests are handled before a Skir procedure is selected, so controller middleware will not protect or hide Studio. Applications continue to control Studio through its existing endpoint configuration and route-level middleware. Calls made from Studio to a protected procedure still run that procedure's controller middleware.
-
-## Action parameters
-
-The Skir adapter will build the initial action parameters in reflected method order:
-
-1. A parameter typed as `SkirContext` or the compatibility `RequestContext` receives the current Skir context.
-2. A parameter whose name matches a bound parameter on the outer Laravel route receives that bound value, including an implicitly bound model or enum.
-3. A Laravel Form Request remains unresolved so Laravel can create and validate it from the method-scoped request.
-4. A generated request object exposing `makeFromSkirPayload()`, `fromArray()`, or `fromSkirValue()` receives the decoded and hydrated method payload.
-5. The first remaining built-in parameter receives a scalar, enum, or array Skir payload directly.
-6. Other parameters remain unresolved so Laravel's `ControllerDispatcher` can inject them from the container or through contextual parameter attributes.
-
-A controller action may have at most one Skir request parameter. Multiple generated request candidates or multiple unbound built-in candidates produce a descriptive package-local exception instead of assigning the payload ambiguously. Generated request hydration remains package-owned because Laravel cannot infer generated Skir DTOs from its route parameters. Existing request hydration precedence remains `makeFromSkirPayload()`, then `fromArray()`, then `fromSkirValue()`.
-
-The dispatcher will continue to support methods that accept only `SkirContext`, methods that omit context, and invokable controller registrations.
-
-## Middleware and response behavior
-
-Controller middleware must wrap an encoded Symfony response, not the raw generated response object. This preserves normal behavior for middleware that short-circuits the action, changes response headers, or expects the downstream result to be an HTTP response.
-
-The rules are:
-
-- When the action completes, Skir encodes its declared response type before middleware unwinds.
-- When middleware returns a `Response` without calling the action, that response is returned unchanged.
-- Authentication, authorization, and other middleware exceptions continue through Laravel's normal exception handler.
-- Existing package-local decoding, method lookup, hydration, and codec failures retain their current Skir error responses.
-- Manual handlers and generated procedure providers have no controller middleware metadata and preserve their existing behavior.
-
-## Deliberate boundaries
-
-### Form Requests and generated DTOs
-
-Form Request support is a hard runtime requirement, not an optional scaffolding feature. Any Laravel Form Request resolved for a Skir action must see the decoded method object in `input()`, `all()`, validation data, and preparation hooks. It must not see the outer `{ method, request }` RPC envelope or unrelated transport query parameters.
-
-`SkirFormRequest` remains the package-provided typed convenience base. Its `skir()` method hydrates the configured generated DTO from the complete prepared request payload after Laravel authorization and validation succeed:
-
-- Simple Data Objects use `makeFromSkirPayload()` and retain their generated structural and validation rules.
-- Spatie Laravel Data uses `makeFromSkirPayload()` and retains its generated Laravel Data hydration and validation behavior.
-- Standard PHP DTOs use `fromArray()` after the Form Request supplies application validation and prepared input.
-
-Ordinary application Form Requests that do not extend `SkirFormRequest` are also supported. They receive the decoded input through Laravel normally; the controller may use their prepared or validated arrays directly. Direct generated DTO injection remains available when an application does not need a Form Request for that method.
-
-For a nullable null Skir request with a nullable Form Request parameter, Laravel still runs request preparation and authorization against empty input. Validation and generated DTO hydration are skipped before the controller receives `null`. A non-nullable Form Request rejects a null or non-object Skir payload with a descriptive package-local invalid-request error.
-
-### Terminable middleware
-
-Controller middleware selected inside the Skir route does not participate in Laravel HTTP kernel's post-response termination phase. The package will support the middleware `handle()` pipeline but will not invoke `terminate()` early or reproduce the kernel lifecycle internally.
-
-This limitation will be documented. Route-level terminable middleware continues to work normally because it remains part of the outer Laravel route.
-
-### Skir contract ownership
-
-Laravel response preparation, resource controller routing, and model binding from arbitrary RPC payload fields remain outside this feature. Skir's declared response type and codec remain authoritative. URL parameters already bound by the outer route may be injected, but RPC fields are not treated as Laravel route parameters.
-
-## Compatibility
-
-The public `Skir::controller()` and `Skir::method()` APIs will not change. Existing controllers using only generated DTOs and `SkirContext` will keep the same signatures and wire behavior.
-
-The internal registered-procedure contract will gain optional controller middleware metadata. Callables, manual procedures, and generated providers will default to an empty middleware list. Controller-backed procedures will provide middleware and delegate action invocation to Laravel.
-
-The complete `feature/laravel-scaffolding` history will be integrated on top of current `main` before this dispatcher is implemented. Existing scaffolding commands, manifests, generated `SkirFormRequest` classes, validation error shapes, nullable-request behavior, and additive file-generation guarantees are compatibility requirements. The old `SkirFormRequestResolver` may be removed or reduced once Laravel resolves Form Requests from the method-scoped request; its public behavior and tests must remain intact.
-
-This is a runtime feature for Laravel 13 and will use Laravel 13's native controller middleware attribute APIs. It does not introduce a Skir-specific middleware attribute.
-
-## Documentation
-
-The package README will mention Laravel-native controller middleware in the feature list and quick-start controller example. `docs/routing.md` will document:
-
-- Class- and method-level `#[Middleware]` usage.
-- `#[Authorize]`, `HasMiddleware`, and middleware aliases.
-- Public and protected methods on the same Skir endpoint.
-- Studio behavior for protected procedures.
-- The decoded-request input lifecycle for Form Requests.
-- Direct and Form Request-backed use of Simple Data Objects, Laravel Data, and standard PHP DTOs.
-- The terminable-middleware boundary.
-
-## Testing
-
-Focused tests will prove:
-
-- Method-level aliased authentication middleware can protect one Skir method while another method on the same endpoint remains public, without adding Sanctum as a server-package dependency.
-- Class-level and method-level middleware are merged in Laravel's order.
-- Repeatable attributes and `only` or `except` filters select the expected methods.
-- `#[Authorize]` executes through Laravel's authorization middleware.
-- `HasMiddleware` and middleware declared through Laravel's base controller execute.
-- Constructor injection continues to work.
-- Method dependencies and contextual parameter attributes are resolved by Laravel.
-- `callAction()` is used when available.
-- Bound outer-route parameters are passed to matching action parameters.
-- Middleware, preparation hooks, Form Request authorization, Form Request validation, and controller dependencies all see the decoded payload rather than the outer RPC envelope.
-- Query, JSON, request, and file bags cannot leak outer transport values into Form Request validation.
-- Headers, authentication, sessions, route bindings, and raw transport content remain available on the method-scoped request.
-- The original request binding is restored after successful and exceptional dispatch.
-- Authentication runs before generated DTO hydration.
-- Ordinary Laravel Form Requests resolve and validate normally.
-- `SkirFormRequest::skir()` hydrates Simple Data Objects, Spatie Laravel Data, and standard PHP DTOs through their correct factories.
-- Nullable Form Requests authorize empty input while preserving null action semantics.
-- Middleware can add headers to an encoded Skir response.
-- Middleware can return a short-circuit response without invoking the controller.
-- Direct DTO hydration, context-only actions, invokable controllers, manual handlers, generated providers, codecs, and Studio retain their existing behavior.
-
-The full package test suite, formatter, Composer validation, and whitespace checks must pass before release.
-
-## Release sequence
-
-After implementation is approved and verified:
-
-1. Integrate the complete `feature/laravel-scaffolding` branch onto current `main` while preserving the configuration and release-hardening commits added since it diverged.
-2. Refactor its request resolution and controller invocation onto the method-scoped request, Laravel middleware pipeline, and native controller dispatcher.
-3. Update package documentation and version-facing release metadata if required by the existing release workflow.
-4. Commit the implementation without mixing unrelated package changes.
-5. Push the server package and publish a patch release through its existing GitHub-native release process.
-6. Verify the GitHub release and Packagist version.
-7. Install that public release into Trackr before implementing the Sanctum and Vue integration.
diff --git a/docs/superpowers/specs/2026-07-20-server-configuration-design.md b/docs/superpowers/specs/2026-07-20-server-configuration-design.md
deleted file mode 100644
index 1556697..0000000
--- a/docs/superpowers/specs/2026-07-20-server-configuration-design.md
+++ /dev/null
@@ -1,88 +0,0 @@
-# Server Package Configuration Design
-
-Date: 2026-07-20
-
-## Goal
-
-Add a publishable Laravel configuration file for package-wide Skir server defaults. The configuration controls whether Studio is enabled by default, which query-string key opens Studio, and which codec routes use by default. Existing route-level overrides remain authoritative.
-
-## Public configuration
-
-The package adds `config/skir-server.php`:
-
-```php
- env('SKIR_SERVER_STUDIO_ENABLED', false),
- 'studio_query_key' => env('SKIR_SERVER_STUDIO_QUERY_KEY', 'studio'),
- 'codec' => DenseJsonCodec::class,
-];
-```
-
-The codec setting is a class name rather than a short driver name. Laravel resolves it through the service container, allowing applications to select a built-in codec or provide their own `SkirCodec` implementation without extending a package-maintained alias list. The codec is configured in PHP rather than through an environment variable because fully qualified PHP class names are application code, not deployment-specific scalar values.
-
-The service provider merges the package defaults under the `skir-server` key and publishes the file to the consuming application's `config/skir-server.php` using the `skir-server-config` tag.
-
-## Runtime behavior and precedence
-
-`Route::skirRpc()` applies the configured Studio settings to every route it creates:
-
-- `studio_enabled` defaults to `false`. When `true`, a route serves Studio without requiring `->studio()`.
-- `studio_query_key` defaults to `studio`. Studio is requested by the presence of that query parameter; its value is irrelevant.
-- `->studio()` explicitly enables Studio for one route.
-- `->studio(false)` explicitly disables Studio for one route, including when the package-wide default is enabled.
-
-The configured codec class is resolved through Laravel's container and bound as the default `SkirCodec`. It therefore applies both to the application-wide `SkirServer` and to isolated route servers created for route-specific providers. Passing a codec as the third argument to `Route::skirRpc()` remains the highest-precedence codec selection for that endpoint.
-
-The precedence order is:
-
-1. Explicit route codec or `studio()` call.
-2. Published application configuration.
-3. Package defaults.
-
-Changing `studio_query_key` is package-wide; this change does not introduce a route-level query-key override.
-
-## Validation and errors
-
-The configured codec must be a resolvable class implementing `SkirCodec`. An invalid configured value produces a descriptive package-local `SkirServerException` when Laravel resolves the default codec. Existing codec-specific failures, including a missing optional CBOR dependency, retain their existing exception behavior.
-
-Studio remains disabled by default. Documentation will state that applications enabling Studio should protect the endpoint using their normal Laravel route middleware and authorization strategy. Changing the query key is not an access-control mechanism.
-
-## Documentation
-
-The README remains a concise quick start. Its installation section will add the config publishing command:
-
-```bash
-php artisan vendor:publish --tag=skir-server-config
-```
-
-It will include a compact configuration example and summarize the route-level precedence rules.
-
-Detailed behavior remains in the existing focused guides:
-
-- `docs/routing.md` documents the global Studio default, configurable query key, per-route enable/disable behavior, and production access warning.
-- `docs/codecs.md` documents the class-based default codec, built-in codec classes, container resolution, and per-route override.
-
-## Testing
-
-Feature and unit coverage will prove:
-
-- Package defaults are merged when the config has not been published.
-- The config file is publishable under the `skir-server-config` tag.
-- Studio remains disabled by default.
-- `studio_enabled = true` enables Studio on routes without `->studio()`.
-- `->studio(false)` overrides the enabled package default.
-- A custom `studio_query_key` opens Studio and the old key no longer does.
-- The configured codec class becomes the default for application-wide and isolated route servers.
-- An explicit route codec overrides the configured codec.
-- Invalid codec configuration produces a package-local exception.
-- Existing route, Studio, validation, and codec tests continue to pass.
-
-## Non-goals
-
-This change does not add global URI, prefix, domain, middleware, provider, or route-name settings. Laravel's route declarations already express those concerns directly. It also does not add an `allow_get_requests` option because GET currently supports both RPC query requests and Studio; changing that coupling requires a separate behavioral design.
diff --git a/resources/boost/skills/skir-server-development/references/procedures-and-routing.md b/resources/boost/skills/skir-server-development/references/procedures-and-routing.md
index 24efde4..019c5da 100644
--- a/resources/boost/skills/skir-server-development/references/procedures-and-routing.md
+++ b/resources/boost/skills/skir-server-development/references/procedures-and-routing.md
@@ -12,6 +12,10 @@ Attributed controllers are the primary Laravel workflow:
```php
final class AccountController
{
+ public function __construct(
+ private readonly AccountActions $accounts,
+ ) {}
+
#[SkirMethod(AccountSkirMethod::GetMe)]
#[Middleware('auth:sanctum')]
#[Authorize('view-account')]
@@ -32,8 +36,12 @@ Route::skirRpc('/api/skir', [
```
Laravel's controller dispatcher resolves route parameters, contextual attributes, generated DTOs,
-Form Requests, `SkirContext`, and container dependencies. `RequestContext` remains a compatibility
-type; new code should use `SkirContext`.
+Form Requests, `SkirContext`, and container dependencies.
+
+Register endpoints in `routes/api.php` (`php artisan install:api` on Laravel 13); a POST endpoint in
+`routes/web.php` gets HTTP 419 unless excluded from CSRF verification. Pass class strings,
+`Skir::controller()`, or `Skir::method()` to `Route::skirRpc()`: provider instances do not survive
+`php artisan route:cache`.
## Middleware and authorization boundaries
@@ -55,7 +63,9 @@ Both ordinary Form Requests and `SkirFormRequest` use Laravel input preparation,
`rules()`, and after-validation hooks. A generated `SkirFormRequest` starts with `authorize()` false
and empty `rules()`; review both before registration. Call `$request->skir()` for its typed payload.
-- Validation failure: HTTP 422, `skir_validation_failed`, field details under `error.details`.
+- Validation failure (Form Request, or validating DTO hydration): HTTP 422, `skir_validation_failed`,
+ field details under `error.details`.
+- Payload that cannot be passed to the request parameter: HTTP 422, `skir_invalid_request`.
- Form Request authorization failure: HTTP 403, `skir_authorization_failed`.
- Controller business exceptions: Laravel's normal exception handling.
diff --git a/resources/boost/skills/skir-server-development/references/structures-and-validation.md b/resources/boost/skills/skir-server-development/references/structures-and-validation.md
index eb2231c..c67360e 100644
--- a/resources/boost/skills/skir-server-development/references/structures-and-validation.md
+++ b/resources/boost/skills/skir-server-development/references/structures-and-validation.md
@@ -70,7 +70,8 @@ selectors fail generation. Standard PHP configuration must omit `config.validati
The server hydrator prefers `makeFromSkirPayload()`, then `fromArray()`, then `fromSkirValue()`. Do
not add competing factories to generated classes or edit their factory implementation.
-Direct DTO hydration and validation never perform authorization. Use Laravel middleware,
+Validation failures during direct DTO hydration return HTTP 422 `skir_validation_failed` with field
+details, like Form Request validation. Direct DTO hydration and validation never perform authorization. Use Laravel middleware,
`#[Authorize]`, or a Form Request for that separate boundary.
## Standard PHP objects
diff --git a/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md b/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md
index aa2dd7f..d7cc9b8 100644
--- a/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md
+++ b/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md
@@ -30,7 +30,8 @@ Use PHPUnit feature tests at the Laravel boundary and never call a real external
paths applicable to the change:
- valid decoded request, exact encoded response, and persisted/application side effects;
-- validation HTTP 422 with `skir_validation_failed` and field details;
+- validation HTTP 422 with `skir_validation_failed` and field details, from Form Requests and from
+ validating DTO hydration;
- authorization HTTP 403 with `skir_authorization_failed`;
- unauthenticated and unauthorized method calls;
- protected and intentionally public Studio behavior;
diff --git a/src/Commands/MakeSkirCommand.php b/src/Commands/MakeSkirCommand.php
index 4790fe7..03137fd 100644
--- a/src/Commands/MakeSkirCommand.php
+++ b/src/Commands/MakeSkirCommand.php
@@ -347,13 +347,11 @@ private function configuredStyle(): ControllerStyle
$option = $this->option('style');
$controller = $this->option('controller');
- if (is_string($option) && $option !== '') {
- $style = $option;
- } elseif (is_string($controller)) {
- $style = ControllerStyle::Single->value;
- } else {
- $style = config('skir-server.scaffolding.controller_style');
- }
+ $style = match (true) {
+ is_string($option) && $option !== '' => $option,
+ is_string($controller) => ControllerStyle::Single->value,
+ default => config('skir-server.scaffolding.controller_style'),
+ };
if (! is_string($style)) {
throw new InvalidArgumentException('Skir scaffolding configuration [controller_style] must be a supported string.');
diff --git a/src/Exceptions/SkirScaffoldingException.php b/src/Exceptions/SkirScaffoldingException.php
index 5f93ea7..da32f27 100644
--- a/src/Exceptions/SkirScaffoldingException.php
+++ b/src/Exceptions/SkirScaffoldingException.php
@@ -158,17 +158,6 @@ public static function invalidSingleController(string $controller): self
return new self("Single Skir controller [{$controller}] must be a canonical class under the application namespace.");
}
- public static function cleanupFailedAfterControllerPublication(
- string $destinationPath,
- string $temporaryPath,
- Throwable $exception,
- ): self {
- return new self(
- "Skir controller [{$destinationPath}] was created, but temporary file cleanup failed; remove leftover [{$temporaryPath}] manually: {$exception->getMessage()}",
- previous: $exception,
- );
- }
-
public static function plannedOutputCollision(string $firstPath, string $secondPath): self
{
return new self(
diff --git a/src/Exceptions/SkirServerException.php b/src/Exceptions/SkirServerException.php
index 09468b3..74f8c92 100644
--- a/src/Exceptions/SkirServerException.php
+++ b/src/Exceptions/SkirServerException.php
@@ -49,13 +49,7 @@ public static function invalidResponse(string $method, string $message): self
public static function invalidRouteProvider(mixed $provider): self
{
- if (is_string($provider)) {
- $providerType = $provider;
- } elseif (is_object($provider)) {
- $providerType = $provider::class;
- } else {
- $providerType = get_debug_type($provider);
- }
+ $providerType = is_string($provider) ? $provider : get_debug_type($provider);
return new self(
"Skir route provider [{$providerType}] must implement [Skir\\Server\\Routing\\SkirRouteDefinition] or [Skir\\Server\\ProcedureProvider].",
@@ -75,7 +69,7 @@ public static function authorizationFailed(): self
return new self('This action is unauthorized.', 'skir_authorization_failed', 403);
}
- public function toResponse(): JsonResponse
+ public function render(Request $request): JsonResponse
{
$error = [
'code' => $this->errorCode,
@@ -90,9 +84,4 @@ public function toResponse(): JsonResponse
'error' => $error,
], $this->status);
}
-
- public function render(Request $request): JsonResponse
- {
- return $this->toResponse();
- }
}
diff --git a/src/Http/Controllers/SkirRpcController.php b/src/Http/Controllers/SkirRpcController.php
index c1bb2f8..ae5d215 100644
--- a/src/Http/Controllers/SkirRpcController.php
+++ b/src/Http/Controllers/SkirRpcController.php
@@ -17,15 +17,15 @@
use Skir\Server\Http\RpcRequest;
use Skir\Server\PreparedProcedure;
use Skir\Server\RegisteredProcedure;
-use Skir\Server\RequestContext;
-use Skir\Server\SkirServer;
+use Skir\Server\Routing\SkirEndpointRegistry;
+use Skir\Server\SkirContext;
use Skir\Server\Studio\StudioRenderer;
use Symfony\Component\HttpFoundation\Response;
final readonly class SkirRpcController
{
public function __construct(
- private SkirServer $server,
+ private SkirEndpointRegistry $endpoints,
private StudioRenderer $studioRenderer,
private Container $container,
private SkirMethodRequestScope $requestScope,
@@ -35,7 +35,7 @@ public function __construct(
public function __invoke(Request $request): Response
{
try {
- $server = $this->serverFromRequest($request);
+ $server = $this->endpoints->server($request->route());
if ($this->isStudioRequest($request)) {
if (! $this->studioEnabled($request)) {
@@ -56,7 +56,7 @@ public function __invoke(Request $request): Response
$request,
$decodedRequest,
function (Request $methodRequest, mixed $decodedPayload) use ($rpcRequest, $procedure): Response {
- $context = new RequestContext($methodRequest, $procedure->descriptor);
+ $context = new SkirContext($methodRequest, $procedure->descriptor);
$prepared = $procedure->prepare($decodedPayload, $context);
$response = (new Pipeline($this->container))
@@ -72,9 +72,9 @@ function (Request $methodRequest, mixed $decodedPayload) use ($rpcRequest, $proc
},
);
} catch (SkirServerException $exception) {
- return $exception->toResponse();
+ return $exception->render($request);
} catch (SkirRuntimeException $exception) {
- return SkirServerException::invalidRequest($exception->getMessage())->toResponse();
+ return SkirServerException::invalidRequest($exception->getMessage())->render($request);
}
}
@@ -109,17 +109,6 @@ private function procedureMiddleware(PreparedProcedure $prepared): array
return $prepared->middleware;
}
- private function serverFromRequest(Request $request): SkirServer
- {
- $server = $request->route()?->defaults['skirServer'] ?? null;
-
- if ($server instanceof SkirServer) {
- return $server;
- }
-
- return $this->server;
- }
-
private function isStudioRequest(Request $request): bool
{
if (! $this->usesQueryString($request)) {
diff --git a/src/ProcedureRegistry.php b/src/ProcedureRegistry.php
index f0e4a22..5b09bff 100644
--- a/src/ProcedureRegistry.php
+++ b/src/ProcedureRegistry.php
@@ -5,6 +5,7 @@
namespace Skir\Server;
use Skir\Runtime\MethodDescriptor;
+use Skir\Server\Contracts\PreparesProcedure;
use Skir\Server\Exceptions\SkirServerException;
final class ProcedureRegistry
@@ -12,7 +13,7 @@ final class ProcedureRegistry
/** @var array */
private array $procedures = [];
- public function add(MethodDescriptor $descriptor, callable $handler): void
+ public function add(MethodDescriptor $descriptor, callable|PreparesProcedure $handler): void
{
if (array_key_exists($descriptor->number, $this->procedures)) {
throw SkirServerException::duplicateMethod($descriptor->name, $descriptor->number);
diff --git a/src/RegisteredProcedure.php b/src/RegisteredProcedure.php
index 1a4d392..e767d71 100644
--- a/src/RegisteredProcedure.php
+++ b/src/RegisteredProcedure.php
@@ -10,22 +10,21 @@
final readonly class RegisteredProcedure
{
- private Closure $handler;
-
- private ?PreparesProcedure $preparer;
+ private Closure|PreparesProcedure $handler;
public function __construct(
public MethodDescriptor $descriptor,
- callable $handler,
+ callable|PreparesProcedure $handler,
) {
- $this->preparer = $handler instanceof PreparesProcedure ? $handler : null;
- $this->handler = Closure::fromCallable($handler);
+ $this->handler = $handler instanceof PreparesProcedure
+ ? $handler
+ : Closure::fromCallable($handler);
}
public function prepare(mixed $request, SkirContext $context): PreparedProcedure
{
- if ($this->preparer instanceof PreparesProcedure) {
- return $this->preparer->prepare($request, $context);
+ if ($this->handler instanceof PreparesProcedure) {
+ return $this->handler->prepare($request, $context);
}
return new PreparedProcedure(
@@ -33,9 +32,4 @@ public function prepare(mixed $request, SkirContext $context): PreparedProcedure
fn (): mixed => ($this->handler)($request, $context),
);
}
-
- public function invoke(mixed $request, SkirContext $context): mixed
- {
- return ($this->handler)($request, $context);
- }
}
diff --git a/src/RequestContext.php b/src/RequestContext.php
deleted file mode 100644
index ce4d073..0000000
--- a/src/RequestContext.php
+++ /dev/null
@@ -1,7 +0,0 @@
-prepare($request, $context)->invoke();
- }
-
public function prepare(mixed $request, SkirContext $context): PreparedProcedure
{
$route = $this->controllerRoute($context);
@@ -136,7 +133,7 @@ private function prepareParameters(
$typeName = $type instanceof ReflectionNamedType ? $type->getName() : null;
$isBuiltin = $type instanceof ReflectionNamedType && $type->isBuiltin();
- if ($typeName === SkirContext::class || $typeName === RequestContext::class) {
+ if ($typeName === SkirContext::class) {
$values[] = $context;
continue;
@@ -166,7 +163,7 @@ private function prepareParameters(
}
if (! is_array($request)) {
- throw new InvalidArgumentException('Skir Form Requests require a decoded array/object payload.');
+ throw SkirServerException::invalidRequest('Skir Form Requests require a decoded array/object payload.');
}
continue;
@@ -180,7 +177,7 @@ private function prepareParameters(
}
if (! is_array($request)) {
- throw new InvalidArgumentException('Laravel Form Requests require a decoded array/object payload.');
+ throw SkirServerException::invalidRequest('Laravel Form Requests require a decoded array/object payload.');
}
continue;
@@ -205,7 +202,7 @@ private function prepareParameters(
if ($typeName !== null && $this->payloadHydrator->supports($typeName)) {
/** @var class-string $typeName */
- $values[] = $this->payloadHydrator->hydrate($typeName, $request);
+ $values[] = $this->hydratePayload($typeName, $request);
continue;
}
@@ -218,6 +215,18 @@ private function prepareParameters(
return new PreparedControllerParameters($values, $nullParameterIndexes);
}
+ /** @param class-string $typeName */
+ private function hydratePayload(string $typeName, mixed $request): object
+ {
+ try {
+ return $this->payloadHydrator->hydrate($typeName, $request);
+ } catch (ValidationException $exception) {
+ throw SkirServerException::validationFailed($exception->errors());
+ } catch (TypeError) {
+ throw SkirServerException::invalidRequest('The request payload does not match the expected request type.');
+ }
+ }
+
private function isDirectRequestParameter(
ReflectionParameter $parameter,
mixed $outerRoute,
@@ -229,7 +238,7 @@ private function isDirectRequestParameter(
$type = $parameter->getType();
$typeName = $type instanceof ReflectionNamedType ? $type->getName() : null;
- if ($typeName === SkirContext::class || $typeName === RequestContext::class) {
+ if ($typeName === SkirContext::class) {
return false;
}
diff --git a/src/Routing/SkirControllerRouteDefinition.php b/src/Routing/SkirControllerRouteDefinition.php
index e146428..005ff59 100644
--- a/src/Routing/SkirControllerRouteDefinition.php
+++ b/src/Routing/SkirControllerRouteDefinition.php
@@ -15,9 +15,15 @@
* @param class-string $controller
*/
public function __construct(
- private string $controller,
+ public string $controller,
) {}
+ /** @param array{controller: class-string} $properties */
+ public static function __set_state(array $properties): self
+ {
+ return new self($properties['controller']);
+ }
+
public function register(SkirServer $server): void
{
$reflection = new ReflectionClass($this->controller);
diff --git a/src/Routing/SkirEndpointRegistry.php b/src/Routing/SkirEndpointRegistry.php
new file mode 100644
index 0000000..0a2348d
--- /dev/null
+++ b/src/Routing/SkirEndpointRegistry.php
@@ -0,0 +1,128 @@
+ */
+ private array $servers = [];
+
+ public function __construct(
+ private readonly Container $container,
+ ) {}
+
+ /** @param list $providers */
+ public function register(Route $route, array $providers): void
+ {
+ $server = $this->build($providers);
+ $cacheable = $this->isCacheable($providers);
+ $endpoint = $cacheable
+ ? hash('xxh128', serialize($providers))
+ : spl_object_hash($server);
+
+ $this->servers[$endpoint] = $server;
+ $route->defaults('skirEndpoint', $endpoint);
+
+ if ($cacheable) {
+ $route->defaults('skirProviders', $providers);
+ }
+ }
+
+ public function server(Route $route): SkirServer
+ {
+ $endpoint = $route->defaults['skirEndpoint'] ?? null;
+
+ if (! is_string($endpoint)) {
+ return $this->container->make(SkirServer::class);
+ }
+
+ if (array_key_exists($endpoint, $this->servers)) {
+ return $this->servers[$endpoint];
+ }
+
+ $providers = $route->defaults['skirProviders'] ?? null;
+
+ if (! is_array($providers)) {
+ throw new LogicException(
+ "Skir endpoint [{$route->uri()}] registers provider instances, which cannot be restored from the route cache. "
+ .'Register class-string providers or Skir::controller() / Skir::method() definitions, or run `php artisan route:clear`.',
+ );
+ }
+
+ return $this->servers[$endpoint] = $this->build($providers);
+ }
+
+ /** @param list $providers */
+ private function build(array $providers): SkirServer
+ {
+ $server = new SkirServer(new ProcedureRegistry);
+
+ foreach ($providers as $provider) {
+ $this->resolveProvider($provider)->register($server);
+ }
+
+ return $server;
+ }
+
+ private function resolveProvider(mixed $provider): ProcedureProvider|SkirRouteDefinition
+ {
+ if (is_string($provider)) {
+ $provider = $this->resolveProviderClass($provider);
+ }
+
+ if ($provider instanceof ProcedureProvider) {
+ return $provider;
+ }
+
+ if ($provider instanceof SkirRouteDefinition) {
+ return $provider;
+ }
+
+ throw SkirServerException::invalidRouteProvider($provider);
+ }
+
+ private function resolveProviderClass(string $provider): mixed
+ {
+ $isResolvable = $this->container->bound($provider)
+ || class_exists($provider)
+ || interface_exists($provider);
+
+ if (! $isResolvable) {
+ throw SkirServerException::invalidRouteProvider($provider);
+ }
+
+ return $this->container->make($provider);
+ }
+
+ /** @param list $providers */
+ private function isCacheable(array $providers): bool
+ {
+ return array_all($providers, static function (mixed $provider): bool {
+ if (is_string($provider)) {
+ return true;
+ }
+
+ if ($provider instanceof SkirControllerRouteDefinition) {
+ return true;
+ }
+
+ if ($provider instanceof SkirMethodRouteDefinition) {
+ return $provider->method instanceof UnitEnum;
+ }
+
+ return false;
+ });
+ }
+}
diff --git a/src/Routing/SkirMethodRouteDefinition.php b/src/Routing/SkirMethodRouteDefinition.php
index db68306..cbbea80 100644
--- a/src/Routing/SkirMethodRouteDefinition.php
+++ b/src/Routing/SkirMethodRouteDefinition.php
@@ -13,10 +13,16 @@
* @param class-string $controller
*/
public function __construct(
- private SkirMethodReference $method,
- private string $controller,
+ public SkirMethodReference $method,
+ public string $controller,
) {}
+ /** @param array{method: SkirMethodReference, controller: class-string} $properties */
+ public static function __set_state(array $properties): self
+ {
+ return new self($properties['method'], $properties['controller']);
+ }
+
public function register(SkirServer $server): void
{
$descriptor = $this->method->descriptor();
diff --git a/src/Scaffolding/ControllerScaffolder.php b/src/Scaffolding/ControllerScaffolder.php
index 9aa7948..9fdb0fd 100644
--- a/src/Scaffolding/ControllerScaffolder.php
+++ b/src/Scaffolding/ControllerScaffolder.php
@@ -399,8 +399,7 @@ private function renderController(
);
}
- $stubName = $invokable ? 'skir-invokable-controller.stub' : 'skir-controller.stub';
- $source = $this->renderStub($stubName, [
+ $source = $this->renderStub('skir-controller.stub', [
'{{ namespace }}' => $namespace,
'{{ imports }}' => $imports->source(),
'{{ className }}' => $className,
@@ -417,9 +416,8 @@ private function renderController(
throw SkirScaffoldingException::controllerChangedDuringScaffolding($destinationPath);
}
- $originalSource = $originalSnapshot->contents;
$edited = $this->controllerEditor->edit(
- $originalSource,
+ $originalSnapshot->contents,
$destinationPath,
$namespace,
$className,
@@ -430,12 +428,9 @@ private function renderController(
return new RenderedController(
new RenderedFile($destinationPath, $edited->source),
- $className,
- $methods,
$registrations,
true,
$edited->changed,
- $originalSource,
$edited->warnings,
$originalSnapshot,
);
@@ -443,8 +438,6 @@ private function renderController(
return new RenderedController(
new RenderedFile($destinationPath, $source),
- $className,
- $methods,
$registrations,
);
}
diff --git a/src/Scaffolding/ControllerScaffoldingResult.php b/src/Scaffolding/ControllerScaffoldingResult.php
index 64c8293..78f035d 100644
--- a/src/Scaffolding/ControllerScaffoldingResult.php
+++ b/src/Scaffolding/ControllerScaffoldingResult.php
@@ -6,9 +6,6 @@
final readonly class ControllerScaffoldingResult
{
- /** @var list */
- public array $routeHints;
-
/**
* @param list $createdPaths
* @param list $unchangedPaths
@@ -22,10 +19,5 @@ public function __construct(
public array $registrations,
public array $updatedPaths = [],
public array $warnings = [],
- ) {
- $this->routeHints = array_map(
- static fn (RouteRegistration $registration): string => $registration->snippet(),
- $registrations,
- );
- }
+ ) {}
}
diff --git a/src/Scaffolding/PhpControllerEditor.php b/src/Scaffolding/PhpControllerEditor.php
index 7318578..f949b99 100644
--- a/src/Scaffolding/PhpControllerEditor.php
+++ b/src/Scaffolding/PhpControllerEditor.php
@@ -4,6 +4,7 @@
namespace Skir\Server\Scaffolding;
+use LogicException;
use PhpParser\Node;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Name;
@@ -14,6 +15,7 @@
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter\Standard;
+use RuntimeException;
use Skir\Server\Attributes\SkirMethod;
use Skir\Server\Exceptions\SkirScaffoldingException;
use Skir\Server\Scaffolding\Manifest\SkirMethodDefinition;
@@ -47,7 +49,7 @@ public function edit(
throw SkirScaffoldingException::invalidExistingController($path, $exception);
}
- $parser = (new ParserFactory)->createForNewestSupportedVersion();
+ $parser = (new ParserFactory)->createForHostVersion();
try {
$originalStatements = $parser->parse($source);
@@ -58,7 +60,7 @@ public function edit(
if ($originalStatements === null) {
throw SkirScaffoldingException::invalidExistingController(
$path,
- new \RuntimeException('The parser returned no statements.'),
+ new RuntimeException('The parser returned no statements.'),
);
}
@@ -319,13 +321,13 @@ private function appendImports(Stmt\Namespace_ $namespace, array $newImports): v
private function parseMethod(string $methodSource): Stmt\ClassMethod
{
- $parser = (new ParserFactory)->createForNewestSupportedVersion();
+ $parser = (new ParserFactory)->createForHostVersion();
$statements = $parser->parse("getMethods()[0] ?? null : null;
if (! $method instanceof Stmt\ClassMethod) {
- throw new \LogicException('Rendered Skir controller method could not be parsed.');
+ throw new LogicException('Rendered Skir controller method could not be parsed.');
}
return $method;
diff --git a/src/Scaffolding/RenderedController.php b/src/Scaffolding/RenderedController.php
index ecfa8dc..ca95992 100644
--- a/src/Scaffolding/RenderedController.php
+++ b/src/Scaffolding/RenderedController.php
@@ -4,23 +4,17 @@
namespace Skir\Server\Scaffolding;
-use Skir\Server\Scaffolding\Manifest\SkirMethodDefinition;
-
final readonly class RenderedController
{
/**
- * @param list $methods
* @param list $registrations
* @param list $warnings
*/
public function __construct(
public RenderedFile $file,
- public string $className,
- public array $methods,
public array $registrations,
public bool $existing = false,
public bool $changed = true,
- public ?string $originalSource = null,
public array $warnings = [],
public ?FileSnapshot $originalSnapshot = null,
) {}
diff --git a/src/Scaffolding/RequestNamespaceValidator.php b/src/Scaffolding/RequestNamespaceValidator.php
index fc12f50..4994527 100644
--- a/src/Scaffolding/RequestNamespaceValidator.php
+++ b/src/Scaffolding/RequestNamespaceValidator.php
@@ -19,6 +19,7 @@ public function resolve(): string
throw SkirScaffoldingException::invalidRequestNamespace($configuredNamespace);
}
+ $configuredNamespace = trim($configuredNamespace, '\\');
$namespaceSegments = explode('\\', $configuredNamespace);
if ($configuredNamespace === '' || in_array('', $namespaceSegments, true)) {
diff --git a/src/SkirServer.php b/src/SkirServer.php
index e781d80..71c78d9 100644
--- a/src/SkirServer.php
+++ b/src/SkirServer.php
@@ -5,6 +5,7 @@
namespace Skir\Server;
use Skir\Runtime\MethodDescriptor;
+use Skir\Server\Contracts\PreparesProcedure;
final readonly class SkirServer
{
@@ -12,7 +13,7 @@ public function __construct(
private ProcedureRegistry $procedures,
) {}
- public function addMethod(MethodDescriptor $descriptor, callable $handler): void
+ public function addMethod(MethodDescriptor $descriptor, callable|PreparesProcedure $handler): void
{
$this->procedures->add($descriptor, $handler);
}
diff --git a/src/SkirServerServiceProvider.php b/src/SkirServerServiceProvider.php
index c75d1c0..9e2ec6d 100644
--- a/src/SkirServerServiceProvider.php
+++ b/src/SkirServerServiceProvider.php
@@ -4,19 +4,16 @@
namespace Skir\Server;
-use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Routing\Route as LaravelRoute;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
-use ReflectionClass;
use Skir\Server\Commands\GeneratorRunner;
use Skir\Server\Commands\MakeSkirCommand;
use Skir\Server\Commands\MakeSkirRequestCommand;
use Skir\Server\Commands\SymfonyGeneratorRunner;
-use Skir\Server\Exceptions\SkirServerException;
use Skir\Server\Http\Controllers\SkirRpcController;
use Skir\Server\Routing\SkirControllerDispatcher;
-use Skir\Server\Routing\SkirRouteDefinition;
+use Skir\Server\Routing\SkirEndpointRegistry;
use Skir\Server\Scaffolding\ControllerScaffolder;
use Skir\Server\Scaffolding\ControllerScaffolding;
use Skir\Server\Scaffolding\Manifest\ManifestRepository;
@@ -40,6 +37,7 @@ public function register(): void
$this->app->singleton(ProcedureRegistry::class);
$this->app->singleton(SkirServer::class);
+ $this->app->singleton(SkirEndpointRegistry::class);
$this->app->singleton(ManifestRepository::class);
$this->app->bind(GeneratorRunner::class, SymfonyGeneratorRunner::class);
$this->app->bind(ControllerScaffolding::class, ControllerScaffolder::class);
@@ -67,29 +65,8 @@ public function boot(): void
/** @var Router $router */
$router = $this->app['router'];
$application = $this->app;
- $resolveProvider = static function (mixed $provider) use ($application): mixed {
- if (! is_string($provider)) {
- return $provider;
- }
-
- try {
- return $application->make($provider);
- } catch (BindingResolutionException $exception) {
- if ($application->bound($provider)) {
- throw $exception;
- }
-
- if (class_exists($provider)) {
- if ((new ReflectionClass($provider))->isInstantiable()) {
- throw $exception;
- }
- }
- throw SkirServerException::invalidRouteProvider($provider);
- }
- };
-
- $router->macro('skirRpc', function (string $uri, array $providers = []) use ($resolveProvider) {
+ $router->macro('skirRpc', function (string $uri, array $providers = []) use ($application) {
/** @var Router $this */
$route = $this
->match(['GET', 'POST'], $uri, SkirRpcController::class)
@@ -100,25 +77,9 @@ public function boot(): void
return $route;
}
- $server = new SkirServer(new ProcedureRegistry);
-
- foreach ($providers as $provider) {
- $resolvedProvider = $resolveProvider($provider);
-
- if ($resolvedProvider instanceof SkirRouteDefinition) {
- $resolvedProvider->register($server);
-
- continue;
- }
-
- if (! $resolvedProvider instanceof ProcedureProvider) {
- throw SkirServerException::invalidRouteProvider($resolvedProvider);
- }
-
- $resolvedProvider->register($server);
- }
+ $application->make(SkirEndpointRegistry::class)->register($route, $providers);
- return $route->defaults('skirServer', $server);
+ return $route;
});
}
}
diff --git a/stubs/skir-invokable-controller.stub b/stubs/skir-invokable-controller.stub
deleted file mode 100644
index 2d742d8..0000000
--- a/stubs/skir-invokable-controller.stub
+++ /dev/null
@@ -1,12 +0,0 @@
-temporaryDirectory.'/app');
}
+ public function test_configured_namespace_may_be_written_with_surrounding_backslashes(): void
+ {
+ config()->set('skir-server.scaffolding.request_namespace', '\\App\\Http\\Requests\\Skir\\');
+
+ $this->artisan('skir:make-request', ['method' => 'Admin.Users.GetUser'])
+ ->assertSuccessful();
+
+ self::assertFileExists($this->temporaryDirectory.'/app/Http/Requests/Skir/Admin/Users/GetUserFormRequest.php');
+ }
+
public function test_configured_namespace_outside_the_application_namespace_is_rejected(): void
{
config()->set('skir-server.scaffolding.request_namespace', 'Domain\\Http\\Requests');
diff --git a/tests/Feature/ControllerProcedureInvokerTest.php b/tests/Feature/ControllerProcedureInvokerTest.php
index 24fbc1f..e4d07d6 100644
--- a/tests/Feature/ControllerProcedureInvokerTest.php
+++ b/tests/Feature/ControllerProcedureInvokerTest.php
@@ -13,7 +13,6 @@
use Skir\Server\Attributes\SkirMethod;
use Skir\Server\Contracts\SkirMethodReference;
use Skir\Server\Facades\Skir;
-use Skir\Server\RequestContext;
use Skir\Server\SkirContext;
use Skir\Server\Tests\TestCase;
@@ -48,17 +47,17 @@ public function it_prefers_to_skir_array_for_response_normalization(): void
}
#[Test]
- public function it_injects_request_context_into_attributed_controllers(): void
+ public function it_injects_the_skir_context_into_attributed_controllers(): void
{
- $this->registerController('/request-context');
+ $this->registerController('/injected-context');
$this
- ->postJson('/request-context', [
- 'method' => 'RequestContext',
+ ->postJson('/injected-context', [
+ 'method' => 'InjectedContext',
'request' => 5.0,
])
->assertOk()
- ->assertContent(json_encode(RequestContext::class, JSON_THROW_ON_ERROR));
+ ->assertContent(json_encode(SkirContext::class, JSON_THROW_ON_ERROR));
}
#[Test]
@@ -144,7 +143,7 @@ enum InvocationSkirMethod implements SkirMethodReference
{
case PreferRequestHydrator;
case PreferResponseNormalizer;
- case RequestContext;
+ case InjectedContext;
case Dependency;
case StaticMethod;
case UntypedParameter;
@@ -166,7 +165,7 @@ public function descriptor(): MethodDescriptor
Type::string(),
Type::string(),
),
- self::RequestContext => new MethodDescriptor('RequestContext', 4003, Type::float32(), Type::string()),
+ self::InjectedContext => new MethodDescriptor('InjectedContext', 4003, Type::float32(), Type::string()),
self::Dependency => new MethodDescriptor('Dependency', 4004, Type::float32(), Type::string()),
self::StaticMethod => new MethodDescriptor('StaticMethod', 4005, Type::float32(), Type::float32()),
self::UntypedParameter => new MethodDescriptor('UntypedParameter', 4006, Type::float32(), Type::float32()),
@@ -194,8 +193,8 @@ public function preferResponseNormalizer(string $request): PreferredResponsePayl
return new PreferredResponsePayload($request);
}
- #[SkirMethod(InvocationSkirMethod::RequestContext)]
- public function requestContext(float $request, RequestContext $context): string
+ #[SkirMethod(InvocationSkirMethod::InjectedContext)]
+ public function injectedContext(float $request, SkirContext $context): string
{
return $context::class;
}
diff --git a/tests/Feature/LaravelControllerDispatchTest.php b/tests/Feature/LaravelControllerDispatchTest.php
index bf4947e..b62bb49 100644
--- a/tests/Feature/LaravelControllerDispatchTest.php
+++ b/tests/Feature/LaravelControllerDispatchTest.php
@@ -35,7 +35,7 @@
use Skir\Server\Facades\Skir;
use Skir\Server\Http\Requests\SkirFormRequest;
use Skir\Server\RegisteredProcedure;
-use Skir\Server\RequestContext;
+use Skir\Server\Routing\SkirEndpointRegistry;
use Skir\Server\SkirContext;
use Skir\Server\SkirServer;
use Skir\Server\Tests\TestCase;
@@ -198,10 +198,10 @@ public function bound_enum_parameters_are_copied_from_the_outer_route(): void
}
#[Test]
- public function it_prepares_manual_procedures_without_middleware_and_keeps_invoke_compatibility(): void
+ public function it_prepares_manual_procedures_without_middleware(): void
{
$descriptor = NativeDispatchMethod::HasMiddleware->descriptor();
- $context = new RequestContext(Request::create('/manual-procedure'), $descriptor);
+ $context = new SkirContext(Request::create('/manual-procedure'), $descriptor);
$procedure = new RegisteredProcedure(
$descriptor,
fn (string $request, SkirContext $context): string => "{$request}:{$context->method->name}",
@@ -211,7 +211,6 @@ public function it_prepares_manual_procedures_without_middleware_and_keeps_invok
$this->assertSame([], $prepared->middleware);
$this->assertSame('prepared:HasMiddleware', $prepared->invoke());
- $this->assertSame('compatible:HasMiddleware', $procedure->invoke('compatible', $context));
}
#[Test]
@@ -689,11 +688,7 @@ private function registerController(string $uri, string $controller): LaravelRou
private function serverFromRoute(LaravelRoute $route): SkirServer
{
- $server = $route->defaults['skirServer'] ?? null;
-
- $this->assertInstanceOf(SkirServer::class, $server);
-
- return $server;
+ return app(SkirEndpointRegistry::class)->server($route);
}
/** @param array $parameters */
@@ -701,12 +696,12 @@ private function contextForRoute(
LaravelRoute $route,
NativeDispatchMethod $method,
array $parameters = [],
- ): RequestContext {
+ ): SkirContext {
$request = Request::create($route->uri(), 'POST');
$route->parameters = $parameters;
$request->setRouteResolver(fn (): LaravelRoute => $route);
- return new RequestContext($request, $method->descriptor());
+ return new SkirContext($request, $method->descriptor());
}
private function assertTransportRequestStateRestored(string $path): void
diff --git a/tests/Feature/NullableControllerRequestTest.php b/tests/Feature/NullableControllerRequestTest.php
index 2082a3b..b79c21e 100644
--- a/tests/Feature/NullableControllerRequestTest.php
+++ b/tests/Feature/NullableControllerRequestTest.php
@@ -225,6 +225,37 @@ public function null_for_a_nonnullable_string_request_is_rejected(): void
->assertJsonPath('error.code', 'skir_invalid_request');
}
+ #[Test]
+ public function null_for_a_nonnullable_generated_request_parameter_is_rejected(): void
+ {
+ $this->registerRoute(NullableRequestMethod::Standard, NonnullableStandardController::class);
+
+ $this->postNullRequest('/nullable-standard', 'Standard')
+ ->assertUnprocessable()
+ ->assertExactJson([
+ 'error' => [
+ 'code' => 'skir_invalid_request',
+ 'message' => 'The request payload does not match the expected request type.',
+ ],
+ ]);
+ }
+
+ #[Test]
+ public function null_for_a_nonnullable_form_request_parameter_is_rejected(): void
+ {
+ $this->registerRoute(NullableRequestMethod::FormRequest, NonnullableFormRequestController::class);
+
+ $this->withSession([])
+ ->postNullRequest('/nullable-form-request/acme', 'FormRequest')
+ ->assertUnprocessable()
+ ->assertExactJson([
+ 'error' => [
+ 'code' => 'skir_invalid_request',
+ 'message' => 'Skir Form Requests require a decoded array/object payload.',
+ ],
+ ]);
+ }
+
#[Test]
public function context_only_methods_are_not_given_a_null_payload_argument(): void
{
diff --git a/tests/Feature/Scaffolding/ControllerScaffolderTest.php b/tests/Feature/Scaffolding/ControllerScaffolderTest.php
index e7f16a5..787ab12 100644
--- a/tests/Feature/Scaffolding/ControllerScaffolderTest.php
+++ b/tests/Feature/Scaffolding/ControllerScaffolderTest.php
@@ -10,6 +10,7 @@
use Skir\Server\Exceptions\SkirScaffoldingException;
use Skir\Server\Scaffolding\AtomicFilePublisher;
use Skir\Server\Scaffolding\ControllerScaffolder;
+use Skir\Server\Scaffolding\ControllerScaffoldingResult;
use Skir\Server\Scaffolding\ControllerStyle;
use Skir\Server\Scaffolding\FormRequestScaffolder;
use Skir\Server\Scaffolding\Manifest\SkirMethodDefinition;
@@ -151,7 +152,7 @@ enumCase: 'DeleteUser',
], $result->registrations);
self::assertSame([
'\\Skir\\Server\\Facades\\Skir::controller(\\App\\Skir\\Admin\\Users\\UsersController::class)',
- ], $result->routeHints);
+ ], $this->routeHints($result));
self::assertFileExists($path);
$source = file_get_contents($path);
@@ -183,7 +184,7 @@ public function it_creates_one_invokable_controller_and_route_hint_per_method():
self::assertSame([
'\\Skir\\Server\\Facades\\Skir::method(\\App\\Skir\\Methods\\AdminUsersMethod::GetUser, \\App\\Skir\\Admin\\Users\\GetUserController::class)',
'\\Skir\\Server\\Facades\\Skir::method(\\App\\Skir\\Methods\\AdminUsersMethod::DeleteUser, \\App\\Skir\\Admin\\Users\\DeleteUserController::class)',
- ], $result->routeHints);
+ ], $this->routeHints($result));
self::assertSame('App\\Skir\\Admin\\Users\\GetUserController', $result->registrations[0]->controllerClass);
self::assertSame('App\\Skir\\Methods\\AdminUsersMethod', $result->registrations[0]->enumClass);
self::assertSame('GetUser', $result->registrations[0]->enumCase);
@@ -217,7 +218,7 @@ enumCase: 'GetInvoice',
self::assertSame([$path], $result->createdPaths);
self::assertSame([
'\\Skir\\Server\\Facades\\Skir::controller(\\App\\Skir\\SkirController::class)',
- ], $result->routeHints);
+ ], $this->routeHints($result));
self::assertStringContainsString('public function getInvoice(string $request, SkirContext $context): ?int', (string) file_get_contents($path));
unlink($path);
@@ -2142,6 +2143,15 @@ static function (string $operation, string $path) use ($controllerPath, &$staged
self::assertCount(2, glob(dirname($controllerPath).'/.skir-*') ?: []);
}
+ /** @return list */
+ private function routeHints(ControllerScaffoldingResult $result): array
+ {
+ return array_map(
+ static fn (RouteRegistration $registration): string => $registration->snippet(),
+ $result->registrations,
+ );
+ }
+
private function method(
string $module = 'Admin.Users',
string $name = 'GetUser',
diff --git a/tests/Feature/SkirFormRequestTest.php b/tests/Feature/SkirFormRequestTest.php
index 1509ff5..3386c08 100644
--- a/tests/Feature/SkirFormRequestTest.php
+++ b/tests/Feature/SkirFormRequestTest.php
@@ -439,6 +439,58 @@ public function it_keeps_direct_generated_object_injection_available_without_a_f
]);
}
+ #[Test]
+ public function it_returns_direct_payload_validation_failures_as_skir_errors(): void
+ {
+ Route::skirRpc('/validated-direct-payload-rpc', [
+ Skir::method(FormRequestSkirMethod::DirectUser, ValidatedDirectPayloadController::class),
+ ]);
+
+ $this
+ ->postJson('/validated-direct-payload-rpc', [
+ 'method' => 'DirectUser',
+ 'request' => [
+ 'id' => 42,
+ 'name' => '',
+ ],
+ ])
+ ->assertUnprocessable()
+ ->assertExactJson([
+ 'error' => [
+ 'code' => 'skir_validation_failed',
+ 'message' => 'The given data was invalid.',
+ 'details' => [
+ 'name' => ['The name field is required.'],
+ ],
+ ],
+ ]);
+ }
+
+ #[Test]
+ public function it_returns_direct_payload_validation_failures_as_skir_errors_without_a_json_accept_header(): void
+ {
+ Route::skirRpc('/validated-direct-payload-rpc', [
+ Skir::method(FormRequestSkirMethod::DirectUser, ValidatedDirectPayloadController::class),
+ ])->middleware('web');
+
+ $this
+ ->call(
+ 'POST',
+ '/validated-direct-payload-rpc',
+ server: ['CONTENT_TYPE' => 'application/json'],
+ content: json_encode([
+ 'method' => 'DirectUser',
+ 'request' => [
+ 'id' => 42,
+ 'name' => '',
+ ],
+ ], JSON_THROW_ON_ERROR),
+ )
+ ->assertUnprocessable()
+ ->assertJsonPath('error.code', 'skir_validation_failed')
+ ->assertJsonPath('error.details.name', ['The name field is required.']);
+ }
+
#[Test]
public function it_rejects_multiple_direct_skir_request_parameters_before_hydration(): void
{
@@ -1079,6 +1131,14 @@ public function __invoke(FromArrayUserPayload $payload): FromArrayUserPayload
}
}
+final class ValidatedDirectPayloadController
+{
+ public function __invoke(ValidatedUserPayload $payload): FromArrayUserPayload
+ {
+ return new FromArrayUserPayload($payload->id, $payload->name);
+ }
+}
+
#[ControllerMiddlewareAttribute(AmbiguousResolverMutationMiddleware::class)]
final class AmbiguousDirectPayloadController
{
@@ -1177,6 +1237,26 @@ public function toArray(): array
}
}
+final readonly class ValidatedUserPayload
+{
+ public function __construct(
+ public int $id,
+ public string $name,
+ ) {}
+
+ /** @param array{id: int, name: string} $payload */
+ public static function fromArray(array $payload): self
+ {
+ if ($payload['name'] === '') {
+ throw ValidationException::withMessages([
+ 'name' => ['The name field is required.'],
+ ]);
+ }
+
+ return new self($payload['id'], $payload['name']);
+ }
+}
+
enum FormRequestSkirMethod implements SkirMethodReference
{
case RenameUser;
diff --git a/tests/Feature/SkirRouteCachingTest.php b/tests/Feature/SkirRouteCachingTest.php
new file mode 100644
index 0000000..f9ca186
--- /dev/null
+++ b/tests/Feature/SkirRouteCachingTest.php
@@ -0,0 +1,114 @@
+cacheRoutes();
+
+ $this->postJson('/cached-provider', ['method' => 'CachedSquare', 'request' => 5.0])
+ ->assertOk()
+ ->assertContent('25');
+ $this->postJson('/cached-controller', ['method' => 'CachedDouble', 'request' => 5.0])
+ ->assertOk()
+ ->assertContent('10');
+ $this->postJson('/cached-method', ['method' => 'CachedTriple', 'request' => 5.0])
+ ->assertOk()
+ ->assertContent('15');
+ }
+
+ #[Test]
+ public function provider_instances_explain_that_they_cannot_be_restored_from_the_route_cache(): void
+ {
+ Route::skirRpc('/cached-instance', [new CachedRouteProvider]);
+
+ $this->cacheRoutes();
+
+ $this->withoutExceptionHandling();
+ $this->expectException(LogicException::class);
+ $this->expectExceptionMessage('Skir endpoint [cached-instance] registers provider instances, which cannot be restored from the route cache.');
+
+ $this->postJson('/cached-instance', ['method' => 'CachedSquare', 'request' => 5.0]);
+ }
+
+ private function cacheRoutes(): void
+ {
+ /** @var Router $router */
+ $router = $this->app['router'];
+ $routes = $router->getRoutes();
+
+ foreach ($routes as $route) {
+ $route->prepareForSerialization();
+ }
+
+ $compiledRoutes = var_export($routes->compile(), true);
+
+ $this->app->forgetInstance(SkirEndpointRegistry::class);
+ $router->setCompiledRoutes(eval("return {$compiledRoutes};"));
+ }
+}
+
+final class CachedRouteProvider implements ProcedureProvider
+{
+ public function register(SkirServer $server): void
+ {
+ $server->addMethod(
+ new MethodDescriptor('CachedSquare', 7001, Type::float32(), Type::float32()),
+ fn (float $value): float => $value * $value,
+ );
+ }
+}
+
+enum CachedRouteMethod implements SkirMethodReference
+{
+ case Double;
+ case Triple;
+
+ public function descriptor(): MethodDescriptor
+ {
+ return match ($this) {
+ self::Double => new MethodDescriptor('CachedDouble', 7002, Type::float32(), Type::float32()),
+ self::Triple => new MethodDescriptor('CachedTriple', 7003, Type::float32(), Type::float32()),
+ };
+ }
+}
+
+final class CachedRouteController
+{
+ #[SkirMethod(CachedRouteMethod::Double)]
+ public function double(float $value): float
+ {
+ return $value * 2;
+ }
+}
+
+final class CachedRouteInvokableController
+{
+ public function __invoke(float $value): float
+ {
+ return $value * 3;
+ }
+}
diff --git a/tests/Feature/SkirRouteConfigurationTest.php b/tests/Feature/SkirRouteConfigurationTest.php
index c0e9516..b76b0ca 100644
--- a/tests/Feature/SkirRouteConfigurationTest.php
+++ b/tests/Feature/SkirRouteConfigurationTest.php
@@ -17,6 +17,7 @@
use Skir\Runtime\Type;
use Skir\Server\Exceptions\SkirServerException;
use Skir\Server\ProcedureProvider;
+use Skir\Server\Routing\SkirEndpointRegistry;
use Skir\Server\Routing\SkirRouteDefinition;
use Skir\Server\SkirServer;
use Skir\Server\Tests\TestCase;
@@ -188,11 +189,7 @@ public function studio_can_be_explicitly_disabled(): void
private function serverFromRoute(LaravelRoute $route): SkirServer
{
- $server = $route->defaults['skirServer'] ?? null;
-
- $this->assertInstanceOf(SkirServer::class, $server);
-
- return $server;
+ return app(SkirEndpointRegistry::class)->server($route);
}
}
diff --git a/tests/Feature/SkirRpcControllerTest.php b/tests/Feature/SkirRpcControllerTest.php
index 91d3f99..9f4f3f9 100644
--- a/tests/Feature/SkirRpcControllerTest.php
+++ b/tests/Feature/SkirRpcControllerTest.php
@@ -16,7 +16,7 @@
use Skir\Server\Exceptions\SkirServerException;
use Skir\Server\Facades\Skir;
use Skir\Server\ProcedureProvider;
-use Skir\Server\RequestContext;
+use Skir\Server\Routing\SkirEndpointRegistry;
use Skir\Server\SkirContext;
use Skir\Server\SkirServer;
use Skir\Server\Tests\TestCase;
@@ -156,7 +156,7 @@ public function it_decodes_struct_requests_and_encodes_struct_responses(): void
app(SkirServer::class)->addMethod(
new MethodDescriptor('RenameUser', 1002, $userType, $userType),
- fn (array $user, RequestContext $context): array => [
+ fn (array $user, SkirContext $context): array => [
'id' => $user['id'],
'name' => "{$user['name']} from {$context->request->ip()}",
],
@@ -261,13 +261,11 @@ public function it_registers_procedure_providers_on_a_route(): void
$route = Route::skirRpc('/provider-rpc', [
SquareProcedureProvider::class,
]);
- $server = $route->defaults['skirServer'] ?? null;
-
- $this->assertInstanceOf(SkirServer::class, $server);
+ $server = app(SkirEndpointRegistry::class)->server($route);
$prepared = $server->procedure('Square')->prepare(
5.0,
- new RequestContext(Request::create('/provider-rpc', 'POST'), TestSkirMethod::Square->descriptor()),
+ new SkirContext(Request::create('/provider-rpc', 'POST'), TestSkirMethod::Square->descriptor()),
);
$this->assertSame([], $prepared->middleware);
@@ -456,7 +454,7 @@ public function it_injects_the_primary_skir_context(): void
#[Test]
public function it_keeps_request_context_as_a_compatibility_type(): void
{
- $context = new RequestContext(
+ $context = new SkirContext(
request: request(),
method: new MethodDescriptor('Compat', 2002, Type::float32(), Type::float32()),
);
diff --git a/tests/Feature/SkirServerConfigurationTest.php b/tests/Feature/SkirServerConfigurationTest.php
index 062ee69..52f8f36 100644
--- a/tests/Feature/SkirServerConfigurationTest.php
+++ b/tests/Feature/SkirServerConfigurationTest.php
@@ -9,6 +9,7 @@
use Illuminate\Support\ServiceProvider;
use PHPUnit\Framework\Attributes\Test;
use Skir\Server\ProcedureProvider;
+use Skir\Server\Routing\SkirEndpointRegistry;
use Skir\Server\SkirServer;
use Skir\Server\SkirServerServiceProvider;
use Skir\Server\Tests\TestCase;
@@ -129,11 +130,7 @@ public function package_configuration_is_publishable(): void
private function serverFromRoute(LaravelRoute $route): SkirServer
{
- $server = $route->defaults['skirServer'] ?? null;
-
- $this->assertInstanceOf(SkirServer::class, $server);
-
- return $server;
+ return app(SkirEndpointRegistry::class)->server($route);
}
}
diff --git a/tests/Unit/ProcedureRegistryTest.php b/tests/Unit/ProcedureRegistryTest.php
index d0e1255..5b57e57 100644
--- a/tests/Unit/ProcedureRegistryTest.php
+++ b/tests/Unit/ProcedureRegistryTest.php
@@ -70,7 +70,7 @@ public function registered_procedures_receive_the_request_and_context(): void
);
$context = new SkirContext(Request::create('/skir'), $descriptor);
- $result = $registry->get('Describe')->invoke(5.0, $context);
+ $result = $registry->get('Describe')->prepare(5.0, $context)->invoke();
$this->assertSame('Describe:5', $result);
}