diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ad0fc3..076ea71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Consumer conveniences on the `Settings` contract, each a thin delegation onto the existing read + and write paths: `missing()`, `many()` (keys or `key => default` pairs), `setMany()` and + `forgetMany()` (one write each, not atomic), `remember()` (read-through: writes a computed value + once through `set()`), `all(?string $prefix)` (every visible value of the handle's scope, the PHP + form of the REST listing) and `definitions()` (the store's definitions, the PHP form of + `GET stores/{store}/definitions`). `SettingsFake` implements all of them and records the writes. + The facade's docblock now lists every contract method. +- A namespaced `Simtabi\Laranail\Settings\settings()` helper (`use function …\settings;`): the + handle with no argument, else `get($key, $default)`. Deliberately not a global function. +- `Services\Resolution\ScopeKeys`: the key walk a listing uses, shared by `all()` and the REST + listing (moved verbatim out of `Actions\Reads\ReadSettings`). +- Documentation: a complete PHP API reference (every contract method with signature, example, + exceptions and events, plus the facade, the helper, `HasSettings` and typed settings), a per-route + REST API reference with every problem type, an exceptions reference, the six approval events and + a call-to-event table in the events reference, and recipes for an admin UI on the REST API, SPA and + mobile clients, a per-user preferences screen, multi-tenancy, auditing a change, moving settings + between environments and typed settings. Tests fail when a contract method, route, event, + exception, command or config key (and its default) goes undocumented. + - Approvals (design §16.7, Phase 4b): a write (`set`, `forget`, `lock`, `unlock`) to a setting whose definition is `requiresApproval()`, or whose key matches the store's new `approvals.keys` globs, opens a change request instead of writing. A @@ -179,6 +198,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- The package is wired the way Laravel wires an application (conventions review, 2026-11-10). + `routes/api.php` declares every REST route by hand in named, nested groups, each `http.routes` + switch an `if` around its group; the service provider loads it once, under `http.prefix`/v1 and + the `laranail-settings.api.` name prefix. URIs, names, methods and middleware are unchanged (39 + routes). `routes/web.php` is no longer loaded while it holds no routes. +- `http.prefix` reads `LARANAIL_SETTINGS_HTTP_PREFIX` (default still `api/settings`); slashes are + trimmed and an empty prefix mounts the API at `/v1`. Change it when the application already has + routes under `/api/settings`: Laravel keeps the last route registered for a method and URI. +- Most classes are autowired, with their lifetime as `#[Scoped]` / `#[Singleton]` on the class and + their configuration as `#[Config]` on the parameter; the service provider binds only what + configuration chooses or validates (1,180 lines to about 700). Closure collaborators became + injected ones: one `Support\Clock` (Laravel's `Date` seam) for every timestamp, the operational + log for write retries and cache failures, the event dispatcher for skipped layers, and a + `Services\Definitions\Definitions` service for "which definition applies", which replaced a + provider closure and two copies of the same rule. +- `SettingsManager` takes every collaborator, required, and its fluent methods return a copy; the + "built without X" `LogicException`s are gone. `CategoryManager`, `Approvals` and + `PersistedConfigurationEditor` take their actions and are narrowed with `in($store, $actor)`. +- REST controllers take their actions per method, return JSON resources and resource collections + (bodies unchanged), and validate each write with its own form request. +- Each exception names its HTTP status and problem type (`STATUS`, `TYPE`); `Problems` renders them + and reads its titles through the translator. Messages are read through Laravel's translator + (`laranail/settings::settings.*`), `__()` and `trans_choice()` in the commands. +- Typed settings classes listed in `typed.classes` are bound when the application boots; the global + `beforeResolving` hook is gone, so a class not listed resolves unloaded (build it with + `::load()`). +- The REST rate limiter is registered through package-tools' `registerRateLimiter()` and reads + `http.rate_limit` per request. +- Configuration is read with the repository's typed getters, which throw on a value of the wrong + type where the old reader fell back to the default (a digit string for a number is now an error). + - A write to a setting that needs approval opens a change request where the store can hold one; `ApprovalUnavailable` is now raised only where it cannot (no active database layer, or no change requests table). `SetSetting`, `ForgetSetting`, `LockSetting` and `UnlockSetting` return @@ -226,21 +276,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `Contracts\Settings` gains `clearCache()` and `warmCache()`; `Actions\StoreActions` gains the optional `warmCache` and `clearCache` actions. -### Deprecated +### Removed + +- Removed with the owner's approval (2026-11-10), before the first tag: `Http\ApiRoutes`, + `Enums\Capability`, `Http\OpenApi\OpenApiDocument` and the `laranail::settings.openapi` + command; `Http\Middleware\FreshControllers`; the seven action bundles (`SettingActions`, + `StoreActions`, `HistoryActions`, `ApprovalActions`, `TransferActions`, `ConfigurationActions`, + `CategoryActions`); `Http\Requests\BodyRequest`, `Data\Http\BodyInput` and + `Http\Support\ListResponse`; the static `fields()` of the five resources; `Support\Messages` + and `Support\ConfigValues`; and the single-implementation contracts `ReadinessProbe` (with + `Database\SchemaReadinessProbe`), `ValueValidator`, `ValueEncrypter`, `BootstrapEvidence` and + `OwnerResolver`. Inject the action, the concrete class or db-tools' `SchemaReadinessInterface` + instead. -- The old names of the 19 classes moved into `Services\` (listed under Changed): - `Database\AuditRepository`, `Database\CategoryRepository`, `Database\DefinitionsRepository`, - `Database\SchemaInspector`, `Database\SchemaShapeRepository`, `Stores\SettingWriter`, - `Stores\StoreRegistry`, `Resolution\Resolver`, `Resolution\PreloadedRecords`, - `Authorization\AccessGuard`, `Audit\Auditor`, `Configuration\RuntimeConfiguration`, - `Definitions\DefinitionRegistry`, `Definitions\DatabaseDefinitions`, - `Tenancy\TenantDiscriminators`, `Casting\CasterRegistry`, `Support\ValuePipeline`, - `Drivers\DriverFactory` and `Caching\SettingsCache`. Each still resolves to the moved class - through `class_alias` in `src/deprecated-aliases.php` (Composer `autoload.files`), so imports, - type declarations, container bindings and `instanceof` keep working; removed in 1.0. -- `PruneOrphans::find()`: use `FindOrphans::handle()`. It forwards; removed in 1.0. -- `DatabaseDefinitions::localised()`: use `Support\Translations::nullableText()`. It forwards; - removed in 1.0. +- The old names of the 19 classes moved into `Services\` (listed under Changed), the + `src/deprecated-aliases.php` file that aliased them, `PruneOrphans::find()` (use + `FindOrphans::handle()`) and `DatabaseDefinitions::localised()` (use + `Support\Translations::nullableText()`). None was ever in a tagged release. - The four migration stubs are replaced by one migration, `database/migrations/create_laranail_settings_tables.php`, which creates categories, the diff --git a/README.md b/README.md index 9e39b58..b528399 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ use Simtabi\Laranail\Settings\Facades\Settings; Settings::set('site.name', 'Acme'); Settings::get('site.name'); // 'Acme' Settings::get('site.tagline', 'Welcome'); // the default when nothing is stored +Settings::many(['site.name', 'site.tagline' => 'Welcome']); +Settings::all('mail'); // every visible key under mail. ``` ```php @@ -88,12 +90,13 @@ The hosted docs live at [ 'enabled' => env('LARANAIL_SETTINGS_HTTP', false), - 'prefix' => 'api/settings', + 'prefix' => env('LARANAIL_SETTINGS_HTTP_PREFIX', 'api/settings'), 'middleware' => null, 'rate_limit' => 60, 'routes' => [ diff --git a/docs/architecture.md b/docs/architecture.md index e1f2c7c..1ed8a8b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -25,7 +25,7 @@ How `laranail/settings` is shaped, and why. | Services (`Services/`) | the database, the files, a body of rules | `Services\Database\AuditRepository`, `Services\Database\HistoryRepository`, `Services\Database\CategoryRepository`, `Services\Stores\SettingWriter`, `Services\Resolution\Resolver`, `Services\Access\AccessGuard`, `Services\Tenancy\TenantDiscriminators`, `Services\Cache\SettingsCache` | | Contract implementations | one per kind, beside its kind | the drivers, the audit sinks, the authorizers, the casters, the verifiers, the actor resolvers | | Listeners (`Listeners/`) and notifications | react to events | `SendSettingsAlert`, `LogSettingsEvent`, `Notifications\SettingsAlert` | -| Support (`Support/`) | stateless logic shared by several classes | `AuditedTransaction`, `Translations`, `Json`, `DatabaseValues`, `ConfigValues`, `ValueEncoder`, `BagCodec` | +| Support (`Support/`) | stateless logic shared by several classes | `AuditedTransaction`, `Translations`, `Json`, `DatabaseValues`, `ValueEncoder`, `BagCodec`, `Clock` | An action never builds a query or reads the schema itself; it asks a repository, so the table, the tenant filter and the row format live in one place. A change and its audit entry always go @@ -48,11 +48,9 @@ entry points. Two architecture tests keep it so: nothing under `Services\` implements a plug-in contract (a driver, sink, authorizer, caster, verifier, resolver or discriminator stays beside its kind, where a reader looking for "the drivers" finds them), and no class named `*Repository` or `*Registry` -lives anywhere else. The 19 classes that moved keep their old names through `class_alias` in -`src/deprecated-aliases.php`, loaded by Composer, until 1.0. The aliases are declared eagerly: -PHP does not autoload a class for a type check, so a lazily declared alias would make -`function f(Stores\SettingWriter $w)` refuse the object it accepted before. A third test asserts the -alias file names exactly the moved classes. +lives anywhere else. The 19 classes that moved there in 0.1 kept no old name: the package had never +been tagged, so the aliases were removed before the first release, and a third test asserts the old +names no longer resolve. ## Why history and audit are separate tables @@ -224,12 +222,32 @@ The package ships no views, Blade components, Livewire, Filament or assets. A se ## Why the REST API lives in the package -The API is a channel, not a product: every endpoint runs an action the PHP API already runs (`Enums\Capability::actions()`), with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside, keep its own copy of the capability list, and drift a release behind the engine whenever an action changed; the design moved it in (D-26) so one pull request changes a capability in every channel at once, and an architecture test fails when a route, the capability enum or a controller disagrees with the others. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless. +The API is a channel, not a product: every endpoint runs an action the PHP API already runs, with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside and drift a release behind the engine whenever an action changed; the design moved it in (D-26) so one pull request changes a capability in every channel at once. The routes are declared by hand in `routes/api.php`, each controller method takes the action it runs as a parameter, and a test reading the live router fails when a route names no controller method, a controller method is not routed, or one does not delegate to an action. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless. ## Why change requests are a table A write that needs approval has to outlive the request that proposed it: the approver acts later, from another request, maybe another server, and a queue or a cache entry can be evicted before anyone looks. So a proposal is a row, written in the same transaction as its `pending` audit entry, on the store's own connection (one table per connection, like the history), with the proposed value stored exactly as the values table would store it, encrypted for an encrypted definition. Keeping the base version on the row is what makes applying it safe: the approval writes through the version-checked update, so a setting that changed in the meantime is never overwritten and the request becomes `stale`. Requests are keyed by ULID, so the table never depends on `ids.type`, and the table is a schema switch (`approvals.table`) like the history. +## How the container builds it + +Most classes are autowired. A class's lifetime is an attribute on the class (`#[Scoped]` for +anything derived from a request, so Octane and queue workers start each request clean; +`#[Singleton]` for stateless helpers), and a configuration value is a `#[Config]` attribute on the +constructor parameter that needs it. The service provider binds only what configuration chooses or +validates: the drivers, sinks, authorizers, verifiers and actor resolvers named in config, the cache +stores, and the stores themselves. A handle (`SettingsManager`) takes every collaborator it calls, +required, and a fluent method returns a copy with a new target, so a handle is never half-built. +Time is read in one place, `Support\Clock`, through Laravel's `Date` seam, so `travelTo()` reaches +every timestamp the package writes. + +A few collaborators stay closures on purpose, each because the alternative is worse: the +`DriverFactory` is a singleton (a driver registered with `extend()` must last) and hands database +drivers the scoped readiness, schema and tenant services through closures; the runtime +configuration's change log and the database audit sink reach the logger, the auditor and the store +registry lazily, because those read the runtime configuration themselves; the encrypter is resolved +only when a value is encrypted, so an application without an `APP_KEY` still boots; and the session +and request are read per call, because they change under a scoped service. + ## Dependencies Built on `laranail/package-tools` (provider, testing guards), `laranail/console` (command base), diff --git a/docs/configuration.md b/docs/configuration.md index 38a7bd7..70bab57 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -81,7 +81,7 @@ Every key in `config/laranail/settings.php`, read at `config('laranail.settings. | `importers` | `spatie`, `toolkit`, `akaunting` | importers `import --from=` can use, name => class | | `typed.classes` | `[]` | typed settings classes whose properties are registered as definitions | | `http.enabled` | `false` (`LARANAIL_SETTINGS_HTTP`) | register the REST API's routes | -| `http.prefix` | `api/settings` | the routes' prefix; they live under `/v1` | +| `http.prefix` | `api/settings` (`LARANAIL_SETTINGS_HTTP_PREFIX`) | the routes' prefix; they live under `/v1`, and an empty prefix mounts them at `/v1`. Change it when the application already has routes under `/api/settings`: Laravel keeps the last route registered for a method and URI and says nothing | | `http.middleware` | `null` | the routes' middleware; null is `['api', 'auth:sanctum']` with Sanctum, else `['api', 'auth']` | | `http.rate_limit` | `60` | requests per minute per user (or IP); `0` for none | | `http.routes.` | `true` | switch a group off: `stores`, `definitions`, `settings`, `history`, `audit`, `approvals`, `categories`, `configuration`, `transfer` | diff --git a/docs/recipes/approving-a-change.md b/docs/recipes/approving-a-change.md index f4cd52a..aa9f086 100644 --- a/docs/recipes/approving-a-change.md +++ b/docs/recipes/approving-a-change.md @@ -29,7 +29,26 @@ settings()->as($reviewer)->approvals()->approve($id, 'agreed with finance'); The editor cannot approve their own request (`approvals.allow_self`). If `billing.plan` changed after the request was opened, approving marks it `stale` instead of overwriting; ask for a new request. Schedule `laranail::settings.prune-changes` daily to expire forgotten requests. -Over HTTP the same steps are `PUT …/settings/billing.plan` (answers `202`), `GET stores/settings/changes?status=pending` and `POST stores/settings/changes/{id}/approve`. +## The same flow over HTTP + +```http +PUT /api/settings/v1/stores/settings/settings/billing.plan +{"value": "pro", "reason": "upgrade for ACME"} +``` + +answers `202 Accepted` with the change request (`"status": "pending"`). A reviewer lists and decides: + +```http +GET /api/settings/v1/stores/settings/changes?status=pending +POST /api/settings/v1/stores/settings/changes/01JC…/approve {"reason": "agreed with finance"} +POST /api/settings/v1/stores/settings/changes/01JC…/reject {"reason": "not this quarter"} +``` + +The requester can follow their own requests with `GET …/changes/{id}` and withdraw one with `POST …/changes/{id}/cancel`. To propose without trying to write, `POST …/changes` with `{"key": "billing.plan", "value": "pro"}`. A decided request answers `409 change-request-closed` to a second decision. + +## Tell the reviewers + +Listen to `ChangeRequested` (identifiers only, never the value) or add an [alert](../tools/alerts.md) rule for it, so reviewers hear of a request without polling. See [Approvals](../tools/approvals.md). diff --git a/docs/recipes/auditing-a-change.md b/docs/recipes/auditing-a-change.md new file mode 100644 index 0000000..87385a3 --- /dev/null +++ b/docs/recipes/auditing-a-change.md @@ -0,0 +1,56 @@ +# Audit a change + +Answer "who changed this setting, when, why, and what was it before" from the audit trail and the value history. + +## Who and when: the audit trail + +```php +$entries = $settings->as($auditor)->audit() + ->key('mail.from.address') + ->since(now()->subMonth()) + ->get(20); + +foreach ($entries as $entry) { + echo "{$entry->occurredAt} {$entry->action->value} {$entry->outcome->value} by {$entry->actorType->value}:{$entry->actorId} via {$entry->channel->value}\n"; +} +``` + +The audit trail records every action, allowed or denied, with the actor, the channel (`php`, `rest`, `console`) and the versions it moved between, but never a value. Denied attempts are there too: filter with `->outcome(AuditOutcome::Denied)`. Needs `view_audit`. + +## What it was: the history + +```php +$versions = $settings->as($auditor)->history()->key('mail.from.address')->get(); +$diff = $settings->as($auditor)->historyDiff('mail.from.address', 3, 4); +``` + +History keeps the value before and after each change, with the reason given through `because()`. An encrypted or sensitive value is shown only to an actor holding `view_sensitive`; others see that it changed, not to what. + +## From the console + +```bash +php artisan laranail::settings.history mail.from.address --diff=3..4 +``` + +## Over HTTP + +```http +GET /api/settings/v1/audit?key=mail.from.address&since=2026-10-01 +GET /api/settings/v1/stores/settings/settings/mail.from.address/history +``` + +## Make every change carry a reason + +```php +$settings->as($request->user())->because($request->input('ticket'))->set('mail.from.address', $address); +``` + +Over HTTP send `"reason"` in the body. A reason costs nothing and is the first thing an auditor asks for. + +## Keep it as long as you need + +`audit.keep_days` and `history.keep_days` (365 by default) decide what `prune-audit` and `prune-history` remove; schedule both. Ship entries elsewhere with an extra audit sink (`audit.sinks`) when the trail must outlive the database. See [Audit and logging](../tools/audit-and-logging.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/building-a-preferences-screen.md b/docs/recipes/building-a-preferences-screen.md new file mode 100644 index 0000000..b4dad69 --- /dev/null +++ b/docs/recipes/building-a-preferences-screen.md @@ -0,0 +1,76 @@ +# Build a per-user preferences screen + +Let each user choose their own theme, language and notification options, falling back to the application's defaults until they do. + +## Define the preferences + +```php +// a store for user preferences, routed by the `user` morph alias +'stores' => [ + 'settings' => [...], + 'preferences' => ['layers' => ['database'], 'owners' => ['user'], 'inherits' => true], +], +``` + +```php +$registry->define('ui.theme')->inStore('preferences')->ofType('string')->rules(['in:light,dark,system'])->withDefault('system')->labelled('Theme')->register(); +$registry->define('ui.locale')->inStore('preferences')->ofType('string')->withDefault('en')->labelled('Language')->register(); +$registry->define('notify.digest')->inStore('preferences')->ofType('boolean')->withDefault(true)->labelled('Weekly digest')->register(); +``` + +The `User` model uses `HasSettings` and implements `Settable`, with `user` in the morph map. + +## Read them into the screen + +```php +public function edit(Request $request, Settings $settings): View +{ + $prefs = $settings->for($request->user())->as($request->user()); + + return view('preferences', [ + 'definitions' => $prefs->definitions(), + 'values' => $prefs->many(['ui.theme', 'ui.locale', 'notify.digest']), + ]); +} +``` + +`many()` returns each value or its definition default, so a new user sees the defaults. + +## Save the form + +```php +public function update(UpdatePreferencesRequest $request, Settings $settings): RedirectResponse +{ + $settings->for($request->user())->as($request->user())->setMany($request->validated()); + + return back()->with('status', 'Preferences saved.'); +} +``` + +Let users change only their own values with a gate that compares the owner: + +```php +Gate::define('laranail-settings.update', fn (User $user, Subject $subject) => + $subject->owner?->alias === 'user' && (string) $subject->owner->id === (string) $user->getKey()); +``` + +## Reset to the default + +```php +$settings->for($user)->as($user)->forgetMany(['ui.theme', 'ui.locale']); +``` + +Forgetting the user's own value lets reads fall back to the default again. + +## Read them on every request without a query each + +```php +User::query()->withSettings()->paginate(); // listing pages: one read per store +$settings->for(auth()->user())->get('ui.theme'); // cached per scope after the first read +``` + +A client-side screen does the same through `GET` and `PUT /stores/preferences/owners/user/{id}/settings/{key}`; see [Read settings from an SPA or a mobile app](consuming-from-an-spa-or-mobile-app.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/building-an-admin-ui-on-the-rest-api.md b/docs/recipes/building-an-admin-ui-on-the-rest-api.md new file mode 100644 index 0000000..5438f83 --- /dev/null +++ b/docs/recipes/building-an-admin-ui-on-the-rest-api.md @@ -0,0 +1,91 @@ +# Build your own admin UI on the REST API + +Render a settings screen from the store's definitions, save each field with optimistic locking, and show who changed what, all over the JSON API. + +## Turn the API on and grant the abilities + +```php +// config/laranail/settings.php +'http' => ['enabled' => true], // routes under /api/settings/v1 +``` + +```php +// AppServiceProvider::boot() +Gate::define('laranail-settings.view', fn (User $user) => $user->is_staff); +Gate::define('laranail-settings.update', fn (User $user) => $user->is_admin); +Gate::define('laranail-settings.view_history', fn (User $user) => $user->is_admin); +Gate::define('laranail-settings.view_audit', fn (User $user) => $user->is_admin); +``` + +## Build the form from definitions + +The definitions carry everything a field needs: type, label, description, category, rules, and whether the value is sensitive. Categories give the sections. + +```js +const api = (path, init = {}) => + fetch(`/api/settings/v1${path}`, { + credentials: 'include', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...init.headers }, + ...init, + }); + +const [categories, definitions, values] = await Promise.all([ + api('/stores/settings/categories').then((r) => r.json()), + api('/stores/settings/definitions?limit=200').then((r) => r.json()), + api('/stores/settings/settings?limit=200').then((r) => r.json()), +]); + +const byKey = Object.fromEntries(values.data.map((s) => [s.key, s])); +const sections = categories.data.map((category) => ({ + title: category.title, + fields: definitions.data + .filter((d) => d.category === category.slug) + .map((d) => ({ ...d, current: byKey[d.key]?.value ?? d.default })), +})); +``` + +Map `type` to an input (`boolean` to a toggle, `integer` to a number field, `email` to an email field), and render `sensitive` fields as write-only: the listing leaves out values the user may not read. Follow `meta.next_cursor` when a store holds more than 200 keys. + +## Save one field at a time, with its ETag + +```js +async function save(key, value, reason) { + const current = await api(`/stores/settings/settings/${key}`); + const response = await api(`/stores/settings/settings/${key}`, { + method: 'PUT', + headers: { 'If-Match': current.headers.get('ETag'), 'Idempotency-Key': crypto.randomUUID() }, + body: JSON.stringify({ value, reason }), + }); + + if (response.status === 202) return { pending: (await response.json()).data }; // needs approval + if (response.ok) return { saved: (await response.json()).data }; + throw await response.json(); // a problem document +} +``` + +Keep the ETag from the read that filled the form, rather than re-reading just before saving, when you want "someone else changed this" warnings: a `412 precondition-failed` then means the field changed since the user saw it. + +## Show errors next to the field + +| Problem `type` ends in | Show | +|---|---| +| `validation`, `invalid-value` | the message under the field (`errors` has per-field messages) | +| `locked` | the field as read-only, with a lock icon | +| `precondition-failed` | "changed by someone else", with a reload button | +| `verification-required` | a password confirmation, then retry the same request | +| `access-denied` | hide the save button for that field | + +## Add history and an activity feed + +```js +const history = await api(`/stores/settings/settings/${key}/history?limit=20`).then((r) => r.json()); +const activity = await api(`/audit?store=settings&since=${weekAgo}`).then((r) => r.json()); +``` + +A "restore this version" button is `POST /stores/settings/settings/{key}/rollback` with `{"version": n}`. + +Every route is in the [REST API reference](../tools/rest-api-reference.md); the same screen can be built server-side with `definitions()` and `all()` from the [Settings API](../tools/settings-api.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/calling-the-rest-api-with-sanctum.md b/docs/recipes/calling-the-rest-api-with-sanctum.md index 35b72b5..739d134 100644 --- a/docs/recipes/calling-the-rest-api-with-sanctum.md +++ b/docs/recipes/calling-the-rest-api-with-sanctum.md @@ -41,7 +41,7 @@ curl -s -X PUT https://app.example/api/settings/v1/stores/settings/settings/site -d '{"value": "Acme Ltd", "reason": "rebrand"}' ``` -`412` means the setting changed since you read its ETag; read it again. `428` means the ability needs step-up verification (`verification.abilities`): use the `actor` verifier and send a fresh `verifiedAt`, or leave such abilities to people. Generate a client from `php artisan laranail::settings.openapi`. +`412` means the setting changed since you read its ETag; read it again. `428` means the ability needs step-up verification (`verification.abilities`): use the `actor` verifier and send a fresh `verifiedAt`, or leave such abilities to people. See [REST API](../tools/rest-api.md). diff --git a/docs/recipes/consuming-from-an-spa-or-mobile-app.md b/docs/recipes/consuming-from-an-spa-or-mobile-app.md new file mode 100644 index 0000000..c98d15c --- /dev/null +++ b/docs/recipes/consuming-from-an-spa-or-mobile-app.md @@ -0,0 +1,59 @@ +# Read settings from an SPA or a mobile app + +Serve a single-page or mobile client the settings it needs: cookie sessions for a first-party SPA, Sanctum tokens for a mobile app, and conditional requests to keep traffic down. + +## A first-party SPA: Sanctum cookies + +```php +// config/laranail/settings.php +'authentication' => ['resolver' => 'sanctum'], +'http' => ['enabled' => true, 'middleware' => ['api', 'auth:sanctum']], +``` + +The SPA calls `/sanctum/csrf-cookie` once, logs in, then sends `credentials: 'include'` and the `X-XSRF-TOKEN` header on writes. Requests act as the logged-in user; the gates decide. + +## A mobile app: a token with a ceiling + +```php +$token = $user->createToken('ios', ['settings:view', 'settings:update'])->plainTextToken; +``` + +```http +GET /api/settings/v1/stores/settings/owners/user/42/settings?limit=200 +Authorization: Bearer 12|kR9… +Accept: application/json +``` + +The token can read and update, never `forget`, `rollback` or `approve`, whatever the gates allow. See [Call the REST API with Sanctum](calling-the-rest-api-with-sanctum.md). + +## Load everything a screen needs in one call + +`GET …/settings` returns every key the user can see, global defaults included through definitions, in pages of up to 200. For a user's own preferences use the owner form; values inherited from the team or the global value come back with `"from"` naming where they came from. + +```kotlin +val page = api.get("stores/settings/owners/user/$userId/settings?limit=200") +val prefs = page.data.associate { it.key to it.value } +``` + +## Cache with ETags + +Each single setting carries an `ETag`. Keep it with the cached value and send it back as `If-Match` when writing, so a stale client cannot overwrite a newer value: it gets `412 precondition-failed` and re-reads. + +## Retry writes safely + +Mobile networks drop responses. Send an `Idempotency-Key` with every write and reuse it on retry: the server answers a replay from cache (`Idempotent-Replayed: true`) for `http.idempotency.ttl` seconds instead of writing twice. + +```swift +var request = URLRequest(url: url.appending(path: "stores/settings/owners/user/\(id)/settings/ui.theme")) +request.httpMethod = "PUT" +request.setValue(pendingWrite.idempotencyKey, forHTTPHeaderField: "Idempotency-Key") +request.httpBody = try JSONEncoder().encode(["value": "dark"]) +``` + +## Handle the answers + +`401` means log in again; `429` means back off (`http.rate_limit` per minute); `202` means the change waits for approval, so show it as pending; anything else is a [problem document](../tools/rest-api-reference.md#problem-types) whose `detail` is safe to show. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/moving-settings-between-environments.md b/docs/recipes/moving-settings-between-environments.md new file mode 100644 index 0000000..493845d --- /dev/null +++ b/docs/recipes/moving-settings-between-environments.md @@ -0,0 +1,52 @@ +# Move settings between environments + +Copy a store from staging to production, or keep environments in step, with export, a dry-run import and a diff. + +## Export from the source + +```bash +php artisan laranail::settings.export storage/settings-staging.json --store=settings +``` + +Encrypted values are left out by default, so the file is safe to commit or attach to a ticket. `--with-secrets` keeps their ciphertext (useful only when both environments share `APP_KEY`), and `--decrypt` writes plaintext after you type the store name. + +## Compare before importing + +```bash +php artisan laranail::settings.diff storage/settings-staging.json --store=settings +``` + +The diff lists keys `added`, `removed`, `changed` and `unchanged`, never values, and exits 1 when the two differ, so it can gate a deploy. + +## Import, dry run first + +```bash +php artisan laranail::settings.import storage/settings-staging.json --store=settings # what would change +php artisan laranail::settings.import storage/settings-staging.json --store=settings --apply # write it +``` + +Each setting goes through the write pipeline: validation, casting, encryption, approvals, history and audit all apply, and the whole import is one transaction. Locks and system categories in the document are ignored unless you pass `--trusted`. + +## From code or over HTTP + +```php +$document = $source->as($admin)->export(); +$report = $target->as($admin)->because('sync from staging')->previewImport($document); +$target->as($admin)->because('sync from staging')->import($document); +``` + +```http +POST /api/settings/v1/stores/settings/export {"mode": "redacted"} +POST /api/settings/v1/stores/settings/diff {"document": {…}} +POST /api/settings/v1/stores/settings/import {"document": {…}, "apply": true} +``` + +## Secrets + +Set secrets in each environment directly (`set()` on an encrypted definition) rather than carrying them in a file. After an `APP_KEY` rotation, run `laranail::settings.reencrypt`. + +See [Import and export](../tools/import-export.md). + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/setting-up-multi-tenancy.md b/docs/recipes/setting-up-multi-tenancy.md new file mode 100644 index 0000000..35fc4e9 --- /dev/null +++ b/docs/recipes/setting-up-multi-tenancy.md @@ -0,0 +1,70 @@ +# Set up multi-tenancy + +Keep each tenant's settings, categories, audit and history apart, in one shared database or in a database per tenant. + +## Choose the mode before installing + +```php +// config/laranail/settings.php +'tenancy' => [ + 'mode' => 'column', // one database: a tenant column on every package table + 'discriminator' => 'auto', // stancl/tenancy or spatie/laravel-multitenancy when installed +], +``` + +```bash +php artisan laranail::settings.install +php artisan migrate +``` + +The mode is a migration-time switch, recorded in the schema file; changing it later needs a migration. With `database` mode instead, publish the migration into the tenant migrations folder and let the tenancy package switch connections. + +## Tell the package who the tenant is + +With stancl/tenancy or spatie/laravel-multitenancy installed, `auto` finds the tenant. Otherwise bind your own: + +```php +'tenancy' => ['mode' => 'column', 'discriminator' => App\Settings\TeamTenant::class], +``` + +```php +final readonly class TeamTenant implements TenantDiscriminator +{ + public function __construct(private CurrentTeam $team) {} + + public function current(): ?string + { + return $this->team->id(); + } +} +``` + +## Use settings as usual + +```php +tenancy()->initialize($acme); +$settings->set('site.name', 'Acme'); // stamped with Acme's tenant id + +tenancy()->initialize($globex); +$settings->get('site.name'); // null: Globex has its own rows +``` + +Reads, writes, the cache and the in-memory preload are all keyed by tenant, so a queue worker or an Octane worker that serves several tenants never mixes them. `''` is the central application's tenant. + +## Seed each tenant's categories + +```php +tenancy()->runForMultiple(Tenant::all(), fn () => Artisan::call('db:seed', [ + '--class' => DefaultCategoriesSeeder::class, +])); +``` + +## Per-tenant defaults + +Definitions are shared by every tenant; values are not. A tenant inherits the definition default until it writes its own value, so ship defaults in definitions or `settings/defaults.php`, not in seeders. + +See [Tenancy](../tools/tenancy.md) for the adapters, the unique keys and the readiness flush on tenant switches. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/recipes/using-typed-settings.md b/docs/recipes/using-typed-settings.md new file mode 100644 index 0000000..4b3fb21 --- /dev/null +++ b/docs/recipes/using-typed-settings.md @@ -0,0 +1,66 @@ +# Use typed settings + +Group related keys into a class with typed properties, so the rest of the application reads `$mail->port` instead of `get('mail.port')`. + +## Declare the class + +```php +use Simtabi\Laranail\Settings\Typed\TypedSettings; +use Simtabi\Laranail\Settings\Typed\Attributes\{Encrypted, Group}; + +#[Group('mail')] +final class MailSettings extends TypedSettings +{ + public string $fromAddress = 'hello@example.com'; // mail.from_address + public string $fromName = 'Acme'; // mail.from_name + public int $port = 25; // mail.port + #[Encrypted] public ?string $password = null; // defined encrypted +} +``` + +## Register it + +```php +// config/laranail/settings.php +'typed' => ['classes' => [App\Settings\MailSettings::class]], +``` + +Each property becomes a definition (type, default, encryption), so `get('mail.port')`, the REST API and the admin UI see the same types and defaults. + +## Inject and read it + +```php +final readonly class MailerFactory +{ + public function __construct(private MailSettings $mail) {} + + public function sender(): Address + { + return new Address($this->mail->fromAddress, $this->mail->fromName); + } +} +``` + +The container builds it with `MailSettings::load()` through the `Settings` handle, so caching and the cascade apply. + +## Change it as a user + +```php +$mail = MailSettings::load($settings->as($request->user())->because('new SMTP relay')); +$mail->port = 587; +$mail->save(); // writes mail.port only, through set(): validated, audited, versioned +``` + +## Per owner + +```php +$teamMail = MailSettings::load($settings->for($team)); +``` + +## Evolve it with migrations + +Renaming a property renames its key; move the stored values with a settings migration instead of losing them. See [Typed settings](../tools/typed-settings.md) for the attributes, the supported types and `SettingsMigration`. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/commands.md b/docs/tools/commands.md index 6de2ac1..8680efb 100644 --- a/docs/tools/commands.md +++ b/docs/tools/commands.md @@ -1,6 +1,6 @@ # Commands -Nineteen Artisan commands, all named `laranail::settings.`. +Eighteen Artisan commands, all named `laranail::settings.`. ## The commands @@ -23,7 +23,6 @@ Nineteen Artisan commands, all named `laranail::settings.`. | `laranail::settings.diff {path} [--store=]` | compares a store with an export file, by identity only; exits 1 when they differ | | `laranail::settings.reencrypt` | encrypts every stored secret again under the current key (values, history, change requests) | | `laranail::settings.rescope {from} {to}` | renames an owner alias in stored values, history and change requests | -| `laranail::settings.openapi [--output=]` | writes the OpenAPI 3.1 document of the REST API (needs `http.enabled`) | Each one delegates to an action (`Actions\PromoteStore`, `Actions\PruneOrphans`, …) that the PHP API uses too, so the console and the API cannot behave differently. @@ -96,7 +95,7 @@ version, through the same action as `rollback()`. See [History](history.md). `export`, `import` and `diff` are described in [Import and export](import-export.md) and [Importers](importers.md); `reencrypt` and `rescope` in [Re-encryption and rescoping](reencryption.md); -`prune-changes` in [Approvals](approvals.md); `openapi` in [REST API](rest-api.md). Each runs as the +`prune-changes` in [Approvals](approvals.md). Each runs as the system actor, is audited under its name, and delegates to the same action as the PHP API. `doctor` also checks, per database store: encrypted values no current or previous key can read, diff --git a/docs/tools/events.md b/docs/tools/events.md index c1e19e3..8253fde 100644 --- a/docs/tools/events.md +++ b/docs/tools/events.md @@ -1,6 +1,6 @@ # Events -Twenty-four events, all `final readonly` classes in `Simtabi\Laranail\Settings\Events`, carrying identifiers and counts, never a value. +Thirty events, all `final readonly` classes in `Simtabi\Laranail\Settings\Events`, carrying identifiers and counts, never a value. ## Changes @@ -17,6 +17,38 @@ Twenty-four events, all `final readonly` classes in `Simtabi\Laranail\Settings\E | `CategoryRenamed` | after a rename, besides `CategorySaved` | `store`, `slug` | | `CategoryDeleting` / `CategoryDeleted` | around a delete | `store`, `slug` | +## Approvals + +| Event | Dispatched | Carries | +|---|---|---| +| `ChangeRequested` | a change request was opened, by `propose()` or by a write that needs approval | `id`, `store`, `scope`, `key`, `locale`, `operation` | +| `ChangeApproved` | a request received an approval | the same, plus `remaining` (approvals still needed) | +| `ChangeApplied` | an approved request was written through the write pipeline (besides `SettingSaved` and its kin) | the same, plus `version` | +| `ChangeStale` | an approved request was not applied: its setting changed after it was opened | the same | +| `ChangeRejected` | a request was rejected; nothing was written | the same | +| `ChangeCancelled` | the requester cancelled a request; nothing was written | the same | + +None carries the proposed value. See [Approvals](approvals.md). + +## Which call fires what + +| Call (PHP, REST or console) | Events | +|---|---| +| `set()`, `setMany()`, `remember()` (when it writes), `PUT …/settings/{key}` | `SettingSaving`, `SettingSaved`; or `ChangeRequested` | +| `forget()`, `forgetMany()`, `DELETE …/settings/{key}` | `SettingForgetting`, `SettingForgotten`; or `ChangeRequested` | +| `lock()`, `unlock()` | `SettingLocked`, `SettingUnlocked`; or `ChangeRequested` | +| `rollback()` | `SettingSaving`, `SettingSaved`, `SettingRolledBack` | +| `flush()`, deleting a `HasSettings` model | `ScopeFlushing`, `ScopeFlushed` | +| `promote()` | `StorePromoting`, `StorePromoted` | +| `propose()`, `POST …/changes` | `ChangeRequested` | +| `approvals()->approve()` | `ChangeApproved`, then `ChangeApplied` or `ChangeStale` once enough approvals arrive | +| `approvals()->reject()`, `->cancel()` | `ChangeRejected`, `ChangeCancelled` | +| `categories()` writes | `CategorySaving`, `CategorySaved`, `CategoryRenamed`, `CategoryMoved`, `CategoryDeleting`, `CategoryDeleted` | +| `import()` | the events of each write it makes | +| any refused call | `AccessWasDenied` or `VerificationWasRequired` | +| `sync-definitions`, `prune-audit`, `prune-history`, `prune-orphans` | `DefinitionsSynced`, `AuditPruned`, `HistoryPruned`, `OrphansPruned` | +| reads (`get()`, `all()`, `GET …`) | none | + ## Refusals | Event | Dispatched | Carries | diff --git a/docs/tools/exceptions.md b/docs/tools/exceptions.md new file mode 100644 index 0000000..544e943 --- /dev/null +++ b/docs/tools/exceptions.md @@ -0,0 +1,68 @@ +# Exceptions + +Thirty exception classes in `Simtabi\Laranail\Settings\Exceptions`, all extending `SettingsException`, with when each is raised and how the REST API answers it. + +## Catching them + +```php +use Simtabi\Laranail\Settings\Exceptions\AccessDenied; +use Simtabi\Laranail\Settings\Exceptions\LockedSetting; +use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; + +try { + $settings->as($user)->set('mail.from.address', $input); +} catch (InvalidSettingValue $e) { + return back()->withErrors(['value' => $e->getMessage()]); +} catch (AccessDenied|LockedSetting $e) { + abort(403, $e->getMessage()); +} catch (SettingsException $e) { + report($e); + throw $e; +} +``` + +Messages name the store, key, scope and ability involved, never a value, so they are safe to log and to show an administrator. A write that opens a change request does not throw; it returns normally (PHP) or answers `202` (REST). + +## Reference + +| Exception | Extends | Raised when | REST | +|---|---|---|---| +| `SettingsException` | `RuntimeException` | the base of every exception below; catch it to catch them all | `500 settings-error` for a subtype not listed | +| `AccessDenied` | `SettingsException` | an actor may not perform the ability on the subject; carries the ability, store and key | `403 access-denied` | +| `ActorRequired` | `SettingsException` | a call has no actor while `authorization.require_actor` is on, or `asCurrentActor()` finds nobody | `401 actor-required` | +| `VerificationRequired` | `SettingsException` | the actor is allowed but must verify again (step-up), for an ability in `verification.abilities` or a definition that `requiresVerification()` | `428 verification-required` | +| `ApprovalUnavailable` | `SettingsException` | a write needs approval but the store cannot hold change requests (no active database layer, or no change requests table) | `409 approval-unavailable` | +| `ChangeRequestClosed` | `SettingsException` | a change request was already applied, rejected, cancelled, stale or expired | `409 change-request-closed` | +| `UnknownChangeRequest` | `SettingsException` | no change request with this id exists in the store (for the current tenant) | `404 unknown-change-request` | +| `ConcurrentModification` | `SettingsException` | another writer changed the row between read and update (the version check failed), or `If-Match` did not match; re-read and retry | `412 precondition-failed` | +| `LockedSetting` | `SettingsException` | the row is locked, or the definition's precedence forbids store writes | `423 locked` | +| `OwnerNotAllowed` | `SettingsException` | the owner's alias is not allowed in the store, or no store accepts it | `409 owner-not-allowed` | +| `UnknownOwner` | `SettingsException` | the REST owner resolver cannot find the alias or the record | `404 unknown-owner` | +| `StoreNotWritable` | `SettingsException` | no layer of the store accepts the write | `409 store-not-writable` | +| `UnknownStore` | `SettingsException` | a store that is not configured | `404 unknown-store` | +| `UnknownSetting` | `SettingsException` | a strict store was asked for a key with no definition | `404 unknown-setting` | +| `UnknownCategory` | `SettingsException` | no category with the slug exists in the store | `404 unknown-category` | +| `CategoryCycle` | `SettingsException` | moving a category under itself or a descendant | `422 category-cycle` | +| `CategoryStoreMismatch` | `SettingsException` | a category belongs to another store than what refers to it | `422 category-store-mismatch` | +| `InvalidSettingValue` | `SettingsException` | a value failed its definition's rules, cast or locale constraints | `422 invalid-value` | +| `TypeMismatch` | `SettingsException` | a typed getter (`string()`, `integer()`, …) or a typed settings property found another type, or no value | `422 type-mismatch` | +| `InvalidIdentifier` | `SettingsException` | a store name, locale, owner alias or filter failed validation | `422 invalid-identifier` | +| `InvalidKey` | `InvalidIdentifier` | a key is not lower-case dot notation of `[a-z0-9_]` segments, at most 191 characters; or `many()` got a non-string list entry | `422 invalid-identifier` | +| `InvalidDefinition` | `SettingsException` | a definition is inconsistent (encrypted and public), uses an unknown type, or a typed property has an unsupported type | `422 invalid-definition` | +| `InvalidConfiguration` | `SettingsException` | the package configuration is invalid; the message names the config path | `422 invalid-configuration` | +| `InvalidImport` | `SettingsException` | an export file or importer source is not a document this release can read | `422 invalid-import` | +| `HistoryUnavailable` | `SettingsException` | the store keeps no history, or lacks the version asked for | `409 history-unavailable` | +| `PromotionLocked` | `SettingsException` | another promotion of the same store holds the lock; retry when it finishes | `500 settings-error` (console and PHP only) | +| `EncryptionUnavailable` | `SettingsException` | an encrypted setting was written or read before an encryption key exists | `500 settings-error` | +| `UndecryptableValue` | `SettingsException` | an encrypted value cannot be decrypted with the current or previous keys (run `reencrypt` after a key rotation) | `500 settings-error` | +| `DriverUnavailable` | `SettingsException` | a required layer is unreachable (the database is down, its table missing) and no bootstrap evidence lets the store skip it; never a silent fall back to defaults | `503 unavailable` | +| `DriverFailure` | `SettingsException` | a storage layer failed; the underlying exception is the previous one | `500 settings-error` | + +`LogicException` (PHP's own) is thrown for a programming error rather than a runtime condition: `flush()` without `for($owner)`. + +Each exception names its HTTP status and problem type itself (`STATUS` and `TYPE` constants), and `Http\Support\Problems` renders them; anything without its own is a `500 settings-error`; [REST API reference](rest-api-reference.md#problem-types) lists every problem type. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/rest-api-reference.md b/docs/tools/rest-api-reference.md new file mode 100644 index 0000000..cecb53b --- /dev/null +++ b/docs/tools/rest-api-reference.md @@ -0,0 +1,359 @@ +# REST API reference + +Every route of the JSON API, 39 in all (30 route names, nine of them with an owner form), with its ability, request, response, status codes and problems. [REST API](rest-api.md) explains turning it on, authentication, ETags and idempotency; this page is the per-route reference. + +Paths are under `/{http.prefix}/v1`, by default `/api/settings/v1`; set `http.prefix` (`LARANAIL_SETTINGS_HTTP_PREFIX`) to move them, for example when the application already has routes under `/api/settings` (Laravel silently keeps the last route registered for a method and URI), or to an empty string to mount them at `/v1`. Route names are `laranail-settings.api.`, and `laranail-settings.api.owners.` for an owner form; they do not change with the prefix. A test reading the live router fails when a registered route is missing from this page. + +## Conventions + +| Topic | Rule | +|---|---| +| Authentication | the host's `http.middleware` authenticates; the actor resolver turns the request into an actor on the `rest` channel. No actor: `401`. The API never runs as trusted code. | +| Abilities | each route names the ability its action checks. A Sanctum token's `settings:` abilities are a ceiling on top. | +| Owners | a settings route has a global form (`/stores/{store}/settings/…`) and an owner form (`/stores/{store}/owners/{alias}/{id}/settings/…`). `{alias}` is a morph alias from `http.owners` or the morph map, never a class name. | +| Locales | `?locale=fr` on settings routes; the write routes also take it. | +| Bodies | JSON. Every write may send `"reason"` (recorded in the audit trail and history). | +| ETags | setting responses carry `ETag`. Send it back as `If-Match` on `PUT` or `DELETE`: a mismatch is `412`; `*` matches any version. | +| Idempotency | every non-`GET` route accepts `Idempotency-Key`; a retry with the same key, user, method and path within `http.idempotency.ttl` (24 hours) is answered from cache with `Idempotent-Replayed: true`. | +| Pagination | lists answer `{"data": [...], "meta": {"next_cursor": "…" or null}}`; pass `?cursor=` and `?limit=` (1 to 200, default `http.page_size`). Cursors are opaque. | +| Visibility | values the actor may not view are left out of lists; a single setting answers `"redacted": true` without `value`. | +| Approvals | a write to a setting that needs approval answers `202` with the change request instead of the setting. | +| Errors | RFC 9457 `application/problem+json`; see [Problem types](#problem-types). | +| Rate limit | `http.rate_limit` per minute per user (or IP): `429`. | + +## Stores and definitions + +### `GET /stores` + +`stores.index`, ability `view` per store (stores the actor may not view are left out). Lists the configured stores. + +```json +{"data": [{"name": "settings", "mode": "polymorphic", "owners": ["user"], "layers": ["database", "runtime", "shipped"], + "strict": false, "inherits": false, "fallback": null, "approvals": ["billing.*"]}], + "meta": {"next_cursor": null}} +``` + +Status: `200`, `401`, `429`. + +### `GET /stores/{store}/definitions` + +`definitions.index`, ability `view`. The store's definitions (code, configuration and the definitions table), in key order: what a form is rendered from. Never a value; an encrypted definition's default is left out. + +```json +{"data": [{"store": "settings", "key": "mail.from.address", "group": "mail", "category": "mail", "type": "email", + "has_default": true, "default": "hello@example.com", "rules": ["email"], "encrypted": false, "sensitive": false, + "public": false, "locked": false, "localised": false, "inherits": null, "overridable_by": [], "precedence": "store", + "label": "Sender address", "description": null, "requires_verification": false, "requires_approval": false}], + "meta": {"next_cursor": null}} +``` + +Status: `200`, `401`, `403`, `404` (`unknown-store`). + +### `PUT /stores/{store}/definitions/{key}` + +`definitions.update`, ability `manage_definitions`. Saves a definition in the definitions table (needs `definitions.table`). It only answers for keys no code or config definition covers. + +```json +{"attributes": {"type": "string", "default": "free", "rules": ["in:free,pro"], "label": "Plan"}} +``` + +Answers `200` with the `Definition`. Status: `200`, `401`, `403`, `404`, `422` (`invalid-definition`, `validation`). + +### `DELETE /stores/{store}/definitions/{key}` + +`definitions.destroy`, ability `manage_definitions`. Deletes a database definition. Status: `204`, `401`, `403`, `404`. + +## Settings + +Every route here has an owner form, listed under it. `{key}` is a setting key (`[A-Za-z0-9_.]`, lower-cased). + +### `GET /stores/{store}/settings` + +Owner form: `GET /stores/{store}/owners/{alias}/{id}/settings`. + +`settings.index`, ability `view` per key. A page of the scope's settings: each key the scope holds in any layer and each key a definition names, in key order, read as `GET …/settings/{key}` reads it. Keys the actor may not view, or sensitive keys it may not read, are left out. Query: `locale`, `limit`, `cursor` (the last key of the previous page). + +```http +GET /api/settings/v1/stores/settings/owners/user/42/settings?limit=2 +``` + +```json +{"data": [ + {"store": "settings", "scope": "user:42", "key": "ui.density", "locale": "", "found": true, "layer": "database", "from": "user:42", "version": 1, "redacted": false, "value": "compact"}, + {"store": "settings", "scope": "user:42", "key": "ui.theme", "locale": "", "found": true, "layer": "database", "from": "global", "version": 0, "redacted": false, "value": "light"} + ], + "meta": {"next_cursor": "ui.theme"}} +``` + +`from` is the scope the value came from (here the global value, inherited); `version` is the address's own row (0: none). Status: `200`, `401`, `403`, `404` (`unknown-store`, `unknown-owner`), `409` (`owner-not-allowed`). + +### `GET /stores/{store}/settings/{key}` + +Owner form: `GET /stores/{store}/owners/{alias}/{id}/settings/{key}`. + +`settings.show`, ability `view` (`view_sensitive` for a sensitive value). One setting, with its `ETag`. + +```json +{"data": {"store": "settings", "scope": "global", "key": "site.name", "locale": "", "found": true, + "layer": "database", "from": "global", "version": 2, "redacted": false, "value": "Acme"}} +``` + +A key with no value answers `200` with `"found": false`. A sensitive value the actor may not read answers `"redacted": true` without `value`. Status: `200`, `401`, `403`, `404`, `409`. + +### `PUT /stores/{store}/settings/{key}` + +Owner form: `PUT /stores/{store}/owners/{alias}/{id}/settings/{key}`. + +`settings.update`, ability `update` (plus step-up verification where configured). Writes a value through the write pipeline. + +```http +PUT /api/settings/v1/stores/settings/settings/site.name +If-Match: "4f1c…" +Idempotency-Key: 6c0d1e8e-… + +{"value": "Acme Ltd", "reason": "INC-7"} +``` + +Answers `200` with the setting as now read (and its new `ETag`), or `202` with a `ChangeRequest` when the setting needs approval. Status: `200`, `202`, `401`, `403`, `404`, `409` (`approval-unavailable`, `store-not-writable`, `owner-not-allowed`), `412`, `422` (`invalid-value`, `validation`), `423`, `428`. + +### `DELETE /stores/{store}/settings/{key}` + +Owner form: `DELETE /stores/{store}/owners/{alias}/{id}/settings/{key}`. + +`settings.destroy`, ability `forget`. Removes the address's own value, so reads fall through again. Takes `If-Match` and `reason`. Answers `204`, or `202` with a `ChangeRequest`. Status: `204`, `202`, `401`, `403`, `404`, `409`, `412`, `423`, `428`. + +### `POST /stores/{store}/settings/{key}/lock` + +Owner form: `POST /stores/{store}/owners/{alias}/{id}/settings/{key}/lock`. + +`settings.lock`, ability `lock`. Locks the row against further writes. Body: `{"reason": "…"}` (optional). Answers `200` with the setting, or `202`. Status: `200`, `202`, `401`, `403`, `404`, `409`, `428`. + +### `DELETE /stores/{store}/settings/{key}/lock` + +Owner form: `DELETE /stores/{store}/owners/{alias}/{id}/settings/{key}/lock`. + +`settings.unlock`, ability `unlock`. Unlocks the row. Answers `200` with the setting, or `202`. Status as for lock. + +### `GET /stores/{store}/settings/{key}/explain` + +Owner form: `GET /stores/{store}/owners/{alias}/{id}/settings/{key}/explain`. + +`settings.explain`, ability `view`. How the read resolves: every layer and scope tried. + +```json +{"data": {"found": true, "layer": "database", "from": "team:7", "redacted": false, + "steps": ["settings / user:42 / (none) / database", "settings / team:7 / (none) / database"], "value": "dark"}} +``` + +Status: `200`, `401`, `403`, `404`. + +### `GET /stores/{store}/settings/{key}/history` + +Owner form: `GET /stores/{store}/owners/{alias}/{id}/settings/{key}/history`. + +`settings.history`, ability `view_history`. The setting's versions, newest first, paginated (`limit`, `cursor`, `locale`). Payloads are as stored (encrypted values encrypted) and are removed for an actor without `view_sensitive`. + +```json +{"data": [{"id": "01JC…", "store": "settings", "setting_ref": "site.name", "scope": "global", "key": "site.name", "locale": "", + "operation": "set", "old_value": "\"Acme\"", "new_value": "\"Acme Ltd\"", "old_type": "string", "new_type": "string", + "old_encrypted": false, "new_encrypted": false, "version": 3, "causer_type": "user", "causer_alias": "user", + "causer_id": "1", "reason": "INC-7", "created_at": "2026-11-10T09:12:00+00:00"}], + "meta": {"next_cursor": null}} +``` + +Status: `200`, `401`, `403`, `404`, `409` (`history-unavailable`). + +### `POST /stores/{store}/settings/{key}/rollback` + +Owner form: `POST /stores/{store}/owners/{alias}/{id}/settings/{key}/rollback`. + +`settings.rollback`, ability `rollback` (verified by default). Writes the value of an earlier version as a new version. + +```json +{"version": 2, "reason": "revert INC-7"} +``` + +Answers `200` with the setting as now read. Status: `200`, `401`, `403`, `404`, `409` (`history-unavailable`), `422`, `423`, `428`. + +## Audit + +### `GET /audit` + +`audit.index`, ability `view_audit`. The audit trail, newest first. Entries never hold values. Filters: `store`, `scope` (`global` or `alias:id`), `key`, `action` (an `AuditAction` value such as `set`, `forget`, `rollback`), `outcome` (`allowed`, `denied`, `pending`, `failed`), `since`, `until` (dates); plus `limit`, `cursor`. + +```json +{"data": [{"id": "01JC…", "occurred_at": "2026-11-10T09:12:00+00:00", "action": "set", "outcome": "allowed", + "store": "settings", "scope": "global", "key": "site.name", "locale": "", "version_from": 2, "version_to": 3, + "actor_type": "user", "actor_alias": "user", "actor_id": "1", "channel": "rest"}], + "meta": {"next_cursor": "…"}} +``` + +Status: `200`, `401`, `403`, `422` (`invalid-identifier` for a bad filter). + +## Change requests + +### `GET /stores/{store}/changes` + +`changes.index`. An actor holding `approve` sees every request of the store; others see their own. Filters: `status` (`pending`, `approved`, `applied`, `rejected`, `cancelled`, `stale`, `expired`), `key`; plus `limit`, `cursor`. Status: `200`, `401`, `404`, `422`. + +### `POST /stores/{store}/changes` + +`changes.store`, the ability of the write being proposed (`update` for `set`). Opens a change request whether or not the setting needs approval. + +```json +{"key": "billing.price", "value": 49, "owner": {"alias": "team", "id": "7"}, "locale": null, "operation": "set", "reason": "Q3 pricing"} +``` + +`operation` is `set` (default), `forget`, `lock` or `unlock`; `owner` is omitted for the global value. Answers `202` with the `ChangeRequest`: + +```json +{"data": {"id": "01JC…", "store": "settings", "scope": "team:7", "key": "billing.price", "locale": "", "operation": "set", + "encrypted": false, "base_version": 4, "status": "pending", "requested_by": {"type": "user", "alias": "user", "id": "3"}, + "approvals": [], "decided_by": null, "decided_at": null, "reason": "Q3 pricing", "decision_reason": null, + "expires_at": "2026-11-17T09:12:00+00:00", "created_at": "2026-11-10T09:12:00+00:00"}} +``` + +Status: `202`, `401`, `403`, `404`, `409` (`approval-unavailable`), `422`. + +### `GET /stores/{store}/changes/{id}` + +`changes.show`, visible as in the listing. Status: `200`, `401`, `404` (`unknown-change-request`). + +### `POST /stores/{store}/changes/{id}/approve` + +`changes.approve`, ability `approve`; the requester cannot approve their own request unless `approvals.allow_self`. Body: `{"reason": "…"}`. When the approvals reach `approvals.min_approvals`, the change is applied against its base version (or becomes `stale` when the setting changed meanwhile). Answers `200` with the `ChangeRequest`. Status: `200`, `401`, `403`, `404`, `409` (`change-request-closed`), `428`. + +### `POST /stores/{store}/changes/{id}/reject` + +`changes.reject`, ability `approve`. Body: `{"reason": "…"}`. Answers `200`. Status as for approve. + +### `POST /stores/{store}/changes/{id}/cancel` + +`changes.cancel`, the requester only. Body: `{"reason": "…"}`. Answers `200`. Status as for approve. + +## Categories + +### `GET /stores/{store}/categories` + +`categories.index`, ability `view`. The store's categories, parents before children. Status: `200`, `401`, `403`, `404`. + +```json +{"data": [{"slug": "mail", "store": "settings", "title": "Mail", "titles": {}, "parent": null, "description": "Sender name and address.", + "icon": "envelope", "sort_order": 0, "system": true}], + "meta": {"next_cursor": null}} +``` + +### `POST /stores/{store}/categories` + +`categories.store`, ability `manage_categories`. + +```json +{"slug": "billing", "title": "Billing", "parent": "general", "description": null, "icon": "credit-card", "sort_order": 3, "titles": {"fr": "Facturation"}} +``` + +Answers `201` with the `Category`. Status: `201`, `401`, `403`, `404`, `422` (`category-cycle`, `category-store-mismatch`, `validation`). + +### `PATCH /stores/{store}/categories/{slug}` + +`categories.update`, ability `manage_categories`. `{"title": "…"}` renames; `{"parent": "…"}` moves (`null` to the top level). Answers `200` with the `Category`. Status: `200`, `401`, `403`, `404` (`unknown-category`), `422`. + +### `DELETE /stores/{store}/categories/{slug}` + +`categories.destroy`, ability `manage_categories`. Status: `204`, `401`, `403`, `404`. + +## Persisted configuration + +These need `configuration.persisted`; see [Persisted configuration](persisted-configuration.md). + +### `GET /configuration` + +`configuration.index`, ability `manage_stores`. Persisted stores and layers: `[{"kind": "store", "name": "tenant_settings", "config": {…}}]`. Status: `200`, `401`, `403`. + +### `PUT /configuration/{kind}/{name}` + +`configuration.update`, ability `manage_stores` (verified by default). `{kind}` is `stores` or `layers`. + +```json +{"config": {"layers": ["database"], "owners": ["team"]}} +``` + +Answers `200` with the `ConfigurationEntry`. Status: `200`, `401`, `403`, `422` (`invalid-configuration`), `428`. + +### `DELETE /configuration/{kind}/{name}` + +`configuration.destroy`, ability `manage_stores`. Status: `204`, `401`, `403`, `428`. + +## Import and export + +### `POST /stores/{store}/export` + +`transfer.export`, ability `export` (`view_sensitive` for `plaintext`). Body: `{"mode": "redacted" | "ciphertext" | "plaintext"}` (default `redacted`). Answers `200` with the `ExportDocument`: + +```json +{"data": {"format": "laranail/settings", "version": 1, "store": "settings", "mode": "redacted", + "categories": [{"slug": "mail", "title": "Mail", "parent": null}], + "settings": [{"scope": "global", "key": "site.name", "locale": "", "value": "Acme", "type": "string"}]}} +``` + +Status: `200`, `401`, `403`, `404`. + +### `POST /stores/{store}/import` + +`transfer.import`, ability `import` (verified by default). A **dry run** unless `"apply": true`. + +```json +{"document": {"format": "laranail/settings", "version": 1, "store": "settings", "mode": "redacted", "categories": [], "settings": []}, "apply": true} +``` + +Answers `200` with the `ImportReport` (`applied`, `created`, `updated`, `unchanged`, `skipped`, `categories`, `proposed`). Status: `200`, `401`, `403`, `404`, `422` (`invalid-import`), `428`. + +### `POST /stores/{store}/diff` + +`transfer.diff`, ability `export`. Body: `{"document": {…}}`. Answers `200` with the `StoreDiff` (`added`, `removed`, `changed`, `unchanged`, `unknown`: keys only). Status: `200`, `401`, `403`, `404`, `422`. + +## Problem types + +Every error is a problem document whose `type` is `https://opensource.simtabi.com/documentation/laranail/settings/problems/`: + +```json +{"type": "https://opensource.simtabi.com/documentation/laranail/settings/problems/locked", "title": "Locked", "status": 423, + "detail": "Setting [billing.currency] in store [settings] is locked for scope [global].", "instance": "/api/settings/v1/stores/settings/settings/billing.currency"} +``` + +| Type | Status | Raised by | +|---|---|---| +| `access-denied` | 403 | `AccessDenied` | +| `actor-required` | 401 | `ActorRequired` | +| `unauthenticated` | 401 | the host's authentication middleware | +| `verification-required` | 428 | `VerificationRequired`: verify (confirm the password) and retry | +| `unknown-store` | 404 | `UnknownStore` | +| `unknown-setting` | 404 | `UnknownSetting` (a strict store's undefined key) | +| `unknown-owner` | 404 | `UnknownOwner` (an alias or record the owner resolver cannot find) | +| `unknown-category` | 404 | `UnknownCategory` | +| `unknown-change-request` | 404 | `UnknownChangeRequest` | +| `invalid-value` | 422 | `InvalidSettingValue` | +| `invalid-identifier` | 422 | `InvalidIdentifier`, `InvalidKey` (a key, store, locale, alias or filter) | +| `invalid-import` | 422 | `InvalidImport` | +| `invalid-definition` | 422 | `InvalidDefinition` | +| `invalid-configuration` | 422 | `InvalidConfiguration` | +| `type-mismatch` | 422 | `TypeMismatch` | +| `category-cycle` | 422 | `CategoryCycle` | +| `category-store-mismatch` | 422 | `CategoryStoreMismatch` | +| `validation` | 422 | request validation; the body adds `errors` | +| `locked` | 423 | `LockedSetting` | +| `precondition-failed` | 412 | `ConcurrentModification` (`If-Match` did not match) | +| `approval-unavailable` | 409 | `ApprovalUnavailable` | +| `change-request-closed` | 409 | `ChangeRequestClosed` | +| `owner-not-allowed` | 409 | `OwnerNotAllowed` | +| `store-not-writable` | 409 | `StoreNotWritable` | +| `history-unavailable` | 409 | `HistoryUnavailable` | +| `too-many-requests` | 429 | the rate limit | +| `unavailable` | 503 | `DriverUnavailable` | +| `http-` | that status | any other HTTP exception (`http-404` for an unknown route) | +| `settings-error` | 500 | any other package exception (its message is not exposed) | + +Detail messages name stores, keys and scopes, never a value. + +--- + +[← Docs index](../../README.md#documentation) diff --git a/docs/tools/rest-api.md b/docs/tools/rest-api.md index 2de20f7..290e0ac 100644 --- a/docs/tools/rest-api.md +++ b/docs/tools/rest-api.md @@ -8,20 +8,20 @@ A JSON API over every capability of the PHP API (§16.10), in this package and o // config/laranail/settings.php 'http' => [ 'enabled' => true, - 'prefix' => 'api/settings', // routes live under api/settings/v1 + 'prefix' => env('LARANAIL_SETTINGS_HTTP_PREFIX', 'api/settings'), // routes live under /v1 'middleware' => null, // null: ['api', 'auth:sanctum'] with Sanctum, else ['api', 'auth'] 'rate_limit' => 60, // per minute, per user (or IP); 0 for none 'routes' => ['approvals' => false], // switch groups off ], ``` -No route is registered until `enabled` is true. Controllers are built afresh for every request, so under Octane no request's actor, tenant or stores reach the next one. Routes are named `laranail-settings.api.` (the owner form of a settings route adds `owners.`), run through `http.middleware` and the `laranail-settings` rate limiter, and every write runs through the idempotency middleware. The host's middleware authenticates; the configured actor resolver turns the request into an [actor](access-control.md) on the `rest` channel, so with the `sanctum` resolver a token's `settings:` abilities are a ceiling on what it may do. A request nobody is authenticated for is refused (`401`); the API never runs as trusted code. +No route is registered until `enabled` is true. The routes are declared in `routes/api.php`, and each controller method takes the action it runs as a parameter, so under Octane no request's actor, tenant or stores reach the next one. Routes are named `laranail-settings.api.` (the owner form of a settings route adds `owners.`), run through `http.middleware` and the `laranail-settings` rate limiter, and every write runs through the idempotency middleware. The host's middleware authenticates; the configured actor resolver turns the request into an [actor](access-control.md) on the `rest` channel, so with the `sanctum` resolver a token's `settings:` abilities are a ceiling on what it may do. A request nobody is authenticated for is refused (`401`); the API never runs as trusted code. ## Endpoints All under `/{prefix}/v1`. `{owner}` is either nothing (the global value) or `owners/{alias}/{id}/`, an owner by morph alias and id. -| Method and path | Capability | Ability | +| Method and path | Route name | Ability | |---|---|---| | `GET stores` | `stores.index` | `view` (stores the actor may not view are left out) | | `GET stores/{store}/definitions` | `definitions.index` | `view` | @@ -42,7 +42,9 @@ All under `/{prefix}/v1`. `{owner}` is either nothing (the global value) or `own | `PUT`, `DELETE stores/{store}/definitions/{key}` | `definitions.update`, `definitions.destroy` | `manage_definitions` | | `POST stores/{store}/export`, `/import`, `/diff` | `transfer.*` | `export` (`view_sensitive` for plaintext), `import` | -Each capability runs the same action the PHP API runs (`Enums\Capability::actions()`), and an architecture test fails if a route, the capability list or a controller drifts from the others. +Every route, with request and response examples, status codes and problem types, is in the [REST API reference](rest-api-reference.md). + +Each route runs the same action the PHP API runs, and a test reading the live router fails if a route names no controller method, a controller method is not routed, or one does not delegate to an action. ## Requests and responses @@ -93,15 +95,21 @@ RFC 9457 problem details, `application/problem+json`: ## Owners -`owners/{alias}/{id}` resolves through the `OwnerResolver` contract. The default takes the alias from `http.owners` (alias => class) or the morph map; an alias in neither is `404`, never a class name from the URL. A `Settable` model is loaded, so its parents take part in reads; a missing record is `404`. Bind your own `OwnerResolver` to change that. +`owners/{alias}/{id}` resolves through `Owners\MorphMapOwnerResolver`: the alias comes from `http.owners` (alias => class) or the morph map; an alias in neither is `404`, never a class name from the URL. A `Settable` model is loaded, so its parents take part in reads; a missing record is `404`. -## OpenAPI +## Avoiding route collisions -```bash -php artisan laranail::settings.openapi --output=public/settings-openapi.json -``` +Laravel keeps the last route registered for a method and URI, and says nothing about the one it +replaced. If the application already serves anything under `/api/settings`, move the API with +`http.prefix` (or `LARANAIL_SETTINGS_HTTP_PREFIX`), for example to `internal/config`, which puts +every route under `/internal/config/v1`. An empty prefix mounts the API at `/v1`. Route names do not +change with the prefix, so `route('laranail-settings.api.settings.show', [...])` follows it. + +## Response shapes -writes an OpenAPI 3.1 document of the routes as registered, with a schema per resource. The package's tests validate real responses against it. See [Call the REST API with Sanctum](../recipes/calling-the-rest-api-with-sanctum.md). +Every response is a JSON resource (`Http\Resources\*`) wrapped in `data`, whatever the +application sets for its own resources; lists add `meta.next_cursor`. The package's tests validate +each response against its shape. See [Call the REST API with Sanctum](../recipes/calling-the-rest-api-with-sanctum.md). --- diff --git a/docs/tools/settings-api.md b/docs/tools/settings-api.md index 017a9d1..5b23b6b 100644 --- a/docs/tools/settings-api.md +++ b/docs/tools/settings-api.md @@ -1,81 +1,615 @@ # Settings API -The `Settings` contract, `Simtabi\Laranail\Settings\Contracts\Settings`, reads and writes settings; the `Settings` facade proxies it for applications. +Every public method of the `Settings` contract, `Simtabi\Laranail\Settings\Contracts\Settings`, with its signature, an example, the exceptions it throws and the events it fires; then the facade, the `settings()` helper, `HasSettings` and the objects the handle returns. -## Handles +The package is headless: this contract, the [REST API](rest-api.md) and the [commands](commands.md) are the three ways in, and all three run the same actions, so a capability reached from one behaves the same from the others. -`store()`, `for()`, `locale()`, `as()`, `asSystem()`, `asCurrentActor()` and `because()` each return a new handle. The shared instance never changes, so a handle scoped to one owner or actor cannot leak into another request. +## Getting a handle + +Take the contract in a constructor (the package's own classes do), or use the facade or the helper in application code. ```php use Simtabi\Laranail\Settings\Contracts\Settings; -public function __construct(private readonly Settings $settings) {} +final readonly class InvoiceMailer +{ + public function __construct(private Settings $settings) {} + + public function sender(): string + { + return $this->settings->string('mail.from.address'); + } +} +``` -$this->settings->get('mail.from.address'); -$this->settings->store('user_settings')->for($user)->get('ui.theme', 'light'); -$this->settings->locale('fr')->get('site.greeting'); +The contract is bound `scoped`: one instance per request or job, never shared across Octane requests. Every scoping method returns a **new handle**; the shared instance never changes, so a handle scoped to one owner or actor cannot leak into another call. + +```php +$settings->store('user_settings')->for($user)->locale('fr')->as($admin)->because('INC-7')->get('ui.theme'); ``` -| Method | Returns | Notes | -|---|---|---| -| `store(string $name)` | handle | another configured store | -| `for(Settable\|OwnerRef $owner)` | handle | without `store()`, routes to the store whose `owners` list the owner's alias | -| `locale(string $locale)` | handle | normalised (`pt-br` → `pt_BR`) | -| `as(Authenticatable\|Actor $actor)` | handle | every operation is authorized and audited; see [Access control](access-control.md) | -| `asSystem(?string $reason)` | handle | trusted code, explicitly; allowed when an actor is required | -| `asCurrentActor(?Request $request)` | handle | the actor the configured resolver finds; `ActorRequired` when nobody is authenticated | -| `because(string $reason)` | handle | the reason recorded with each change in the audit trail | -| `actor()` | `?Actor` | the handle's actor, or null for trusted code | -| `configuration()` | `RuntimeConfiguration` | changes for this request; see [Runtime configuration](runtime-configuration.md) | -| `withConfiguration($change, $run)` | `$run`'s result | changes for one callback, restored afterwards | +## Every method at a glance + +| Group | Methods | +|---|---| +| Scoping (return a handle) | [`store()`](#store), [`for()`](#for), [`locale()`](#locale), [`as()`](#as), [`asSystem()`](#assystem), [`asCurrentActor()`](#ascurrentactor), [`because()`](#because) | +| Reading | [`get()`](#get), [`lookup()`](#lookup), [`has()`](#has), [`missing()`](#missing), [`many()`](#many), [`all()`](#all), [`string()`, `integer()`, `float()`, `boolean()`, `array()`](#typed-getters), [`explain()`](#explain), [`definitions()`](#definitions) | +| Writing | [`set()`](#set), [`setMany()`](#setmany), [`remember()`](#remember), [`forget()`](#forget), [`forgetMany()`](#forgetmany), [`lock()`, `unlock()`](#lock-and-unlock), [`flush()`](#flush) | +| Cache and loading | [`preload()`](#preload), [`warmCache()`](#warmcache), [`clearCache()`](#clearcache) | +| History | [`history()`](#history), [`historyDiff()`](#historydiff), [`rollback()`](#rollback) | +| Approvals | [`propose()`](#propose), [`approvals()`](#approvals) | +| Store administration | [`categories()`](#categories), [`promote()`](#promote), [`audit()`](#audit), [`export()`](#export), [`import()`, `previewImport()`](#import-and-previewimport), [`compare()`](#compare), [`persistedConfiguration()`](#persistedconfiguration) | +| Context | [`actor()`](#actor), [`configuration()`](#configuration), [`withConfiguration()`](#withconfiguration) | + +Abilities are named in the [access control](access-control.md) reference. A handle **without** an actor is trusted code: it is not authorized, and it is audited as `system` (unless `authorization.require_actor` is on, when it throws `ActorRequired`). A handle **with** an actor is authorized for every operation, reads included, and every refusal fires `AccessWasDenied`. + +Every exception extends `Simtabi\Laranail\Settings\Exceptions\SettingsException`; the [exceptions reference](exceptions.md) says when each is raised and how the REST API answers it. + +## Scoping + +### `store()` + +```php +public function store(string $name): static + +$settings->store('user_settings')->get('ui.theme'); +``` + +A handle on another configured store. Throws `UnknownStore` on first use when the store is not configured, `InvalidIdentifier` for a malformed name. Fires nothing. + +### `for()` + +```php +public function for(Settable|OwnerRef $owner): static + +$settings->for($user)->set('ui.theme', 'dark'); +$settings->for(new OwnerRef('team', 42))->get('billing.plan'); +``` + +A handle for one owner. Without `store()` it routes to the store whose `owners` list the owner's morph alias; with one, the store must accept the alias. A `Settable` model also brings its parents, so reads can fall back to them (see [Owners](owners.md)). Throws `OwnerNotAllowed` when no store accepts the alias, `InvalidIdentifier` for a class-name alias. + +### `locale()` + +```php +public function locale(string $locale): static + +$settings->locale('fr')->get('site.greeting'); // falls back to app.fallback_locale, then to no locale +``` + +A handle reading and writing one locale, normalised (`pt-br` becomes `pt_BR`). Throws `InvalidIdentifier` for a malformed locale. + +### `as()` + +```php +public function as(Authenticatable|Actor $actor): static + +$settings->as($request->user())->set('mail.from.address', 'ap@acme.test'); +``` + +A handle acting as a user (or a prepared `Actor`): every operation is authorized through the configured authorizer and audited with that actor. See [Act as a user](../recipes/acting-as-a-user.md). + +### `asSystem()` + +```php +public function asSystem(?string $reason = null): static + +$settings->asSystem('nightly sync')->set('feeds.last_run', now()->toIso8601String()); +``` + +Trusted code, said out loud: allowed even when `authorization.require_actor` is on, audited as `system` with the reason. + +### `asCurrentActor()` + +```php +public function asCurrentActor(?Request $request = null): static + +$settings->asCurrentActor()->get('ui.theme'); +``` + +A handle acting as whoever the configured actor resolver (`authentication.resolver`) finds for the request: the guard's user, or a Sanctum token with its abilities as a ceiling. Throws `ActorRequired` when nobody is authenticated. + +### `because()` + +```php +public function because(string $reason): static + +$settings->as($admin)->because('INC-123')->set('billing.grace_days', 14); +``` + +A handle whose changes carry this reason in the audit trail, history and change requests. ## Reading -| Method | Returns | When nothing is stored | -|---|---|---| -| `get($key, $default = null)` | the value | the definition default, else `$default` | -| `lookup($key)` | `Lookup` | `isFound()` is false | -| `has($key)` | `bool` | false | -| `string()`, `integer()`, `float()`, `boolean()`, `array()` | the typed value | throws `TypeMismatch` | -| `explain($key)` | `Explanation` | lists every step tried; redacted when the actor may not view the value | +Reads fire no event (they are the hot path), except `AccessWasDenied` when an actor is refused. A read by an actor needs `view`; a sensitive or encrypted value needs `view_sensitive` as well. On a strict store a key without a definition throws `UnknownSetting`. + +### `get()` + +```php +public function get(string $key, mixed $default = null): mixed + +$settings->get('site.name'); // the stored value +$settings->get('site.tagline', 'Welcome'); // the definition default, else 'Welcome' +``` + +The value, resolved through the store's layers, the owner's parents and the global value as the definition allows; when nothing is found, the definition's default, else `$default`. A stored `null` is an answer: `get()` returns `null`, not the default. Throws `AccessDenied`, `ActorRequired`, `UnknownSetting`, `DriverUnavailable`. + +### `lookup()` + +```php +public function lookup(string $key): Lookup + +$lookup = $settings->lookup('site.name'); +$lookup->isFound(); // true when stored or defaulted +$lookup->value(); // throws when not found +$lookup->valueOr('x'); +$lookup->layer(); // 'database', 'runtime', 'shipped', 'default' … +$lookup->scope(); // the scope the value came from (an owner, a parent, global) +``` + +A presence-aware read. Throws as `get()` does. -A stored `null` is an answer: `has()` is true and `get()` returns `null`, not the default. +### `has()` + +```php +public function has(string $key): bool + +if ($settings->has('mail.from.address')) { … } +``` + +True when a value is stored (a stored `null` counts) or the definition has a default. + +### `missing()` + +```php +public function missing(string $key): bool + +if ($settings->for($user)->missing('onboarding.completed_at')) { + return redirect()->route('onboarding'); +} +``` + +The opposite of `has()`. + +### `many()` + +```php +public function many(array $keys): array + +[$name, $tagline] = array_values($settings->many(['site.name', 'site.tagline' => 'Welcome'])); +// ['site.name' => 'Acme', 'site.tagline' => 'Welcome'] +``` + +Several values at once, keyed as asked: a list of keys, `key => default` pairs, or both. Each key is read and authorized exactly as `get()` reads it. Throws `InvalidKey` when a list entry is not a string, and whatever `get()` throws. + +### `all()` + +```php +public function all(?string $prefix = null): array + +$settings->for($user)->all(); // ['ui.density' => 'compact', 'ui.theme' => 'dark'] +$settings->all('mail'); // 'mail' itself and every key below it +``` + +Every value the handle can see in its store and scope, by key, in key order: each key the scope holds in any layer, plus each key a code or config definition of the store names (so defaults appear). A key the actor may not view, or a sensitive key whose value it may not read, is left out rather than masked; a strict store's undefined stray rows are left out too. This is the PHP form of the REST API's `GET …/settings` listing, and both walk the same keys. Parents are consulted for the values of those keys, but keys held **only** by a parent are not listed unless a definition names them. + +### Typed getters + +```php +public function string(string $key): string +public function integer(string $key): int +public function float(string $key): float // accepts a stored int +public function boolean(string $key): bool +public function array(string $key): array + +$seats = $settings->integer('limits.seats'); +``` + +The value, guaranteed to be of that type. Throws `TypeMismatch` when the value is of another type or when nothing is found. + +### `explain()` + +```php +public function explain(string $key): Explanation + +$explanation = $settings->for($user)->explain('ui.theme'); +$explanation->lookup; // the answer, as lookup() returns it +$explanation->steps; // every layer and scope tried, in order, as text +``` + +How a read resolves: every step tried and the answer. For an actor without `view_sensitive` on a sensitive key, the answer is redacted (`isRedacted()`), the steps are kept. + +### `definitions()` + +```php +public function definitions(): array // list + +foreach ($settings->as($admin)->definitions() as $definition) { + $definition->key->value; // 'mail.from.address' + $definition->type; // 'email', 'integer', … + $definition->label; // for a form + $definition->category; // the category slug + $definition->isSensitive(); +} +``` + +The store's definitions from code, configuration and the definitions table, in key order: what a UI renders a form from. Never a value; an encrypted definition's default stays out. Needs `view`; throws `AccessDenied`. The PHP form of `GET /stores/{store}/definitions`. ## Writing -| Method | Effect | +A write by an actor needs the ability named below, and step-up verification when `verification.abilities` lists it or the definition `requiresVerification()` (`VerificationRequired`, with `VerificationWasRequired` fired). A write to a setting that needs approval opens a change request instead (`ChangeRequested`), and the method still returns normally; on a store that cannot hold change requests it throws `ApprovalUnavailable`. + +### `set()` + +```php +public function set(string $key, mixed $value): void + +$settings->set('site.name', 'Acme'); +$settings->for($user)->set('ui.theme', 'dark'); +``` + +Validates against the definition's rules, casts, encrypts an encrypted definition, and writes to the first writable layer, recording history and audit in the same transaction. Needs `update`. + +- **Throws** `UnknownSetting` (strict store), `OwnerNotAllowed`, `LockedSetting`, `InvalidSettingValue`, `EncryptionUnavailable`, `StoreNotWritable`, `ConcurrentModification` (after the one retry `writes.retry_on_conflict` allows), `AccessDenied`, `ActorRequired`, `VerificationRequired`, `ApprovalUnavailable`. +- **Fires** `SettingSaving`, then `SettingSaved` after commit; `ChangeRequested` instead when approval is needed. + +### `setMany()` + +```php +public function setMany(array $values): void + +$settings->for($user)->setMany([ + 'ui.theme' => 'dark', + 'ui.density' => 'compact', +]); +``` + +One `set()` per key, in the order given. **Not atomic**: each write is its own transaction, and the first refusal stops the rest while earlier writes stay. Wrap the call in `DB::transaction()` when every value lives in one database store and all-or-nothing matters. Throws and fires as `set()`, per key. + +### `remember()` + +```php +public function remember(string $key, callable $value): mixed + +$installId = $settings->asSystem()->remember('install.id', fn (): string => (string) Str::ulid()); +``` + +The stored value; when nothing is found, `$value()` is written with `set()` and read back, so the answer is cast exactly as a later read would be. Useful for values generated once (an installation id, a signing salt). When the write opens a change request instead, the read falls back to the computed value. Throws and fires as `get()` and `set()`. + +### `forget()` + +```php +public function forget(string $key): void + +$settings->for($user)->forget('ui.theme'); // the user's value goes; reads fall back to the global one +``` + +Removes this handle's own value (owner, locale), so reads fall through again. Needs `forget`. Throws as `set()` does (`LockedSetting` for a locked row). Fires `SettingForgetting` and `SettingForgotten`. + +### `forgetMany()` + +```php +public function forgetMany(iterable $keys): void + +$settings->for($user)->forgetMany(['ui.theme', 'ui.density']); +``` + +One `forget()` per key, in the order given; not atomic, like `setMany()`. + +### `lock()` and `unlock()` + +```php +public function lock(string $key): void +public function unlock(string $key): void + +$settings->as($admin)->lock('billing.currency'); +``` + +Refuse, or allow again, further writes to this row. A locked row refuses everyone unless the store's `locks.overridable` is on and the actor holds `override_lock`. Needs `lock` / `unlock`. Fires `SettingLocked` / `SettingUnlocked`. + +### `flush()` + +```php +public function flush(): void + +$settings->for($user)->asSystem('account closed')->flush(); +``` + +Removes every value the handle's owner holds in its store, as when an owner is deleted (`HasSettings` does this for you). Needs `for($owner)` (a `LogicException` otherwise) and `forget`. Throws `AccessDenied`, `StoreNotWritable`. Fires `ScopeFlushing` and `ScopeFlushed`. + +## Cache and loading + +### `preload()` + +```php +public function preload(iterable $owners): void + +$settings->preload($users); // one read per store for the whole page +foreach ($users as $user) { + $settings->for($user)->get('ui.theme'); // no further query +} +``` + +Loads many owners' settings, their parents' and the global scope, one read per store, for the rest of the request. `User::query()->withSettings()` does this for a query (see [Database](database.md)). + +### `warmCache()` + +```php +public function warmCache(): int + +$settings->store('settings')->warmCache(); // records cached +``` + +Loads the handle's scope (owner or global) into the cache now. Returns the number of records cached (0 when the store is not cached). Needs `manage_stores` with an actor. See [Caching](caching.md). + +### `clearCache()` + +```php +public function clearCache(): void + +$settings->for($user)->clearCache(); // that owner's cached values +$settings->clearCache(); // every cached value of the store, every tenant +``` + +Resets cached values; stored values are untouched. Needs `manage_stores` with an actor. + +## History + +All three need a store that keeps history (`history.enabled` when it was migrated); otherwise `HistoryUnavailable`. See [History](history.md). + +### `history()` + +```php +public function history(): HistoryQuery + +$entries = $settings->for($user)->history()->key('ui.theme')->since(now()->subWeek())->get(); +``` + +The value history of the handle's store, owner and locale. Filters: `for()`, `global()`, `store()`, `key()`, `locale()`, `since()`, `until()`, `versions($from, $to)`; then `get(?int $limit)`, `cursor()` or `paginate($perPage, $cursor)`. Payloads stay as stored; encrypted or sensitive payloads are removed for an actor without `view_sensitive`. Needs `view_history`. + +### `historyDiff()` + +```php +public function historyDiff(string $key, int $from, int $to): HistoryDiff + +$diff = $settings->as($admin)->historyDiff('mail.from.address', 3, 5); +``` + +The value at two versions. An encrypted or sensitive value is decrypted only for an actor holding `view_sensitive` (or trusted code), and otherwise redacted to "changed or not". Needs `view_history`. + +### `rollback()` + +```php +public function rollback(string $key, int $toVersion): int + +$newVersion = $settings->as($admin)->because('revert INC-7')->rollback('mail.from.address', 3); +``` + +Writes the value held at `$toVersion` as a new version, through the normal write pipeline; returns that version. Needs `rollback`, which `verification.abilities` lists by default. Throws `HistoryUnavailable`, `AccessDenied`, `VerificationRequired`, `LockedSetting`. Fires `SettingSaving`, `SettingSaved` and `SettingRolledBack`. See [Roll back a setting](../recipes/rolling-back-a-setting.md). + +## Approvals + +See [Approvals](approvals.md) and [Approve a change](../recipes/approving-a-change.md). + +### `propose()` + +```php +public function propose(string $key, mixed $value): ChangeRequest + +$request = $settings->as($author)->because('Q3 price change')->propose('billing.price', 49); +$request->id; // ULID +``` + +Opens a change request for a value instead of writing it, whether or not the setting needs approval. The value is validated now and stored as the values table would store it. Needs `update`. Throws `ApprovalUnavailable`, `InvalidSettingValue`. Fires `ChangeRequested`. + +### `approvals()` + +```php +public function approvals(): Approvals + +$approvals = $settings->as($reviewer)->approvals(); +$open = $approvals->pending()->key('billing.price')->get(); +$approvals->approve($open[0]->id, 'checked with finance'); +``` + +The store's change requests, decided as the handle's actor: `pending()`, `status(ChangeStatus)`, `key()`, `for($owner)`, then `get($limit, $after)` or `find($id)`; and `approve($id, $reason)`, `reject($id, $reason)`, `cancel($id, $reason)`, each returning the `ChangeRequest`. Approving needs `approve`; cancelling is the requester's. Throws `UnknownChangeRequest`, `ChangeRequestClosed`, `AccessDenied`. Fires `ChangeApproved`, then `ChangeApplied` (with `SettingSaved`) or `ChangeStale`; `ChangeRejected`; `ChangeCancelled`. + +## Store administration + +### `categories()` + +```php +public function categories(): CategoryManager + +$categories = $settings->as($admin)->categories(); +$categories->create(new NewCategory('billing', 'Billing', parent: 'general')); +$categories->rename('billing', 'Billing and invoices'); +$categories->move('billing', null); +$categories->all(); +``` + +The store's categories: `create(NewCategory)`, `rename()`, `move()`, `delete()`, `get()`, `all()`. Writes need `manage_categories`, reads `view`. Throws `UnknownCategory`, `CategoryCycle`, `CategoryStoreMismatch`. Fires `CategorySaving`, `CategorySaved`, `CategoryRenamed`, `CategoryMoved`, `CategoryDeleting`, `CategoryDeleted`. See [Categories](categories.md). + +### `promote()` + +```php +public function promote(?PromotionRequest $request = null): PromotionReport + +$report = $settings->asSystem('post-install')->promote(); +$report->promoted; // keys copied into the database +``` + +Copies the values written to the runtime file before the database existed into the database layer; shipped defaults are never copied. Idempotent. Needs `promote`. Throws `PromotionLocked`, `StoreNotWritable`, `AccessDenied`. Fires `StorePromoting` and `StorePromoted`. See [Move from files to the database](../recipes/moving-from-files-to-the-database.md). + +### `audit()` + +```php +public function audit(): AuditQuery + +$page = $settings->as($auditor)->audit()->key('mail.from.address')->since(now()->subMonth())->paginate(50); +``` + +The audit trail: `for()`, `global()`, `store()`, `key()`, `action(AuditAction)`, `outcome(AuditOutcome)`, `since()`, `until()`; then `get()`, `cursor()` or `paginate()`. Entries never hold values. Needs `view_audit`. See [Audit queries](audit-queries.md) and [Audit a change](../recipes/auditing-a-change.md). + +### `export()` + +```php +public function export(ExportMode $mode = ExportMode::Redacted): ExportDocument + +file_put_contents('settings.json', json_encode($settings->as($admin)->export()->toArray())); +``` + +The store as a portable document: categories by slug, settings by scope, key and locale. Encrypted values are left out (`Redacted`), kept as ciphertext (`Ciphertext`), or decrypted (`Plaintext`, needs `view_sensitive`). Needs `export`. See [Import and export](import-export.md). + +### `import()` and `previewImport()` + +```php +public function import(ExportDocument $document): ImportReport +public function previewImport(ExportDocument $document): ImportReport + +$document = ExportDocument::fromArray(json_decode(file_get_contents('settings.json'), true)); +$preview = $settings->as($admin)->previewImport($document); // nothing written +$report = $settings->as($admin)->because('copy from staging')->import($document); +``` + +Writes a document through the write pipeline, categories first, in one transaction; `previewImport()` reports what that would do without writing. Locks and system categories in the document are ignored here (the console's `--trusted` honours them). Needs `import` (verified by default). Throws `InvalidImport`, `AccessDenied`, `VerificationRequired`. Fires `SettingSaved` and the category events per write, or `ChangeRequested` for keys that need approval. + +### `compare()` + +```php +public function compare(ExportDocument $document): StoreDiff + +$diff = $settings->as($admin)->compare($document); +$diff->changed; // keys whose value differs, never the values +``` + +How the store differs from a document: `added`, `removed`, `changed`, `unchanged`, `unknown`. Needs `export`. + +### `persistedConfiguration()` + +```php +public function persistedConfiguration(): PersistedConfigurationEditor + +$editor = $settings->as($admin)->persistedConfiguration(); +$editor->saveStore('tenant_settings', ['layers' => ['database'], 'owners' => ['team']]); +$editor->saveDefinition('billing.plan', ['type' => 'string', 'default' => 'free']); +``` + +Stores and layers kept in the database, and definitions kept in the definitions table: `entries()`, `saveStore()`, `saveLayer()`, `deleteStore()`, `deleteLayer()`, `saveDefinition()`, `deleteDefinition()`. Needs `manage_stores` or `manage_definitions` and `configuration.persisted`. See [Persisted configuration](persisted-configuration.md). + +## Context + +### `actor()` + +```php +public function actor(): ?Actor + +$settings->as($user)->actor()?->id; +``` + +The handle's actor, or `null` for trusted code. + +### `configuration()` + +```php +public function configuration(): RuntimeConfiguration + +$settings->configuration()->define('beta.enabled')->ofType('boolean')->withDefault(false); +$settings->configuration()->authorizeUsing(fn ($actor, $ability, $subject) => …); +``` + +Configuration changed in code for the current request only: `addStore()`, `addLayer()`, `extendDriver()`, `define()`, `authorizeUsing()`, `verifyUsing()`, `resolveActorsUsing()`, `auditTo()`, `logTo()`, `requireActor()`, `allowActorless()`. See [Runtime configuration](runtime-configuration.md). + +### `withConfiguration()` + +```php +public function withConfiguration(callable $change, callable $run): mixed + +$value = $settings->withConfiguration( + fn (RuntimeConfiguration $config) => $config->requireActor(), + fn () => $settings->as($user)->get('billing.plan'), +); +``` + +Applies the changes for the duration of `$run` only, then restores them; returns `$run`'s result. + +## The facade + +`Simtabi\Laranail\Settings\Facades\Settings` proxies every method above (its docblock lists them for IDEs). It is application sugar; the package's own classes never use it. + +```php +use Simtabi\Laranail\Settings\Facades\Settings; + +Settings::for($user)->get('ui.theme', 'light'); +$fake = Settings::fake(); // see Test code that uses settings +``` + +## The `settings()` helper + +A namespaced function, never a global one: a bare global `settings()` is a name other packages and applications already define, and the second definition would silently win. + +```php +use function Simtabi\Laranail\Settings\settings; + +settings('site.name'); // get('site.name') +settings('site.tagline', 'Welcome'); // with a default +settings()->for($user)->set('ui.theme', 'dark'); // the handle +``` + +## `HasSettings` + +Makes an Eloquent model an owner. The model implements `Settable` and has a morph map entry. + +```php +use Simtabi\Laranail\Settings\Contracts\Settable; +use Simtabi\Laranail\Settings\Concerns\HasSettings; + +final class User extends Authenticatable implements Settable +{ + use HasSettings; + + public function settingsParents(): array + { + return OwnerRef::list(['team' => $this->team_id]); // optional: inherit from the team + } +} + +$user->settings()->get('ui.theme'); // Settings::for($user) +$user->settings()->as($user)->set('ui.theme', 'dark'); +User::query()->withSettings()->paginate(); // preloads every user on the page +``` + +| Member | Does | |---|---| -| `set($key, $value)` | validates, casts, encrypts if defined so, and writes to the first writable layer | -| `forget($key)` | removes this handle's own value, so reads fall through again | -| `lock($key)` / `unlock($key)` | refuses or allows further writes to this row | -| `flush()` | removes every value of the handle's owner in its store (needs `for($owner)`) | +| `settings()` | a handle for this model; rename it with `use HasSettings { settings as preferences; }` | +| `settingsOwner()` | the model as an `OwnerRef` (morph alias and key) | +| `settingsParents()` | owners to inherit from, nearest first; build from foreign keys so no model loads | +| `scopeWithSettings()` | eager-loads the settings of every model a query returns | +| deleting the model | flushes its settings; a soft-deleted model keeps them until force-deleted | -## Store-level operations +## Typed settings -| Method | Does | +A typed class reads and writes its properties through a handle, so everything above applies to it. See [Typed settings](typed-settings.md) and [Use typed settings](../recipes/using-typed-settings.md). + +```php +$mail = MailSettings::load($settings->as($admin)); +$mail->port = 587; +$mail->save(); +``` + +| Member | Does | |---|---| -| `preload($owners)` | loads many owners' settings in one read per store; see [Database](database.md) | -| `categories()` | the store's categories; see [Categories](categories.md) | -| `promote(?PromotionRequest)` | moves runtime-file values into the database; returns a `PromotionReport` | -| `clearCache()` | resets the cached values of the handle's owner, or of its whole store; see [Caching](caching.md) | -| `warmCache()` | loads the handle's scope (owner or global) into the cache now; returns the record count | -| `history()` | the value history of the handle's store, owner and locale (needs `view_history`); see [History](history.md) | -| `rollback($key, $toVersion)` | writes the value of an earlier version as a new version (needs `rollback`); returns the new version | -| `historyDiff($key, $from, $to)` | the value at two versions, decrypted only for an actor holding `view_sensitive` | -| `propose($key, $value)` | opens a change request for a value instead of writing it; returns the `ChangeRequest`; see [Approvals](approvals.md) | -| `approvals()` | the store's change requests: list, approve, reject, cancel | -| `export(ExportMode)` | the store as a portable document; see [Import and export](import-export.md) | -| `import($document)` / `previewImport($document)` | write a document through the write pipeline, or report what that would do | -| `compare($document)` | how the store differs from a document, by identity | -| `persistedConfiguration()` | stores, layers and definitions kept in the database; see [Persisted configuration](persisted-configuration.md) | - -Writes raise `UnknownSetting` (strict store, no definition), `OwnerNotAllowed`, `LockedSetting`, `InvalidSettingValue`, `EncryptionUnavailable` or `StoreNotWritable`. A handle with an actor can also raise `AccessDenied` or `VerificationRequired`, any handle `ActorRequired` (when an actor is required) and, for a setting that needs approval on a store that cannot hold change requests, `ApprovalUnavailable` (on one that can, the write opens a change request instead). `history()`, `rollback()` and `historyDiff()` raise `HistoryUnavailable` for a store that keeps no history or a version it does not hold. Every exception extends `SettingsException`. - -Each write is one action in `Simtabi\Laranail\Settings\Actions` (`SetSetting`, `ForgetSetting`, `LockSetting`, `UnlockSetting`), taking a DTO and the actor. The handle, the console commands and the [REST API](rest-api.md) all delegate to them, so behaviour cannot differ between them. [Typed settings](typed-settings.md) classes read and write through a handle. +| `TypedSettings::load(Settings $settings)` | reads every property's key through the handle | +| `$typed->save(?Settings $settings = null)` | writes the changed properties (all of them to another handle) through `set()` | +| `TypedSettings::register(DefinitionRegistry $registry)` | registers each property as a definition (type, default, encryption); `typed.classes` does it for you | +| `TypedSettings::properties()` | the property-to-key map | ## Keys -Keys are lower-case dot notation of `[a-z0-9_]` segments, at most 191 characters. They are lower-cased on input, so `Site.Name` and `site.name` are one key. +Keys are lower-case dot notation of `[a-z0-9_]` segments, at most 191 characters. They are lower-cased on input, so `Site.Name` and `site.name` are one key. A malformed key throws `InvalidKey`. + +## How the channels share one implementation + +Each write is one action in `Simtabi\Laranail\Settings\Actions` (`SetSetting`, `ForgetSetting`, `LockSetting`, `UnlockSetting`, …), taking a DTO and the actor. The handle, the console commands and the [REST API](rest-api.md) all delegate to them, so behaviour cannot differ between them; each REST controller method takes the action it runs as a parameter, and a test reading the live router holds the routes and the controllers to each other. --- diff --git a/docs/tools/typed-settings.md b/docs/tools/typed-settings.md index 435d469..659288b 100644 --- a/docs/tools/typed-settings.md +++ b/docs/tools/typed-settings.md @@ -38,7 +38,7 @@ $mail->save($settings->for($otherTeam)); // writes every pro `load()` reads each key through the handle, so the store, owner, locale and actor apply exactly as for `get()`, including the cascade and `view` / `view_sensitive`. `save()` writes each property that changed through `set()`: validation, casting, encryption, locks, approvals, history and audit all apply, as the handle's actor. A stored value the property cannot hold raises `TypeMismatch` naming the key. -Resolving a typed class from the container loads it through the request's settings handle. +Resolving a class listed in `typed.classes` from the container loads it through the request's settings handle; the package binds each listed class when the application boots. A class not listed is not bound: build it with `MailSettings::load(settings())`. ## Definitions diff --git a/helpers/helpers.php b/helpers/helpers.php new file mode 100644 index 0000000..d769059 --- /dev/null +++ b/helpers/helpers.php @@ -0,0 +1,39 @@ +for($user)->set('ui.theme', 'dark'); + * + * The package's own classes never call it; they take the contract through their constructors. + */ + +namespace Simtabi\Laranail\Settings; + +use Illuminate\Container\Container; +use Simtabi\Laranail\Settings\Contracts\Settings; + +if (! function_exists(__NAMESPACE__ . '\settings')) { + /** + * The settings handle with no key, else the value of `$key` (or `$default`), read as + * {@see Settings::get()} reads it. + * + * @return ($key is null ? Settings : mixed) + */ + function settings(?string $key = null, mixed $default = null): mixed + { + $settings = Container::getInstance()->make(Settings::class); + + return $key === null ? $settings : $settings->get($key, $default); + } +} diff --git a/resources/assets/.gitkeep b/resources/assets/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/resources/lang/en/settings.php b/resources/lang/en/settings.php new file mode 100644 index 0000000..be4fe3b --- /dev/null +++ b/resources/lang/en/settings.php @@ -0,0 +1,116 @@ + [ + 'titles' => [ + 'access-denied' => 'Access denied', + 'actor-required' => 'Actor required', + 'verification-required' => 'Verification required', + 'unknown-store' => 'Unknown store', + 'unknown-setting' => 'Unknown setting', + 'unknown-owner' => 'Unknown owner', + 'unknown-category' => 'Unknown category', + 'unknown-change-request' => 'Unknown change request', + 'invalid-value' => 'Invalid value', + 'invalid-identifier' => 'Invalid identifier', + 'invalid-import' => 'Invalid import', + 'invalid-definition' => 'Invalid definition', + 'invalid-configuration' => 'Invalid configuration', + 'type-mismatch' => 'Type mismatch', + 'category-cycle' => 'Category cycle', + 'category-store-mismatch' => 'Category store mismatch', + 'locked' => 'Locked', + 'precondition-failed' => 'Precondition failed', + 'approval-unavailable' => 'Approval unavailable', + 'change-request-closed' => 'Change request closed', + 'owner-not-allowed' => 'Owner not allowed', + 'store-not-writable' => 'Store not writable', + 'history-unavailable' => 'History unavailable', + 'unavailable' => 'Unavailable', + 'validation' => 'Validation', + 'unauthenticated' => 'Unauthenticated', + 'too-many-requests' => 'Too many requests', + 'settings-error' => 'Settings error', + ], + 'validation' => 'The request is invalid.', + 'unauthenticated' => 'Authentication is required.', + 'too-many-requests' => 'Too many requests.', + 'http' => 'The request failed.', + 'settings-error' => 'The settings operation failed.', + ], + + // The SettingsAlert notification (mail, Slack). Identifiers only: an alert never carries a value. + 'alert' => [ + 'labels' => [ + 'event' => 'Event', + 'store' => 'Store', + 'key' => 'Key', + 'scope' => 'Scope', + 'locale' => 'Locale', + 'actor' => 'Actor', + 'outcome' => 'Outcome', + 'at' => 'At', + ], + 'yes' => 'yes', + 'no' => 'no', + 'footer' => 'Values are never included in alerts; read the setting or its history to see what changed.', + ], + + // Artisan command output. + 'console' => [ + 'cache_reset' => 'Settings cache reset (:stores).', + 'cache_every_store' => 'every store', + 'cache_off' => 'Caching is off; nothing to reset.', + 'definitions_synced' => 'Synced :synced definition(s); removed :removed stale system row(s).', + 'definitions_skipped' => 'Store [:store] skipped: no active database layer, or the definitions table is off.', + 'definitions_conflict' => '[:key] is defined in code and edited in the table; code wins, the row was left alone.', + 'diff_none' => 'No differences (:unchanged setting(s) equal).', + 'diff_summary' => ':added to add, :removed only in the store, :changed changed, :unknown not comparable (redacted).', + 'history_none' => 'No history for [:key].', + 'history_diff_usage' => '--diff takes two versions, FROM..TO (for example 3..5).', + 'history_changed' => 'The value changed.', + 'history_same' => 'The value is the same.', + 'rollback_usage' => '--rollback takes a version number.', + 'rolled_back' => 'Rolled [:key] back to version :version; it is now at version :new.', + 'promoted' => 'Store [:store]: :promoted promoted, :skipped skipped.', + 'promote_archived' => 'The runtime file was archived as [:archive]; skipped entries remain there.', + 'orphans_unmapped' => 'Alias [:alias] has no model in the morph map; its settings were not checked.', + 'orphans_none' => 'No orphaned settings.', + 'orphans_dry_run' => ':count orphaned owner(s) found; nothing removed (dry run).', + 'orphans_removed' => 'Removed :removed row(s) of :count orphaned owner(s).', + 'warm_none' => 'No store is cached (caching is off, or no store has a database layer); nothing to warm.', + 'import_applied' => 'Imported:', + 'import_dry_run' => 'Dry run (add --apply to write):', + 'imported' => ':prefix :created created, :updated updated, :unchanged unchanged, :skipped skipped; :count category created.|:prefix :created created, :updated updated, :unchanged unchanged, :skipped skipped; :count categories created.', + 'import_skipped' => ':identity skipped: :reason', + 'import_proposed' => ':count setting(s) need approval: change requests :ids.', + 'store_created' => 'Created :path', + 'store_next_step' => 'Add this to your configuration, then run the migrations:', + 'audit_days_invalid' => 'The retention period must be a whole number of days.', + 'audit_pruned' => 'Removed :count audit entry older than :days day(s).|Removed :count audit entries older than :days day(s).', + 'changes_pruned' => 'Expired :expired change request(s); deleted :deleted decided one(s).', + 'history_invalid' => 'The retention period and the number of versions must be whole numbers.', + 'history_unconfigured' => 'No history retention is configured (history.keep_days and history.keep_versions are null); nothing to prune.', + 'history_pruned' => 'Removed :count history entry.|Removed :count history entries.', + 'export_confirm' => 'This writes decrypted secrets. Type the store name [:store] to continue', + 'export_mismatch' => 'The store name did not match; nothing was written.', + 'exported' => 'Exported :settings setting(s) and :count category of store [:store] to :path.|Exported :settings setting(s) and :count categories of store [:store] to :path.', + 'export_ciphertext' => 'Encrypted values are ciphertext: importable only under the same APP_KEY, or one listed in APP_PREVIOUS_KEYS.', + 'reencrypted' => 'Re-encrypted :values value(s), :count history entry and :changes change request(s).|Re-encrypted :values value(s), :count history entries and :changes change request(s).', + 'reencrypt_failed' => ':failed payload(s) could not be decrypted with the current or previous keys and were left as they were.', + 'rescoped' => 'Renamed [:from] to [:to] in :values value(s), :count history entry and :changes change request(s). Update the stores\' owners lists to match.|Renamed [:from] to [:to] in :values value(s), :count history entries and :changes change request(s). Update the stores\' owners lists to match.', + ], +]; diff --git a/resources/views/mail/alert.blade.php b/resources/views/mail/alert.blade.php new file mode 100644 index 0000000..3ea36df --- /dev/null +++ b/resources/views/mail/alert.blade.php @@ -0,0 +1,19 @@ +{{-- + laranail/settings::mail.alert -- the SettingsAlert mail (markdown). The notification hands it + identifiers only (headline, label => value lines, footer), never a setting's value, and the + text is already translated. Publish with --tag=laranail::settings-views to restyle it. +--}} + +# @lang('Hello!') + +{{ $headline }}. + +@foreach ($lines as $label => $value) +{{ $label }}: {{ $value }} + +@endforeach +{{ $footer }} + +@lang('Regards,')
+{{ config('app.name') }} +
diff --git a/routes/api.php b/routes/api.php new file mode 100644 index 0000000..7762ad3 --- /dev/null +++ b/routes/api.php @@ -0,0 +1,128 @@ +` switch leaves its group out when it is false. Every write passes the + * idempotency middleware. + */ + +$enabled = static fn (string $group): bool => config('laranail.settings.http.routes.' . $group, true) !== false; + +// A setting, addressed globally or for an owner: the same routes under two prefixes. +$settings = static function () use ($enabled): void { + Route::prefix('settings')->name('settings.')->group(static function () use ($enabled): void { + if ($enabled('settings')) { + Route::controller(SettingsController::class)->group(static function (): void { + Route::get('/', 'index')->name('index'); + Route::get('{key}', 'show')->name('show'); + Route::get('{key}/explain', 'explain')->name('explain'); + + Route::middleware(IdempotentWrites::class)->group(static function (): void { + Route::put('{key}', 'update')->name('update'); + Route::delete('{key}', 'destroy')->name('destroy'); + Route::post('{key}/lock', 'lock')->name('lock'); + Route::delete('{key}/lock', 'unlock')->name('unlock'); + }); + }); + } + + if ($enabled('history')) { + Route::controller(HistoryController::class)->group(static function (): void { + Route::get('{key}/history', 'index')->name('history'); + Route::post('{key}/rollback', 'rollback')->middleware(IdempotentWrites::class)->name('rollback'); + }); + } + }); +}; + +Route::prefix('stores')->group(static function () use ($enabled, $settings): void { + if ($enabled('stores')) { + Route::get('/', [StoresController::class, 'index'])->name('stores.index'); + } + + Route::prefix('{store}')->group(static function () use ($enabled, $settings): void { + $settings(); + + Route::prefix('owners/{alias}/{id}')->name('owners.')->group($settings); + + Route::prefix('definitions')->name('definitions.')->group(static function () use ($enabled): void { + if ($enabled('definitions')) { + Route::get('/', [StoresController::class, 'definitions'])->name('index'); + } + + if ($enabled('configuration')) { + Route::controller(ConfigurationController::class)->middleware(IdempotentWrites::class)->group(static function (): void { + Route::put('{key}', 'updateDefinition')->name('update'); + Route::delete('{key}', 'destroyDefinition')->name('destroy'); + }); + } + }); + + if ($enabled('approvals')) { + Route::controller(ChangesController::class)->prefix('changes')->name('changes.')->group(static function (): void { + Route::get('/', 'index')->name('index'); + Route::get('{id}', 'show')->name('show'); + + Route::middleware(IdempotentWrites::class)->group(static function (): void { + Route::post('/', 'store')->name('store'); + Route::post('{id}/approve', 'approve')->name('approve'); + Route::post('{id}/reject', 'reject')->name('reject'); + Route::post('{id}/cancel', 'cancel')->name('cancel'); + }); + }); + } + + if ($enabled('categories')) { + Route::controller(CategoriesController::class)->prefix('categories')->name('categories.')->group(static function (): void { + Route::get('/', 'index')->name('index'); + + Route::middleware(IdempotentWrites::class)->group(static function (): void { + Route::post('/', 'store')->name('store'); + Route::patch('{slug}', 'update')->name('update'); + Route::delete('{slug}', 'destroy')->name('destroy'); + }); + }); + } + + if ($enabled('transfer')) { + Route::controller(TransferController::class)->name('transfer.')->middleware(IdempotentWrites::class)->group(static function (): void { + Route::post('export', 'export')->name('export'); + Route::post('import', 'import')->name('import'); + Route::post('diff', 'diff')->name('diff'); + }); + } + }); +}); + +if ($enabled('audit')) { + Route::get('audit', [AuditController::class, 'index'])->name('audit.index'); +} + +if ($enabled('configuration')) { + Route::controller(ConfigurationController::class)->prefix('configuration')->name('configuration.')->group(static function (): void { + Route::get('/', 'index')->name('index'); + + Route::middleware(IdempotentWrites::class)->group(static function (): void { + Route::put('{kind}/{name}', 'update')->name('update'); + Route::delete('{kind}/{name}', 'destroy')->name('destroy'); + }); + }); +} diff --git a/routes/web.php b/routes/web.php new file mode 100644 index 0000000..a34436b --- /dev/null +++ b/routes/web.php @@ -0,0 +1,14 @@ +`. To opt in, add the + * route here and load the file from SettingsServiceProvider::packageBooted(), behind the + * `http.enabled` switch, with `$this->loadRoutesFrom($this->package->basePath('/routes/web.php'))`. + * An admin interface is a separate companion package, never this file. + */ diff --git a/src/Actions/Approvals/ApprovalActions.php b/src/Actions/Approvals/ApprovalActions.php deleted file mode 100644 index 0fa8851..0000000 --- a/src/Actions/Approvals/ApprovalActions.php +++ /dev/null @@ -1,21 +0,0 @@ -get($store->name, $decision->id); $key = new Key($request->key); - $definition = ($this->definitions)($store, $key); + $definition = $this->definitions->find($store, $key); $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), $definition); $now = CarbonImmutable::now(); diff --git a/src/Actions/Approvals/RejectChange.php b/src/Actions/Approvals/RejectChange.php index 9e11a38..31603b7 100644 --- a/src/Actions/Approvals/RejectChange.php +++ b/src/Actions/Approvals/RejectChange.php @@ -4,16 +4,13 @@ namespace Simtabi\Laranail\Settings\Actions\Approvals; -use Closure; use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Locale; use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; -use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Enums\Ability; -use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Enums\AuditOutcome; @@ -22,6 +19,7 @@ use Simtabi\Laranail\Settings\Events\ChangeRejected; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** @@ -30,11 +28,10 @@ */ final readonly class RejectChange { - /** @param Closure(Store, Key): ?Definition $definitions */ public function __construct( private AccessGuard $access, private Dispatcher $events, - private Closure $definitions, + private Definitions $definitions, ) {} /** @throws ChangeRequestClosed */ @@ -44,7 +41,7 @@ public function handle(ChangeDecision $decision, ?Actor $actor = null): ChangeRe $repository = ChangeRequestRepository::of($store); $request = $repository->get($store->name, $decision->id); $key = new Key($request->key); - $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), ($this->definitions)($store, $key)); + $subject = Subject::of($store->name, $key, new Locale($request->locale), $request->owner(), $this->definitions->find($store, $key)); $this->access->authorize($actor, Ability::Approve, $subject); diff --git a/src/Actions/Categories/CategoryActions.php b/src/Actions/Categories/CategoryActions.php deleted file mode 100644 index 9e4f05f..0000000 --- a/src/Actions/Categories/CategoryActions.php +++ /dev/null @@ -1,28 +0,0 @@ -)|null $persisted problems found in the persisted configuration */ public function __construct( private StoreRegistry $stores, - private ?SchemaShapeRepository $shapes = null, - private ?ValueEncrypter $encrypter = null, - private ?Closure $persisted = null, + private SchemaShapeRepository $shapes, + private LaravelValueEncrypter $encrypter, + private PersistedConfiguration $persisted, ) {} /** @return list */ public function handle(): array { - $findings = $this->shapes instanceof SchemaShapeRepository ? $this->schemaFile($this->shapes) : []; + $findings = $this->schemaFile($this->shapes); foreach ($this->stores->all() as $name => $store) { $database = $this->databaseOf($store); @@ -87,21 +86,17 @@ public function handle(): array $findings[] = $this->scopes($store, $database); $findings[] = $this->categories($store, $database); - if ($this->encrypter instanceof ValueEncrypter) { - $findings[] = $this->encryption($store, $database, $this->encrypter); - } + $findings[] = $this->encryption($store, $database, $this->encrypter); if ($database->shape()->changeRequestsTable) { $findings[] = $this->changeRequests($store, $database); } } - if ($this->persisted instanceof Closure) { - $problems = ($this->persisted)(); - $findings[] = new Finding('persisted configuration', 'Every persisted store and layer entry is valid', $problems === [] - ? DoctorResult::pass('Every persisted entry is valid (or persisted configuration is off).') - : DoctorResult::warn('Persisted entries skipped as invalid: ' . implode('; ', $problems), ['problems' => $problems])); - } + $problems = $this->persisted->problems(); + $findings[] = new Finding('persisted configuration', 'Every persisted store and layer entry is valid', $problems === [] + ? DoctorResult::pass('Every persisted entry is valid (or persisted configuration is off).') + : DoctorResult::warn('Persisted entries skipped as invalid: ' . implode('; ', $problems), ['problems' => $problems])); return $findings; } @@ -277,7 +272,7 @@ private function scopes(Store $store, DatabaseDriver $database): Finding * Encrypted values no current or previous key can read (a key rotated without `reencrypt`, * or with the old key dropped from APP_PREVIOUS_KEYS). The current tenant's rows. */ - private function encryption(Store $store, DatabaseDriver $database, ValueEncrypter $encrypter): Finding + private function encryption(Store $store, DatabaseDriver $database, LaravelValueEncrypter $encrypter): Finding { $unreadable = []; $encrypted = 0; diff --git a/src/Actions/FindOrphans.php b/src/Actions/FindOrphans.php index fea9ab7..519b130 100644 --- a/src/Actions/FindOrphans.php +++ b/src/Actions/FindOrphans.php @@ -4,10 +4,10 @@ namespace Simtabi\Laranail\Settings\Actions; -use Closure; use Illuminate\Database\Eloquent\Model; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; +use Illuminate\Database\Eloquent\Relations\Relation; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; @@ -20,10 +20,8 @@ */ final readonly class FindOrphans { - /** @param Closure(string): ?string $models the model class of a morph alias (the morph map) */ public function __construct( private StoreRegistry $stores, - private Closure $models, ) {} /** @@ -44,7 +42,7 @@ public function handle(): array } foreach ($store->owners as $alias) { - $model = ($this->models)($alias); + $model = Relation::getMorphedModel($alias); if ($model === null || ! is_subclass_of($model, Model::class)) { $unmapped[] = $alias; diff --git a/src/Actions/HistoryActions.php b/src/Actions/HistoryActions.php deleted file mode 100644 index 0e430ad..0000000 --- a/src/Actions/HistoryActions.php +++ /dev/null @@ -1,18 +0,0 @@ -scope->owner(); if ($to instanceof Store && $step->toKey instanceof Key && $record->payload !== null) { - $value = $this->pipeline->fromRecord($record, ($this->definitions)($from, $step->fromKey)); - $writer->set($to, $step->toKey, $record->locale, $owner, ($this->definitions)($to, $step->toKey), $value); + $value = $this->pipeline->fromRecord($record, $this->definitions->find($from, $step->fromKey)); + $writer->set($to, $step->toKey, $record->locale, $owner, $this->definitions->find($to, $step->toKey), $value); if ($record->locked) { $writer->lock($to, $step->toKey, $record->locale, $owner); @@ -98,7 +96,7 @@ public function handle(SettingsMigrationStep $step, ?Actor $actor = null): int private function add(Store $store, SettingsMigrationStep $step, SettingWriter $writer): int { - $writer->set($store, $step->fromKey, Locale::none(), null, ($this->definitions)($store, $step->fromKey), $step->value); + $writer->set($store, $step->fromKey, Locale::none(), null, $this->definitions->find($store, $step->fromKey), $step->value); return 1; } diff --git a/src/Actions/PromoteStore.php b/src/Actions/PromoteStore.php index e9afc5c..0fc8c7d 100644 --- a/src/Actions/PromoteStore.php +++ b/src/Actions/PromoteStore.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Actions; -use Closure; use Carbon\CarbonImmutable; -use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Record; @@ -29,6 +27,7 @@ use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; /** * Promote a store's runtime file into its database layer (design §7.4): needs `promote`. @@ -45,13 +44,12 @@ */ final readonly class PromoteStore { - /** @param Closure(Store, Key): ?Definition $definitions the definition a store has for a key */ public function __construct( private ValuePipeline $pipeline, private AccessGuard $access, private Dispatcher $events, private Caches $caches, - private Closure $definitions, + private Definitions $definitions, ) {} /** @@ -126,7 +124,7 @@ private function copy(Store $store, PromotionRequest $request, DatabaseDriver $d $skipped = []; foreach ($records as $record) { - $definition = ($this->definitions)($store, $record->key); + $definition = $this->definitions->find($store, $record->key); if (! $definition instanceof Definition && $store->strict) { $skipped[$record->identity()] = 'undefined'; diff --git a/src/Actions/PruneAudit.php b/src/Actions/PruneAudit.php index 5a64b29..f2dce56 100644 --- a/src/Actions/PruneAudit.php +++ b/src/Actions/PruneAudit.php @@ -26,15 +26,11 @@ */ final readonly class PruneAudit { - private AccessGuard $access; - public function __construct( private StoreRegistry $stores, - ?AccessGuard $access = null, - private ?Dispatcher $events = null, - ) { - $this->access = $access ?? AccessGuard::closed(); - } + private AccessGuard $access, + private Dispatcher $events, + ) {} public function handle(int $keepDays, ?Actor $actor = null): int { @@ -62,7 +58,7 @@ public function handle(int $keepDays, ?Actor $actor = null): int } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'audit', 'keep_days' => $keepDays, 'removed' => $removed]); - $this->events?->dispatch(new AuditPruned($removed, $keepDays)); + $this->events->dispatch(new AuditPruned($removed, $keepDays)); return $removed; } diff --git a/src/Actions/PruneOrphans.php b/src/Actions/PruneOrphans.php index b6e1413..8ba85c8 100644 --- a/src/Actions/PruneOrphans.php +++ b/src/Actions/PruneOrphans.php @@ -4,11 +4,9 @@ namespace Simtabi\Laranail\Settings\Actions; -use Closure; use Simtabi\Laranail\Settings\Data\Actor; use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\Subject; -use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; @@ -24,30 +22,13 @@ */ final readonly class PruneOrphans { - private AccessGuard $access; - - /** @param Closure(string): ?string $models the model class of a morph alias (the morph map) */ public function __construct( private StoreRegistry $stores, private FlushScope $flush, - private Closure $models, - ?AccessGuard $access = null, - private ?Dispatcher $events = null, - ) { - $this->access = $access ?? AccessGuard::closed(); - } - - /** - * The orphaned owners per store, and the aliases no model answers for. - * - * @deprecated 0.1 Use {@see FindOrphans::handle()}; this forwards to it and is removed in 1.0. - * - * @return array{orphans: array>, unmapped: list} - */ - public function find(): array - { - return $this->finder()->handle(); - } + private FindOrphans $find, + private AccessGuard $access, + private Dispatcher $events, + ) {} /** * Remove every orphan's settings; returns the number of rows removed. @@ -59,7 +40,7 @@ public function handle(?Actor $actor = null): int $removed = 0; $flushed = 0; - foreach ($this->finder()->handle()['orphans'] as $name => $owners) { + foreach ($this->find->handle()['orphans'] as $name => $owners) { $store = $this->stores->all()[$name]; foreach ($owners as $owner) { @@ -69,13 +50,8 @@ public function handle(?Actor $actor = null): int } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'orphans', 'owners' => $flushed, 'removed' => $removed]); - $this->events?->dispatch(new OrphansPruned($flushed, $removed)); + $this->events->dispatch(new OrphansPruned($flushed, $removed)); return $removed; } - - private function finder(): FindOrphans - { - return new FindOrphans($this->stores, $this->models); - } } diff --git a/src/Actions/Reads/ReadSettings.php b/src/Actions/Reads/ReadSettings.php index d00d04d..f584d53 100644 --- a/src/Actions/Reads/ReadSettings.php +++ b/src/Actions/Reads/ReadSettings.php @@ -9,6 +9,7 @@ use Simtabi\Laranail\Settings\Data\SettingView; use Simtabi\Laranail\Settings\Data\SettingAddress; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; +use Simtabi\Laranail\Settings\Services\Resolution\ScopeKeys; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; @@ -30,23 +31,7 @@ public function __construct( public function handle(SettingAddress $scope, ?Actor $actor = null, int $limit = 50, ?string $after = null): array { $store = $this->targets->store($scope->store); - $owner = Scope::of($scope->ownerRef()); - $keys = []; - - foreach ($store->load([$owner]) as $records) { - foreach ($records->all() as $record) { - $keys[$record->key->value] = true; - } - } - - foreach ($this->definitions->all() as $definition) { - if ($definition->store->value === $store->name->value) { - $keys[$definition->key->value] = true; - } - } - - $keys = array_keys($keys); - sort($keys); + $keys = new ScopeKeys($this->definitions)->keys($store, Scope::of($scope->ownerRef())); $keys = array_values(array_filter($keys, static fn (string $key): bool => $after === null || strcmp($key, $after) > 0)); $items = []; $last = null; diff --git a/src/Actions/ReencryptSettings.php b/src/Actions/ReencryptSettings.php index 85ea9a1..c2d7e83 100644 --- a/src/Actions/ReencryptSettings.php +++ b/src/Actions/ReencryptSettings.php @@ -10,10 +10,10 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; @@ -31,7 +31,7 @@ public function __construct( private StoreRegistry $stores, private AccessGuard $access, - private ValueEncrypter $encrypter, + private LaravelValueEncrypter $encrypter, ) {} /** @return array{values: int, history: int, changes: int, failed: int} */ diff --git a/src/Actions/SettingActions.php b/src/Actions/SettingActions.php deleted file mode 100644 index 32ba315..0000000 --- a/src/Actions/SettingActions.php +++ /dev/null @@ -1,39 +0,0 @@ - $report['removed'], 'conflicts' => count($report['conflicts']), ]); - $this->events?->dispatch(new DefinitionsSynced($report['synced'], $report['removed'], count($report['conflicts']), count($report['skipped']))); + $this->events->dispatch(new DefinitionsSynced($report['synced'], $report['removed'], count($report['conflicts']), count($report['skipped']))); return $report; } diff --git a/src/Actions/Transfer/ImportStore.php b/src/Actions/Transfer/ImportStore.php index 90d117a..a85e24a 100644 --- a/src/Actions/Transfer/ImportStore.php +++ b/src/Actions/Transfer/ImportStore.php @@ -4,8 +4,6 @@ namespace Simtabi\Laranail\Settings\Actions\Transfer; -use Closure; -use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Record; use Simtabi\Laranail\Settings\Data\Subject; @@ -13,7 +11,6 @@ use Simtabi\Laranail\Settings\Data\Category; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; -use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Data\CategorySlug; use Simtabi\Laranail\Settings\Data\SettingWrite; @@ -31,6 +28,7 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportedSetting; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Data\Transfer\ExportedCategory; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Services\Transfer\StoreSnapshots; use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; @@ -46,7 +44,6 @@ */ final readonly class ImportStore { - /** @param Closure(Store, Key): ?Definition $definitions */ public function __construct( private AccessGuard $access, private StoreSnapshots $snapshots, @@ -55,7 +52,7 @@ public function __construct( private SetSetting $set, private LockSetting $lock, private CreateCategory $createCategory, - private Closure $definitions, + private Definitions $definitions, ) {} public function handle(ImportRequest $request, ?Actor $actor = null): ImportReport @@ -192,7 +189,7 @@ private function categoriesToCreate(array $incoming, array $existing): array private function target(Store $store, ExportedSetting $setting, ?string $reason): SettingTarget { try { - $definition = ($this->definitions)($store, $setting->key); + $definition = $this->definitions->find($store, $setting->key); } catch (SettingsException) { $definition = null; } diff --git a/src/Actions/Transfer/TransferActions.php b/src/Actions/Transfer/TransferActions.php deleted file mode 100644 index 6129c7a..0000000 --- a/src/Actions/Transfer/TransferActions.php +++ /dev/null @@ -1,15 +0,0 @@ -requiresApproval) { // A store that can hold change requests turns the write into one (§16.7). - if ($this->proposer instanceof ProposeChange && $proposal instanceof ChangeProposal && $target->store->acceptsChangeRequests()) { + if ($proposal instanceof ChangeProposal && $target->store->acceptsChangeRequests()) { return $this->proposer->handle($proposal, $actor); } diff --git a/src/Approvals/Approvals.php b/src/Approvals/Approvals.php index 7e3dbc0..42a5e0e 100644 --- a/src/Approvals/Approvals.php +++ b/src/Approvals/Approvals.php @@ -15,9 +15,13 @@ use Simtabi\Laranail\Settings\Enums\ChangeStatus; use Simtabi\Laranail\Settings\Data\ChangeDecision; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Actions\Approvals\CancelChange; +use Simtabi\Laranail\Settings\Actions\Approvals\QueryChanges; +use Simtabi\Laranail\Settings\Actions\Approvals\RejectChange; use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; +use Simtabi\Laranail\Settings\Actions\Approvals\ApproveChange; use Simtabi\Laranail\Settings\Exceptions\UnknownChangeRequest; -use Simtabi\Laranail\Settings\Actions\Approvals\ApprovalActions; /** * The change requests of one store (§16.7), as the handle's actor: list them (`->pending()`, @@ -26,13 +30,24 @@ */ final readonly class Approvals { + /** The store and actor are set by {@see in()}; without them, the default store as trusted code. */ public function __construct( - private ApprovalActions $actions, - private Store $store, + private QueryChanges $query, + private ApproveChange $approve, + private RejectChange $reject, + private CancelChange $cancel, + private StoreRegistry $stores, + private ?Store $store = null, private ?Actor $actor = null, private ?ChangeFilter $filter = null, ) {} + /** These change requests: the store's, as this actor. */ + public function in(Store $store, ?Actor $actor = null): self + { + return new self($this->query, $this->approve, $this->reject, $this->cancel, $this->stores, $store, $actor); + } + /** Open requests only (pending, or approved and waiting for more approvals). */ public function pending(): self { @@ -61,7 +76,7 @@ public function for(Settable|OwnerRef $owner): self */ public function get(int $limit = 100, ?string $after = null): array { - return $this->actions->query->handle($this->filter(), $this->actor, $limit, $after); + return $this->query->handle($this->filter(), $this->actor, $limit, $after); } /** @@ -71,7 +86,7 @@ public function get(int $limit = 100, ?string $after = null): array */ public function find(string $id): ChangeRequest { - return $this->actions->query->handle(new ChangeFilter($this->store->name, id: $id), $this->actor, 1)[0] ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $this->store->name, $id)); + return $this->query->handle(new ChangeFilter($this->store()->name, id: $id), $this->actor, 1)[0] ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $this->store()->name, $id)); } /** @@ -80,28 +95,33 @@ public function find(string $id): ChangeRequest */ public function approve(string $id, ?string $reason = null): ChangeRequest { - return $this->actions->approve->handle(new ChangeDecision($this->store, $id, $reason), $this->actor); + return $this->approve->handle(new ChangeDecision($this->store(), $id, $reason), $this->actor); } /** @throws ChangeRequestClosed */ public function reject(string $id, ?string $reason = null): ChangeRequest { - return $this->actions->reject->handle(new ChangeDecision($this->store, $id, $reason), $this->actor); + return $this->reject->handle(new ChangeDecision($this->store(), $id, $reason), $this->actor); } /** @throws ChangeRequestClosed */ public function cancel(string $id, ?string $reason = null): ChangeRequest { - return $this->actions->cancel->handle(new ChangeDecision($this->store, $id, $reason), $this->actor); + return $this->cancel->handle(new ChangeDecision($this->store(), $id, $reason), $this->actor); } private function filter(): ChangeFilter { - return $this->filter ?? new ChangeFilter($this->store->name); + return $this->filter ?? new ChangeFilter($this->store()->name); + } + + private function store(): Store + { + return $this->store ?? $this->stores->default(); } private function with(ChangeFilter $filter): self { - return new self($this->actions, $this->store, $this->actor, $filter); + return new self($this->query, $this->approve, $this->reject, $this->cancel, $this->stores, $this->store, $this->actor, $filter); } } diff --git a/src/Categories/CategoryManager.php b/src/Categories/CategoryManager.php index e50f4de..27db5ba 100644 --- a/src/Categories/CategoryManager.php +++ b/src/Categories/CategoryManager.php @@ -14,8 +14,12 @@ use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Actions\Categories\MoveCategory; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; -use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; +use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; +use Simtabi\Laranail\Settings\Actions\Categories\DeleteCategory; +use Simtabi\Laranail\Settings\Actions\Categories\RenameCategory; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** @@ -25,25 +29,36 @@ */ final readonly class CategoryManager { + /** The store and actor are set by {@see in()}; without them, the default store as trusted code. */ public function __construct( - private Store $store, - private ?Actor $actor, - private CategoryActions $actions, + private CreateCategory $create, + private RenameCategory $rename, + private MoveCategory $move, + private DeleteCategory $delete, private AccessGuard $access, + private StoreRegistry $stores, + private ?Store $store = null, + private ?Actor $actor = null, ) {} + /** These categories: the store's, as this actor. */ + public function in(Store $store, ?Actor $actor = null): self + { + return new self($this->create, $this->rename, $this->move, $this->delete, $this->access, $this->stores, $store, $actor); + } + /** * @throws CategoryStoreMismatch * @throws UnknownCategory when the parent does not exist */ public function create(NewCategory $category): Category { - return $this->actions->create->handle($this->store, $category, $this->actor); + return $this->create->handle($this->store(), $category, $this->actor); } public function rename(string $slug, string $title): void { - $this->actions->rename->handle($this->store, $slug, $title, $this->actor); + $this->rename->handle($this->store(), $slug, $title, $this->actor); } /** @@ -52,12 +67,12 @@ public function rename(string $slug, string $title): void */ public function move(string $slug, ?string $parent): void { - $this->actions->move->handle($this->store, $slug, $parent, $this->actor); + $this->move->handle($this->store(), $slug, $parent, $this->actor); } public function delete(string $slug): void { - $this->actions->delete->handle($this->store, $slug, $this->actor); + $this->delete->handle($this->store(), $slug, $this->actor); } /** @throws UnknownCategory */ @@ -76,8 +91,13 @@ public function all(): array private function repository(?string $category): CategoryRepository { - $this->access->authorize($this->actor, Ability::View, new Subject($this->store->name, category: $category)); + $this->access->authorize($this->actor, Ability::View, new Subject($this->store()->name, category: $category)); - return CategoryRepository::of($this->store); + return CategoryRepository::of($this->store()); + } + + private function store(): Store + { + return $this->store ?? $this->stores->default(); } } diff --git a/src/Configuration/PersistedConfigurationEditor.php b/src/Configuration/PersistedConfigurationEditor.php index 942edd1..f461e6d 100644 --- a/src/Configuration/PersistedConfigurationEditor.php +++ b/src/Configuration/PersistedConfigurationEditor.php @@ -9,8 +9,13 @@ use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Data\ConfigurationEntry; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Actions\Configuration\ConfigurationActions; +use Simtabi\Laranail\Settings\Actions\Configuration\SaveDefinition; +use Simtabi\Laranail\Settings\Actions\Configuration\DeleteDefinition; +use Simtabi\Laranail\Settings\Actions\Configuration\SaveConfigurationEntry; +use Simtabi\Laranail\Settings\Actions\Configuration\DeleteConfigurationEntry; +use Simtabi\Laranail\Settings\Actions\Configuration\ListConfigurationEntries; /** * Persisted configuration (§16.11) edited as a handle's actor: stores and layers saved in the @@ -19,16 +24,28 @@ */ final readonly class PersistedConfigurationEditor { + /** The store and actor are set by {@see in()}; without them, the default store as trusted code. */ public function __construct( - private ConfigurationActions $actions, - private Store $store, + private ListConfigurationEntries $list, + private SaveConfigurationEntry $save, + private DeleteConfigurationEntry $delete, + private SaveDefinition $saveDefinition, + private DeleteDefinition $deleteDefinition, + private StoreRegistry $stores, + private ?Store $store = null, private ?Actor $actor = null, ) {} + /** This configuration, with the store's definitions, as this actor. */ + public function in(Store $store, ?Actor $actor = null): self + { + return new self($this->list, $this->save, $this->delete, $this->saveDefinition, $this->deleteDefinition, $this->stores, $store, $actor); + } + /** @return list */ public function entries(): array { - return $this->actions->list->handle($this->actor); + return $this->list->handle($this->actor); } /** @@ -38,7 +55,7 @@ public function entries(): array */ public function saveStore(string $name, array $config): void { - $this->actions->save->handle(new ConfigurationEntry(ConfigurationEntry::STORE, $name, $config), $this->actor); + $this->save->handle(new ConfigurationEntry(ConfigurationEntry::STORE, $name, $config), $this->actor); } /** @@ -48,17 +65,17 @@ public function saveStore(string $name, array $config): void */ public function saveLayer(string $name, array $config): void { - $this->actions->save->handle(new ConfigurationEntry(ConfigurationEntry::LAYER, $name, $config), $this->actor); + $this->save->handle(new ConfigurationEntry(ConfigurationEntry::LAYER, $name, $config), $this->actor); } public function deleteStore(string $name): bool { - return $this->actions->delete->handle(new ConfigurationEntry(ConfigurationEntry::STORE, $name), $this->actor); + return $this->delete->handle(new ConfigurationEntry(ConfigurationEntry::STORE, $name), $this->actor); } public function deleteLayer(string $name): bool { - return $this->actions->delete->handle(new ConfigurationEntry(ConfigurationEntry::LAYER, $name), $this->actor); + return $this->delete->handle(new ConfigurationEntry(ConfigurationEntry::LAYER, $name), $this->actor); } /** @@ -68,11 +85,16 @@ public function deleteLayer(string $name): bool */ public function saveDefinition(string $key, array $attributes): Definition { - return $this->actions->saveDefinition->handle($this->store, $key, $attributes, $this->actor); + return $this->saveDefinition->handle($this->store(), $key, $attributes, $this->actor); } public function deleteDefinition(string $key): bool { - return $this->actions->deleteDefinition->handle($this->store, $key, $this->actor); + return $this->deleteDefinition->handle($this->store(), $key, $this->actor); + } + + private function store(): Store + { + return $this->store ?? $this->stores->default(); } } diff --git a/src/Console/ClearCacheCommand.php b/src/Console/ClearCacheCommand.php index 2a4f2e2..046b356 100644 --- a/src/Console/ClearCacheCommand.php +++ b/src/Console/ClearCacheCommand.php @@ -41,7 +41,7 @@ public function handle(ClearCache $clear, StoreRegistry $registry): int return self::FAILURE; } - $this->info($cleared ? sprintf('Settings cache reset (%s).', $names === [] ? 'every store' : implode(', ', $names)) : 'Caching is off; nothing to reset.'); + $this->info($cleared ? __('laranail/settings::settings.console.cache_reset', ['stores' => $names === [] ? __('laranail/settings::settings.console.cache_every_store') : implode(', ', $names)]) : __('laranail/settings::settings.console.cache_off')); return self::SUCCESS; } diff --git a/src/Console/DiffCommand.php b/src/Console/DiffCommand.php index 4143d2f..c905ec6 100644 --- a/src/Console/DiffCommand.php +++ b/src/Console/DiffCommand.php @@ -9,10 +9,10 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Console\Tools\Commands\Command; use Simtabi\Laranail\Settings\Exceptions\InvalidImport; +use Simtabi\Laranail\Settings\Actions\Transfer\DiffStore; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Actions\Transfer\TransferActions; use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** @@ -29,7 +29,7 @@ final class DiffCommand extends Command protected $description = 'Compare a settings store with an export file'; - public function handle(TransferActions $transfer, StoreRegistry $stores, Filesystem $files): int + public function handle(DiffStore $diffStore, StoreRegistry $stores, Filesystem $files): int { $path = $this->argument('path'); $path = is_string($path) ? $path : ''; @@ -42,7 +42,7 @@ public function handle(TransferActions $transfer, StoreRegistry $stores, Filesys throw new InvalidImport(sprintf('[%s] is not a file.', $path)); } - $diff = $transfer->diff->handle($store, ExportDocument::fromJson($files->get($path)), Actor::system('laranail::settings.diff')); + $diff = $diffStore->handle($store, ExportDocument::fromJson($files->get($path)), Actor::system('laranail::settings.diff')); } catch (SettingsException $exception) { $this->error($exception->getMessage()); @@ -56,8 +56,8 @@ public function handle(TransferActions $transfer, StoreRegistry $stores, Filesys } $this->info($diff->isEmpty() - ? sprintf('No differences (%d setting(s) equal).', count($diff->unchanged)) - : sprintf('%d to add, %d only in the store, %d changed, %d not comparable (redacted).', count($diff->added), count($diff->removed), count($diff->changed), count($diff->unknown))); + ? __('laranail/settings::settings.console.diff_none', ['unchanged' => count($diff->unchanged)]) + : __('laranail/settings::settings.console.diff_summary', ['added' => count($diff->added), 'removed' => count($diff->removed), 'changed' => count($diff->changed), 'unknown' => count($diff->unknown)])); return $diff->isEmpty() ? self::SUCCESS : self::FAILURE; } diff --git a/src/Console/DoctorCommand.php b/src/Console/DoctorCommand.php index e50a618..a01ea71 100644 --- a/src/Console/DoctorCommand.php +++ b/src/Console/DoctorCommand.php @@ -34,7 +34,7 @@ public function handle(DiagnoseSettings $diagnose, SyncDefinitions $sync): int if ($this->option('fix') === true) { try { $report = $sync->handle(Actor::system('laranail::settings.doctor')); - $this->info(sprintf('Synced %d definition(s); removed %d stale system row(s).', $report['synced'], $report['removed'])); + $this->info(__('laranail/settings::settings.console.definitions_synced', ['synced' => $report['synced'], 'removed' => $report['removed']])); } catch (SettingsException $exception) { $this->error($exception->getMessage()); diff --git a/src/Console/ExportCommand.php b/src/Console/ExportCommand.php index 5ddb914..ba8b5a4 100644 --- a/src/Console/ExportCommand.php +++ b/src/Console/ExportCommand.php @@ -53,10 +53,10 @@ public function handle(Settings $settings, Filesystem $files): int if ($mode === ExportMode::Plaintext) { $confirm = $this->option('confirm'); - $typed = is_string($confirm) ? $confirm : $this->ask(sprintf('This writes decrypted secrets. Type the store name [%s] to continue', $document->store)); + $typed = is_string($confirm) ? $confirm : $this->ask(__('laranail/settings::settings.console.export_confirm', ['store' => $document->store])); if ($typed !== ($name ?? $document->store)) { - $this->error('The store name did not match; nothing was written.'); + $this->error(__('laranail/settings::settings.console.export_mismatch')); return self::FAILURE; } @@ -66,10 +66,10 @@ public function handle(Settings $settings, Filesystem $files): int if (is_string($path) && $path !== '') { $files->put($path, $document->toJson()); - $this->info(sprintf('Exported %d setting(s) and %d categor%s of store [%s] to %s.', count($document->settings), count($document->categories), count($document->categories) === 1 ? 'y' : 'ies', $document->store, $path)); + $this->info(trans_choice('laranail/settings::settings.console.exported', count($document->categories), ['settings' => count($document->settings), 'store' => $document->store, 'path' => $path])); if ($mode === ExportMode::Ciphertext) { - $this->comment('Encrypted values are ciphertext: importable only under the same APP_KEY, or one listed in APP_PREVIOUS_KEYS.'); + $this->comment(__('laranail/settings::settings.console.export_ciphertext')); } return self::SUCCESS; diff --git a/src/Console/HistoryCommand.php b/src/Console/HistoryCommand.php index dbf29a8..d89b5a8 100644 --- a/src/Console/HistoryCommand.php +++ b/src/Console/HistoryCommand.php @@ -82,7 +82,7 @@ private function list(Settings $settings, string $key): int $entries = $settings->history()->key($key)->get(is_string($limit) && ctype_digit($limit) ? (int) $limit : 20); if ($entries === []) { - $this->info(sprintf('No history for [%s].', $key)); + $this->info(__('laranail/settings::settings.console.history_none', ['key' => $key])); return self::SUCCESS; } @@ -106,7 +106,7 @@ private function list(Settings $settings, string $key): int private function diff(Settings $settings, string $key, string $range): int { if (preg_match('/^(\d+)\.\.(\d+)$/', $range, $versions) !== 1) { - $this->error('--diff takes two versions, FROM..TO (for example 3..5).'); + $this->error(__('laranail/settings::settings.console.history_diff_usage')); return self::FAILURE; } @@ -121,7 +121,7 @@ private function diff(Settings $settings, string $key, string $range): int $this->line(sprintf('v%d: %s', $diff->fromVersion, $show($diff->from, $diff->fromFound))); $this->line(sprintf('v%d: %s', $diff->toVersion, $show($diff->to, $diff->toFound))); - $this->info($diff->changed ? 'The value changed.' : 'The value is the same.'); + $this->info($diff->changed ? __('laranail/settings::settings.console.history_changed') : __('laranail/settings::settings.console.history_same')); return self::SUCCESS; } @@ -129,13 +129,13 @@ private function diff(Settings $settings, string $key, string $range): int private function rollback(Settings $settings, string $key, string $version): int { if (! ctype_digit($version) || (int) $version < 1) { - $this->error('--rollback takes a version number.'); + $this->error(__('laranail/settings::settings.console.rollback_usage')); return self::FAILURE; } $new = $settings->rollback($key, (int) $version); - $this->info(sprintf('Rolled [%s] back to version %d; it is now at version %d.', $key, (int) $version, $new)); + $this->info(__('laranail/settings::settings.console.rolled_back', ['key' => $key, 'version' => (int) $version, 'new' => $new])); return self::SUCCESS; } diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php index c32029e..058cb30 100644 --- a/src/Console/ImportCommand.php +++ b/src/Console/ImportCommand.php @@ -12,10 +12,10 @@ use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; use Simtabi\Laranail\Settings\Data\Transfer\ImportRequest; use Simtabi\Laranail\Settings\Services\Transfer\Importers; +use Simtabi\Laranail\Settings\Actions\Transfer\ImportStore; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Actions\Transfer\TransferActions; use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** @@ -38,7 +38,7 @@ final class ImportCommand extends Command protected $description = 'Import settings from an export file or another package (dry run by default)'; - public function handle(TransferActions $transfer, StoreRegistry $stores, Importers $importers, Filesystem $files): int + public function handle(ImportStore $import, StoreRegistry $stores, Importers $importers, Filesystem $files): int { $source = $this->argument('source'); $source = is_string($source) ? $source : ''; @@ -58,7 +58,7 @@ public function handle(TransferActions $transfer, StoreRegistry $stores, Importe $document = ExportDocument::fromJson($files->get($source)); } - $report = $transfer->import->handle(new ImportRequest( + $report = $import->handle(new ImportRequest( $store, $document, apply: $this->option('apply') === true, @@ -78,27 +78,24 @@ public function handle(TransferActions $transfer, StoreRegistry $stores, Importe private function report(ImportReport $report): void { - $this->info(sprintf( - '%s %d created, %d updated, %d unchanged, %d skipped; %d categor%s created.', - $report->applied ? 'Imported:' : 'Dry run (add --apply to write):', - count($report->created), - count($report->updated), - count($report->unchanged), - count($report->skipped), - count($report->categories), - count($report->categories) === 1 ? 'y' : 'ies', - )); + $this->info(trans_choice('laranail/settings::settings.console.imported', count($report->categories), [ + 'prefix' => $report->applied ? __('laranail/settings::settings.console.import_applied') : __('laranail/settings::settings.console.import_dry_run'), + 'created' => count($report->created), + 'updated' => count($report->updated), + 'unchanged' => count($report->unchanged), + 'skipped' => count($report->skipped), + ])); foreach ([...array_map(static fn (string $id): string => '+ ' . $id, $report->created), ...array_map(static fn (string $id): string => '~ ' . $id, $report->updated)] as $line) { $this->line(' ' . $line); } foreach ($report->skipped as $identity => $reason) { - $this->line(sprintf(' ! %s skipped: %s', $identity, $reason)); + $this->line(' ! ' . __('laranail/settings::settings.console.import_skipped', ['identity' => $identity, 'reason' => $reason])); } if ($report->proposed !== []) { - $this->comment(sprintf('%d setting(s) need approval: change requests %s.', count($report->proposed), implode(', ', $report->proposed))); + $this->comment(__('laranail/settings::settings.console.import_proposed', ['count' => count($report->proposed), 'ids' => implode(', ', $report->proposed)])); } } } diff --git a/src/Console/MakeStoreCommand.php b/src/Console/MakeStoreCommand.php index 2cbab7f..3bb3931 100644 --- a/src/Console/MakeStoreCommand.php +++ b/src/Console/MakeStoreCommand.php @@ -44,11 +44,11 @@ public function handle(MakeStore $make): int } foreach ($generated->migrations as $path) { - $this->info('Created ' . $path); + $this->info(__('laranail/settings::settings.console.store_created', ['path' => $path])); } $this->newLine(); - $this->line('Add this to your configuration, then run the migrations:'); + $this->line(__('laranail/settings::settings.console.store_next_step')); $this->newLine(); $this->line($generated->config); diff --git a/src/Console/OpenApiCommand.php b/src/Console/OpenApiCommand.php deleted file mode 100644 index e4ff35c..0000000 --- a/src/Console/OpenApiCommand.php +++ /dev/null @@ -1,52 +0,0 @@ -getRoutes()->getRoutes(), static fn (Route $route): bool => str_starts_with((string) $route->getName(), ApiRoutes::NAME_PREFIX)); - - if ($routes === []) { - $this->error('The settings REST API is off: set laranail.settings.http.enabled to true first.'); - - return self::FAILURE; - } - - $json = json_encode(OpenApiDocument::build($routes), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n"; - $output = $this->option('output'); - - if (is_string($output) && $output !== '') { - $files->put($output, $json); - $this->info(sprintf('Wrote the OpenAPI document (%d operation(s)) to %s.', count($routes), $output)); - - return self::SUCCESS; - } - - $this->output->write($json); - - return self::SUCCESS; - } -} diff --git a/src/Console/PromoteCommand.php b/src/Console/PromoteCommand.php index 4a44192..841d553 100644 --- a/src/Console/PromoteCommand.php +++ b/src/Console/PromoteCommand.php @@ -44,7 +44,7 @@ public function handle(Settings $settings): int return self::FAILURE; } - $this->info(sprintf('Store [%s]: %d promoted, %d skipped.', $report->store, count($report->promoted), count($report->skipped))); + $this->info(__('laranail/settings::settings.console.promoted', ['store' => $report->store, 'promoted' => count($report->promoted), 'skipped' => count($report->skipped)])); if ($report->skipped !== []) { $this->table(['Setting (scope|key|locale)', 'Skipped because'], array_map( @@ -55,7 +55,7 @@ public function handle(Settings $settings): int } if ($report->archive !== null) { - $this->line(sprintf('The runtime file was archived as [%s]; skipped entries remain there.', $report->archive)); + $this->line(__('laranail/settings::settings.console.promote_archived', ['archive' => $report->archive])); } return self::SUCCESS; diff --git a/src/Console/PruneAuditCommand.php b/src/Console/PruneAuditCommand.php index 5e3cf67..02be5aa 100644 --- a/src/Console/PruneAuditCommand.php +++ b/src/Console/PruneAuditCommand.php @@ -27,7 +27,7 @@ public function handle(PruneAudit $prune, Repository $config): int $days = $this->option('days') ?? $config->get('laranail.settings.audit.keep_days', 365); if (! is_int($days) && (! is_string($days) || ! ctype_digit($days))) { - $this->error('The retention period must be a whole number of days.'); + $this->error(__('laranail/settings::settings.console.audit_days_invalid')); return self::FAILURE; } @@ -40,7 +40,7 @@ public function handle(PruneAudit $prune, Repository $config): int return self::FAILURE; } - $this->info(sprintf('Removed %d audit entr%s older than %d day(s).', $removed, $removed === 1 ? 'y' : 'ies', (int) $days)); + $this->info(trans_choice('laranail/settings::settings.console.audit_pruned', $removed, ['days' => (int) $days])); return self::SUCCESS; } diff --git a/src/Console/PruneChangesCommand.php b/src/Console/PruneChangesCommand.php index a138a96..db6e63a 100644 --- a/src/Console/PruneChangesCommand.php +++ b/src/Console/PruneChangesCommand.php @@ -7,7 +7,7 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Console\Tools\Commands\Command; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -use Simtabi\Laranail\Settings\Actions\Approvals\ApprovalActions; +use Simtabi\Laranail\Settings\Actions\Approvals\PruneChanges; use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** @@ -23,17 +23,17 @@ final class PruneChangesCommand extends Command protected $description = 'Expire overdue change requests and delete old decided ones'; - public function handle(ApprovalActions $approvals): int + public function handle(PruneChanges $prune): int { try { - $result = $approvals->prune->handle(Actor::system('laranail::settings.prune-changes')); + $result = $prune->handle(Actor::system('laranail::settings.prune-changes')); } catch (SettingsException $exception) { $this->error($exception->getMessage()); return self::FAILURE; } - $this->info(sprintf('Expired %d change request(s); deleted %d decided one(s).', $result['expired'], $result['deleted'])); + $this->info(__('laranail/settings::settings.console.changes_pruned', ['expired' => $result['expired'], 'deleted' => $result['deleted']])); return self::SUCCESS; } diff --git a/src/Console/PruneHistoryCommand.php b/src/Console/PruneHistoryCommand.php index c0374ae..32ce7a6 100644 --- a/src/Console/PruneHistoryCommand.php +++ b/src/Console/PruneHistoryCommand.php @@ -32,13 +32,13 @@ public function handle(PruneHistory $prune, Repository $config): int $versions = $this->number($this->option('versions') ?? $config->get('laranail.settings.history.keep_versions')); if ($days === false || $versions === false) { - $this->error('The retention period and the number of versions must be whole numbers.'); + $this->error(__('laranail/settings::settings.console.history_invalid')); return self::FAILURE; } if ($days === null && $versions === null) { - $this->info('No history retention is configured (history.keep_days and history.keep_versions are null); nothing to prune.'); + $this->info(__('laranail/settings::settings.console.history_unconfigured')); return self::SUCCESS; } @@ -51,7 +51,7 @@ public function handle(PruneHistory $prune, Repository $config): int return self::FAILURE; } - $this->info(sprintf('Removed %d history entr%s.', $removed, $removed === 1 ? 'y' : 'ies')); + $this->info(trans_choice('laranail/settings::settings.console.history_pruned', $removed)); return self::SUCCESS; } diff --git a/src/Console/PruneOrphansCommand.php b/src/Console/PruneOrphansCommand.php index 417227d..f39680f 100644 --- a/src/Console/PruneOrphansCommand.php +++ b/src/Console/PruneOrphansCommand.php @@ -29,7 +29,7 @@ public function handle(PruneOrphans $prune, FindOrphans $find): int $found = $find->handle(); foreach ($found['unmapped'] as $alias) { - $this->warn(sprintf('Alias [%s] has no model in the morph map; its settings were not checked.', $alias)); + $this->warn(__('laranail/settings::settings.console.orphans_unmapped', ['alias' => $alias])); } $rows = []; @@ -41,7 +41,7 @@ public function handle(PruneOrphans $prune, FindOrphans $find): int } if ($rows === []) { - $this->info('No orphaned settings.'); + $this->info(__('laranail/settings::settings.console.orphans_none')); return self::SUCCESS; } @@ -49,7 +49,7 @@ public function handle(PruneOrphans $prune, FindOrphans $find): int $this->table(['Store', 'Scope'], $rows); if ($this->option('dry-run') === true) { - $this->info(sprintf('%d orphaned owner(s) found; nothing removed (dry run).', count($rows))); + $this->info(__('laranail/settings::settings.console.orphans_dry_run', ['count' => count($rows)])); return self::SUCCESS; } @@ -61,7 +61,7 @@ public function handle(PruneOrphans $prune, FindOrphans $find): int return self::FAILURE; } - $this->info(sprintf('Removed %d row(s) of %d orphaned owner(s).', $removed, count($rows))); + $this->info(__('laranail/settings::settings.console.orphans_removed', ['removed' => $removed, 'count' => count($rows)])); return self::SUCCESS; } diff --git a/src/Console/ReencryptCommand.php b/src/Console/ReencryptCommand.php index b97a392..3c5e938 100644 --- a/src/Console/ReencryptCommand.php +++ b/src/Console/ReencryptCommand.php @@ -33,10 +33,10 @@ public function handle(ReencryptSettings $reencrypt): int return self::FAILURE; } - $this->info(sprintf('Re-encrypted %d value(s), %d history entr%s and %d change request(s).', $result['values'], $result['history'], $result['history'] === 1 ? 'y' : 'ies', $result['changes'])); + $this->info(trans_choice('laranail/settings::settings.console.reencrypted', $result['history'], ['values' => $result['values'], 'changes' => $result['changes']])); if ($result['failed'] > 0) { - $this->error(sprintf('%d payload(s) could not be decrypted with the current or previous keys and were left as they were.', $result['failed'])); + $this->error(__('laranail/settings::settings.console.reencrypt_failed', ['failed' => $result['failed']])); return self::FAILURE; } diff --git a/src/Console/RescopeCommand.php b/src/Console/RescopeCommand.php index 0579f8b..937b6a5 100644 --- a/src/Console/RescopeCommand.php +++ b/src/Console/RescopeCommand.php @@ -39,7 +39,7 @@ public function handle(RescopeOwners $rescope): int return self::FAILURE; } - $this->info(sprintf('Renamed [%s] to [%s] in %d value(s), %d history entr%s and %d change request(s). Update the stores\' owners lists to match.', $from, $to, $result['values'], $result['history'], $result['history'] === 1 ? 'y' : 'ies', $result['changes'])); + $this->info(trans_choice('laranail/settings::settings.console.rescoped', $result['history'], ['from' => $from, 'to' => $to, 'values' => $result['values'], 'changes' => $result['changes']])); return self::SUCCESS; } diff --git a/src/Console/SyncDefinitionsCommand.php b/src/Console/SyncDefinitionsCommand.php index 8493fd8..e47fd01 100644 --- a/src/Console/SyncDefinitionsCommand.php +++ b/src/Console/SyncDefinitionsCommand.php @@ -34,14 +34,14 @@ public function handle(SyncDefinitions $sync): int } foreach ($report['skipped'] as $store) { - $this->line(sprintf('Store [%s] skipped: no active database layer, or the definitions table is off.', $store)); + $this->line(__('laranail/settings::settings.console.definitions_skipped', ['store' => $store])); } foreach ($report['conflicts'] as $key) { - $this->warn(sprintf('[%s] is defined in code and edited in the table; code wins, the row was left alone.', $key)); + $this->warn(__('laranail/settings::settings.console.definitions_conflict', ['key' => $key])); } - $this->info(sprintf('Synced %d definition(s); removed %d stale system row(s).', $report['synced'], $report['removed'])); + $this->info(__('laranail/settings::settings.console.definitions_synced', ['synced' => $report['synced'], 'removed' => $report['removed']])); return self::SUCCESS; } diff --git a/src/Console/WarmCacheCommand.php b/src/Console/WarmCacheCommand.php index eb8c36a..17e9109 100644 --- a/src/Console/WarmCacheCommand.php +++ b/src/Console/WarmCacheCommand.php @@ -43,7 +43,7 @@ public function handle(WarmCache $warm, StoreRegistry $registry): int } if ($rows === []) { - $this->info('No store is cached (caching is off, or no store has a database layer); nothing to warm.'); + $this->info(__('laranail/settings::settings.console.warm_none')); return self::SUCCESS; } diff --git a/src/Contracts/BootstrapEvidence.php b/src/Contracts/BootstrapEvidence.php deleted file mode 100644 index 5b63188..0000000 --- a/src/Contracts/BootstrapEvidence.php +++ /dev/null @@ -1,15 +0,0 @@ - $tables */ - public function isReady(?string $connection, array $tables): bool; - - /** Forget memoised answers, so the next call looks again (after migrations, per request). */ - public function flush(): void; -} diff --git a/src/Contracts/Settings.php b/src/Contracts/Settings.php index 9395c32..f53acd3 100644 --- a/src/Contracts/Settings.php +++ b/src/Contracts/Settings.php @@ -9,6 +9,7 @@ use Simtabi\Laranail\Settings\Data\Lookup; use Simtabi\Laranail\Settings\Data\OwnerRef; use Illuminate\Contracts\Auth\Authenticatable; +use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Audit\AuditQuery; use Simtabi\Laranail\Settings\Data\HistoryDiff; use Simtabi\Laranail\Settings\Enums\ExportMode; @@ -17,6 +18,7 @@ use Simtabi\Laranail\Settings\Data\PromotionReport; use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Data\PromotionRequest; +use Simtabi\Laranail\Settings\Exceptions\InvalidKey; use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; @@ -100,11 +102,49 @@ public function get(string $key, mixed $default = null): mixed; * Presence-aware read: found (value possibly null) or missing. * * @throws AccessDenied when the actor may not view the key (or, for a sensitive key, its value) + * @throws UnknownSetting when the store is strict and has no definition for the key */ public function lookup(string $key): Lookup; public function has(string $key): bool; + /** The opposite of {@see has()}: true when nothing is stored and the definition has no default. */ + public function missing(string $key): bool; + + /** + * Several values at once, keyed as asked. Pass a list of keys, or `key => default` pairs, or + * both: `many(['site.name', 'site.tagline' => 'Welcome'])`. Each key is read (and authorized) + * exactly as {@see get()} reads it. + * + * @param array $keys + * + * @return array + * + * @throws InvalidKey when a list entry is not a string + * @throws AccessDenied + */ + public function many(array $keys): array; + + /** + * Every value this handle can see in its store and scope, by key, in key order: each key the + * scope holds in any layer, and each key a code or config definition of the store names. A key + * the actor may not view (or, when sensitive, may not read) is left out, not masked, as the + * REST API's listing leaves it out. `$prefix` keeps only `prefix` itself and the keys below it. + * + * @return array + */ + public function all(?string $prefix = null): array; + + /** + * The definitions of this handle's store (code, configuration and the definitions table), in + * key order: what a UI renders a form from. Needs `view` on the store. + * + * @return list + * + * @throws AccessDenied + */ + public function definitions(): array; + /** @throws TypeMismatch */ public function string(string $key): string; @@ -143,6 +183,30 @@ public function set(string $key, mixed $value): void; /** Remove this handle's own value, so reads fall through again. */ public function forget(string $key): void; + /** + * Write several values, one {@see set()} each, in the order given. Not atomic: each write is + * its own transaction, and the first refusal stops the rest (earlier writes stay). + * + * @param array $values + */ + public function setMany(array $values): void; + + /** + * Remove several of this handle's own values, one {@see forget()} each, in the order given. + * + * @param iterable $keys + */ + public function forgetMany(iterable $keys): void; + + /** + * The stored value, or, when nothing is found, `$value()` written with {@see set()} and read + * back (so the answer is cast exactly as a later read would be). A write that opens a change + * request leaves the value unwritten; the read then falls back to the computed value. + * + * @param callable(): mixed $value + */ + public function remember(string $key, callable $value): mixed; + public function lock(string $key): void; public function unlock(string $key): void; diff --git a/src/Contracts/ValueEncrypter.php b/src/Contracts/ValueEncrypter.php deleted file mode 100644 index 592ec85..0000000 --- a/src/Contracts/ValueEncrypter.php +++ /dev/null @@ -1,20 +0,0 @@ - $rules - * - * @throws InvalidSettingValue naming the key and the failed rule, never the value - */ - public function validate(Key $key, mixed $value, array $rules): void; -} diff --git a/src/Data/ApprovalPolicy.php b/src/Data/ApprovalPolicy.php index 72446fd..92f9671 100644 --- a/src/Data/ApprovalPolicy.php +++ b/src/Data/ApprovalPolicy.php @@ -29,4 +29,26 @@ public function __construct( } } } + + /** + * The policy `approvals.*` describes. + * + * @param array $approvals `laranail.settings.approvals` + */ + public static function fromConfig(array $approvals): self + { + $days = static function (string $key, ?int $default) use ($approvals): ?int { + $value = array_key_exists($key, $approvals) ? $approvals[$key] : $default; + + return $value === null ? null : (is_numeric($value) ? (int) $value : throw new InvalidConfiguration(sprintf('laranail.settings.approvals.%s: a number of days, or null.', $key))); + }; + $min = $approvals['min_approvals'] ?? 1; + + return new self( + is_int($min) || (is_string($min) && ctype_digit($min)) ? (int) $min : 1, + ($approvals['allow_self'] ?? false) === true, + $days('expire_after', 7), + $days('keep_days', 90), + ); + } } diff --git a/src/Data/Http/BodyInput.php b/src/Data/Http/BodyInput.php deleted file mode 100644 index c75cb26..0000000 --- a/src/Data/Http/BodyInput.php +++ /dev/null @@ -1,60 +0,0 @@ - $params route parameters - * @param array $body validated body - * @param bool $hasParent whether the body named `parent` at all (null moves to the top level) - */ - public function __construct( - public array $params, - public array $body, - public bool $hasParent = false, - ) {} - - public function param(string $name): string - { - return $this->params[$name] ?? ''; - } - - public function text(string $name): ?string - { - $value = $this->body[$name] ?? null; - - return is_string($value) && $value !== '' ? $value : null; - } - - public function integer(string $name, int $default = 0): int - { - $value = $this->body[$name] ?? null; - - return is_numeric($value) ? (int) $value : $default; - } - - public function boolean(string $name): bool - { - return filter_var($this->body[$name] ?? false, FILTER_VALIDATE_BOOL); - } - - /** @return array */ - public function array(string $name): array - { - $value = $this->body[$name] ?? []; - - return is_array($value) ? $value : []; - } - - public function value(string $name): mixed - { - return $this->body[$name] ?? null; - } -} diff --git a/src/Database/SchemaReadinessProbe.php b/src/Database/SchemaReadinessProbe.php deleted file mode 100644 index 15e65e6..0000000 --- a/src/Database/SchemaReadinessProbe.php +++ /dev/null @@ -1,30 +0,0 @@ -readiness->isReady($tables, $connection); - } - - public function flush(): void - { - $this->readiness->flush(); - } -} diff --git a/src/Drivers/BootstrapGatedDriver.php b/src/Drivers/BootstrapGatedDriver.php index 047565b..6d1a72e 100644 --- a/src/Drivers/BootstrapGatedDriver.php +++ b/src/Drivers/BootstrapGatedDriver.php @@ -4,16 +4,17 @@ namespace Simtabi\Laranail\Settings\Drivers; -use Closure; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\Record; +use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Events\LayerSkipped; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; -use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; +use Simtabi\Laranail\Settings\Stores\InstallationEvidence; /** * The database layer of a store in bootstrap mode (`stores..bootstrap`). The layer is @@ -28,12 +29,13 @@ final class BootstrapGatedDriver implements DatabaseBacked { private bool $reported = false; - /** @param (Closure(string): void)|null $onSkip told the reason the first time the layer is skipped */ + /** @param ?Dispatcher $events told ({@see LayerSkipped}) the first time the layer named `$layer` is skipped */ public function __construct( private readonly DatabaseDriver $inner, private readonly StoreName $store, - private readonly BootstrapEvidence $evidence, - private readonly ?Closure $onSkip = null, + private readonly InstallationEvidence $evidence, + private readonly ?Dispatcher $events = null, + private readonly string $layer = 'database', ) {} public function database(): DatabaseDriver @@ -47,9 +49,9 @@ public function isActive(): bool return true; } - if (! $this->reported && $this->onSkip instanceof Closure) { + if (! $this->reported && $this->events instanceof Dispatcher) { $this->reported = true; - ($this->onSkip)('the application is being installed and the database is not ready'); + $this->events->dispatch(new LayerSkipped($this->store->value, $this->layer, 'the application is being installed and the database is not ready')); } return false; diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index 240dc47..81c4cd2 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -27,7 +27,6 @@ use Illuminate\Database\ConnectionResolverInterface; use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; -use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; @@ -37,6 +36,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; +use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; /** * Records in a database table, through the query builder (no Eloquent on the hot path). @@ -60,7 +60,7 @@ /** * @param ?string $table the store's configured table (`stores..table`); null uses the store name - * @param Closure(): ReadinessProbe $probe resolved only after a database error + * @param Closure(): SchemaReadinessInterface $probe db-tools' schema readiness, resolved only after a database error * @param (Closure(): SchemaShape)|null $shape the recorded schema shape; null is the default shape over $names * @param (Closure(): ?string)|null $tenant the current tenant (column-mode tenancy); null is no tenant */ @@ -178,7 +178,7 @@ public function connection(): Connection public function isReady(StoreName $store): bool { try { - return ($this->probe)()->isReady($this->connectionName(), [$this->tableFor($store)]); + return ($this->probe)()->isReady([$this->tableFor($store)], $this->connectionName()); } catch (Exception) { return false; } @@ -507,7 +507,7 @@ private function readyAfterFailure(StoreName $store, Exception $exception): bool $probe = ($this->probe)(); $probe->flush(); - return $probe->isReady($this->connectionName(), [$this->tableFor($store)]); + return $probe->isReady([$this->tableFor($store)], $this->connectionName()); } catch (Exception) { return false; } diff --git a/src/Enums/Capability.php b/src/Enums/Capability.php deleted file mode 100644 index d18aa2d..0000000 --- a/src/Enums/Capability.php +++ /dev/null @@ -1,199 +0,0 @@ -`, and `laranail-settings.api.owners.` for the owner - * form) and backed by the actions the PHP API uses. An architecture test holds the routes, this - * list and the controllers to each other, so no channel can grow a capability the others lack. - */ -enum Capability: string implements Enumerator -{ - use HasEnumeratorBehavior; - - #[Label('List stores')] - case StoresIndex = 'stores.index'; - - #[Label('List definitions')] - case DefinitionsIndex = 'definitions.index'; - - #[Label('List settings')] - case SettingsIndex = 'settings.index'; - - #[Label('Read a setting')] - case SettingsShow = 'settings.show'; - - #[Label('Write a setting')] - case SettingsUpdate = 'settings.update'; - - #[Label('Forget a setting')] - case SettingsDestroy = 'settings.destroy'; - - #[Label('Lock a setting')] - case SettingsLock = 'settings.lock'; - - #[Label('Unlock a setting')] - case SettingsUnlock = 'settings.unlock'; - - #[Label('Explain a setting')] - case SettingsExplain = 'settings.explain'; - - #[Label('A setting\'s history')] - case SettingsHistory = 'settings.history'; - - #[Label('Roll a setting back')] - case SettingsRollback = 'settings.rollback'; - - #[Label('The audit trail')] - case AuditIndex = 'audit.index'; - - #[Label('List change requests')] - case ChangesIndex = 'changes.index'; - - #[Label('Read a change request')] - case ChangesShow = 'changes.show'; - - #[Label('Propose a change')] - case ChangesStore = 'changes.store'; - - #[Label('Approve a change')] - case ChangesApprove = 'changes.approve'; - - #[Label('Reject a change')] - case ChangesReject = 'changes.reject'; - - #[Label('Cancel a change')] - case ChangesCancel = 'changes.cancel'; - - #[Label('List categories')] - case CategoriesIndex = 'categories.index'; - - #[Label('Create a category')] - case CategoriesStore = 'categories.store'; - - #[Label('Rename or move a category')] - case CategoriesUpdate = 'categories.update'; - - #[Label('Delete a category')] - case CategoriesDestroy = 'categories.destroy'; - - #[Label('List persisted configuration')] - case ConfigurationIndex = 'configuration.index'; - - #[Label('Save a persisted store or layer')] - case ConfigurationUpdate = 'configuration.update'; - - #[Label('Delete a persisted store or layer')] - case ConfigurationDestroy = 'configuration.destroy'; - - #[Label('Save a definition')] - case DefinitionsUpdate = 'definitions.update'; - - #[Label('Delete a definition')] - case DefinitionsDestroy = 'definitions.destroy'; - - #[Label('Export a store')] - case TransferExport = 'transfer.export'; - - #[Label('Import into a store')] - case TransferImport = 'transfer.import'; - - #[Label('Compare a store with an export')] - case TransferDiff = 'transfer.diff'; - - /** - * The actions this capability runs, as the PHP API runs them. - * - * @return list - */ - public function actions(): array - { - return match ($this) { - self::StoresIndex => [ListStores::class], - self::DefinitionsIndex => [ListDefinitions::class], - self::SettingsIndex => [ReadSettings::class], - self::SettingsShow => [ReadSetting::class], - self::SettingsUpdate => [SetSetting::class], - self::SettingsDestroy => [ForgetSetting::class], - self::SettingsLock => [LockSetting::class], - self::SettingsUnlock => [UnlockSetting::class], - self::SettingsExplain => [ExplainSetting::class], - self::SettingsHistory => [ReadHistory::class], - self::SettingsRollback => [RollbackSetting::class], - self::AuditIndex => [QueryAudit::class], - self::ChangesIndex => [QueryChanges::class], - self::ChangesShow => [QueryChanges::class], - self::ChangesStore => [ProposeChange::class], - self::ChangesApprove => [ApproveChange::class], - self::ChangesReject => [RejectChange::class], - self::ChangesCancel => [CancelChange::class], - self::CategoriesIndex => [ListCategories::class], - self::CategoriesStore => [CreateCategory::class], - self::CategoriesUpdate => [RenameCategory::class, MoveCategory::class], - self::CategoriesDestroy => [DeleteCategory::class], - self::ConfigurationIndex => [ListConfigurationEntries::class], - self::ConfigurationUpdate => [SaveConfigurationEntry::class], - self::ConfigurationDestroy => [DeleteConfigurationEntry::class], - self::DefinitionsUpdate => [SaveDefinition::class], - self::DefinitionsDestroy => [DeleteDefinition::class], - self::TransferExport => [ExportStore::class], - self::TransferImport => [ImportStore::class], - self::TransferDiff => [DiffStore::class], - }; - } - - /** The `http.routes` group that switches this capability's routes on or off. */ - public function group(): string - { - return match ($this) { - self::SettingsHistory, self::SettingsRollback => 'history', - self::ChangesIndex, self::ChangesShow, self::ChangesStore, - self::ChangesApprove, self::ChangesReject, self::ChangesCancel => 'approvals', - self::DefinitionsUpdate, self::DefinitionsDestroy => 'configuration', - default => explode('.', $this->value)[0], - }; - } - - /** Whether the capability has an owner form (`/owners/{alias}/{id}/settings/…`). */ - public function hasOwnerForm(): bool - { - return str_starts_with($this->value, 'settings.'); - } -} diff --git a/src/Exceptions/AccessDenied.php b/src/Exceptions/AccessDenied.php index d0362b6..8e7809f 100644 --- a/src/Exceptions/AccessDenied.php +++ b/src/Exceptions/AccessDenied.php @@ -13,6 +13,10 @@ */ final class AccessDenied extends SettingsException { + public const int STATUS = 403; + + public const string TYPE = 'access-denied'; + public function __construct( public readonly Ability $ability, public readonly string $store, diff --git a/src/Exceptions/ActorRequired.php b/src/Exceptions/ActorRequired.php index 736e031..1098d64 100644 --- a/src/Exceptions/ActorRequired.php +++ b/src/Exceptions/ActorRequired.php @@ -8,4 +8,9 @@ * The call has no actor while `authorization.require_actor` is on, or no actor could be resolved * from the current request. Pass one with `as()`, or mark trusted code with `asSystem()`. */ -final class ActorRequired extends SettingsException {} +final class ActorRequired extends SettingsException +{ + public const int STATUS = 401; + + public const string TYPE = 'actor-required'; +} diff --git a/src/Exceptions/ApprovalUnavailable.php b/src/Exceptions/ApprovalUnavailable.php index adfefe4..8f517e9 100644 --- a/src/Exceptions/ApprovalUnavailable.php +++ b/src/Exceptions/ApprovalUnavailable.php @@ -10,4 +10,9 @@ * recorded without the change requests table (`approvals.table`). A store that can hold them turns * such a write into a change request instead (§16.7). */ -final class ApprovalUnavailable extends SettingsException {} +final class ApprovalUnavailable extends SettingsException +{ + public const int STATUS = 409; + + public const string TYPE = 'approval-unavailable'; +} diff --git a/src/Exceptions/CategoryCycle.php b/src/Exceptions/CategoryCycle.php index d47925c..74ecdc3 100644 --- a/src/Exceptions/CategoryCycle.php +++ b/src/Exceptions/CategoryCycle.php @@ -7,4 +7,9 @@ /** * Moving a category under itself or one of its descendants would create a cycle. */ -final class CategoryCycle extends SettingsException {} +final class CategoryCycle extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'category-cycle'; +} diff --git a/src/Exceptions/CategoryStoreMismatch.php b/src/Exceptions/CategoryStoreMismatch.php index 6feb185..0190a47 100644 --- a/src/Exceptions/CategoryStoreMismatch.php +++ b/src/Exceptions/CategoryStoreMismatch.php @@ -7,4 +7,9 @@ /** * A category belongs to another store than the setting or category referring to it. */ -final class CategoryStoreMismatch extends SettingsException {} +final class CategoryStoreMismatch extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'category-store-mismatch'; +} diff --git a/src/Exceptions/ChangeRequestClosed.php b/src/Exceptions/ChangeRequestClosed.php index 2325f92..f77f698 100644 --- a/src/Exceptions/ChangeRequestClosed.php +++ b/src/Exceptions/ChangeRequestClosed.php @@ -8,4 +8,9 @@ * The change request can no longer be decided: it was applied, rejected, cancelled, went stale or * expired (or another approver decided it first). */ -final class ChangeRequestClosed extends SettingsException {} +final class ChangeRequestClosed extends SettingsException +{ + public const int STATUS = 409; + + public const string TYPE = 'change-request-closed'; +} diff --git a/src/Exceptions/ConcurrentModification.php b/src/Exceptions/ConcurrentModification.php index 36420a5..2a14a8d 100644 --- a/src/Exceptions/ConcurrentModification.php +++ b/src/Exceptions/ConcurrentModification.php @@ -7,4 +7,9 @@ /** * Another writer changed the row between this write's read and its update (the version check failed), or inserted the same (scope, key, locale) first. Re-read and retry. */ -final class ConcurrentModification extends SettingsException {} +final class ConcurrentModification extends SettingsException +{ + public const int STATUS = 412; + + public const string TYPE = 'precondition-failed'; +} diff --git a/src/Exceptions/DriverUnavailable.php b/src/Exceptions/DriverUnavailable.php index da3838b..1372e3d 100644 --- a/src/Exceptions/DriverUnavailable.php +++ b/src/Exceptions/DriverUnavailable.php @@ -7,4 +7,9 @@ /** * A required layer is unreachable (the database is down, or its table is missing) and no bootstrap evidence lets the store skip it. Never a fallback to defaults. */ -final class DriverUnavailable extends SettingsException {} +final class DriverUnavailable extends SettingsException +{ + public const int STATUS = 503; + + public const string TYPE = 'unavailable'; +} diff --git a/src/Exceptions/HistoryUnavailable.php b/src/Exceptions/HistoryUnavailable.php index 5470364..6a72ac2 100644 --- a/src/Exceptions/HistoryUnavailable.php +++ b/src/Exceptions/HistoryUnavailable.php @@ -9,4 +9,9 @@ * history table (`history.enabled` was off when it was migrated), or the version asked for is * not in it. */ -final class HistoryUnavailable extends SettingsException {} +final class HistoryUnavailable extends SettingsException +{ + public const int STATUS = 409; + + public const string TYPE = 'history-unavailable'; +} diff --git a/src/Exceptions/InvalidConfiguration.php b/src/Exceptions/InvalidConfiguration.php index 8bc90cc..861e05d 100644 --- a/src/Exceptions/InvalidConfiguration.php +++ b/src/Exceptions/InvalidConfiguration.php @@ -7,4 +7,9 @@ /** * The package configuration is invalid; the message names the offending config path. */ -final class InvalidConfiguration extends SettingsException {} +final class InvalidConfiguration extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'invalid-configuration'; +} diff --git a/src/Exceptions/InvalidDefinition.php b/src/Exceptions/InvalidDefinition.php index 992c146..349c035 100644 --- a/src/Exceptions/InvalidDefinition.php +++ b/src/Exceptions/InvalidDefinition.php @@ -7,4 +7,9 @@ /** * A setting definition is internally inconsistent (for example encrypted and public). */ -final class InvalidDefinition extends SettingsException {} +final class InvalidDefinition extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'invalid-definition'; +} diff --git a/src/Exceptions/InvalidIdentifier.php b/src/Exceptions/InvalidIdentifier.php index 430e54c..db77746 100644 --- a/src/Exceptions/InvalidIdentifier.php +++ b/src/Exceptions/InvalidIdentifier.php @@ -7,4 +7,9 @@ /** * A store name, key, locale or owner alias failed its value object's validation. */ -class InvalidIdentifier extends SettingsException {} +class InvalidIdentifier extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'invalid-identifier'; +} diff --git a/src/Exceptions/InvalidImport.php b/src/Exceptions/InvalidImport.php index 6966508..f52dd23 100644 --- a/src/Exceptions/InvalidImport.php +++ b/src/Exceptions/InvalidImport.php @@ -5,4 +5,9 @@ namespace Simtabi\Laranail\Settings\Exceptions; /** An export file (or importer source) is not a document this release can read. */ -final class InvalidImport extends SettingsException {} +final class InvalidImport extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'invalid-import'; +} diff --git a/src/Exceptions/InvalidSettingValue.php b/src/Exceptions/InvalidSettingValue.php index 568f4d6..7925fd7 100644 --- a/src/Exceptions/InvalidSettingValue.php +++ b/src/Exceptions/InvalidSettingValue.php @@ -7,4 +7,9 @@ /** * A value failed its definition's rules, cast or locale constraints. */ -final class InvalidSettingValue extends SettingsException {} +final class InvalidSettingValue extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'invalid-value'; +} diff --git a/src/Exceptions/LockedSetting.php b/src/Exceptions/LockedSetting.php index bfb88ec..4d6f63b 100644 --- a/src/Exceptions/LockedSetting.php +++ b/src/Exceptions/LockedSetting.php @@ -7,4 +7,9 @@ /** * A write was refused because the setting is locked or its precedence forbids store writes. */ -final class LockedSetting extends SettingsException {} +final class LockedSetting extends SettingsException +{ + public const int STATUS = 423; + + public const string TYPE = 'locked'; +} diff --git a/src/Exceptions/OwnerNotAllowed.php b/src/Exceptions/OwnerNotAllowed.php index f1ca679..5f9254d 100644 --- a/src/Exceptions/OwnerNotAllowed.php +++ b/src/Exceptions/OwnerNotAllowed.php @@ -7,4 +7,9 @@ /** * The owner's morph alias is not allowed in the store, or no store accepts it. */ -final class OwnerNotAllowed extends SettingsException {} +final class OwnerNotAllowed extends SettingsException +{ + public const int STATUS = 409; + + public const string TYPE = 'owner-not-allowed'; +} diff --git a/src/Exceptions/SettingsException.php b/src/Exceptions/SettingsException.php index d58dcf8..fdde405 100644 --- a/src/Exceptions/SettingsException.php +++ b/src/Exceptions/SettingsException.php @@ -9,6 +9,14 @@ /** * Base of every exception this package throws, so a caller can catch anything from it in one * place or catch one precise subtype. Messages name the store, key and scope involved and never - * carry a setting's value. + * carry a setting's value. Each subtype the REST API answers names its HTTP status and problem + * type ({@see STATUS}, {@see TYPE}); the rest are a 500 `settings-error`. */ -abstract class SettingsException extends RuntimeException {} +abstract class SettingsException extends RuntimeException +{ + /** The HTTP status the REST API answers this exception with; a subtype names its own. */ + public const int STATUS = 500; + + /** The problem type (RFC 9457) the REST API names, under Problems::TYPE_BASE. */ + public const string TYPE = 'settings-error'; +} diff --git a/src/Exceptions/StoreNotWritable.php b/src/Exceptions/StoreNotWritable.php index aae9cbb..3372811 100644 --- a/src/Exceptions/StoreNotWritable.php +++ b/src/Exceptions/StoreNotWritable.php @@ -7,4 +7,9 @@ /** * No layer of the store can accept the write. */ -final class StoreNotWritable extends SettingsException {} +final class StoreNotWritable extends SettingsException +{ + public const int STATUS = 409; + + public const string TYPE = 'store-not-writable'; +} diff --git a/src/Exceptions/TypeMismatch.php b/src/Exceptions/TypeMismatch.php index 84999f1..3bda91f 100644 --- a/src/Exceptions/TypeMismatch.php +++ b/src/Exceptions/TypeMismatch.php @@ -7,4 +7,9 @@ /** * A typed getter found a value of a different type. */ -final class TypeMismatch extends SettingsException {} +final class TypeMismatch extends SettingsException +{ + public const int STATUS = 422; + + public const string TYPE = 'type-mismatch'; +} diff --git a/src/Exceptions/UnknownCategory.php b/src/Exceptions/UnknownCategory.php index 4b60fed..370b1f7 100644 --- a/src/Exceptions/UnknownCategory.php +++ b/src/Exceptions/UnknownCategory.php @@ -7,4 +7,9 @@ /** * No category with this slug exists in the store. */ -final class UnknownCategory extends SettingsException {} +final class UnknownCategory extends SettingsException +{ + public const int STATUS = 404; + + public const string TYPE = 'unknown-category'; +} diff --git a/src/Exceptions/UnknownChangeRequest.php b/src/Exceptions/UnknownChangeRequest.php index 7d85676..b98460c 100644 --- a/src/Exceptions/UnknownChangeRequest.php +++ b/src/Exceptions/UnknownChangeRequest.php @@ -5,4 +5,9 @@ namespace Simtabi\Laranail\Settings\Exceptions; /** No change request with this id exists in the store (for the current tenant). */ -final class UnknownChangeRequest extends SettingsException {} +final class UnknownChangeRequest extends SettingsException +{ + public const int STATUS = 404; + + public const string TYPE = 'unknown-change-request'; +} diff --git a/src/Exceptions/UnknownOwner.php b/src/Exceptions/UnknownOwner.php index 12d11ed..91dae85 100644 --- a/src/Exceptions/UnknownOwner.php +++ b/src/Exceptions/UnknownOwner.php @@ -5,4 +5,9 @@ namespace Simtabi\Laranail\Settings\Exceptions; /** No owner of that alias and id: the alias is not in the morph map, or no such record exists. */ -final class UnknownOwner extends SettingsException {} +final class UnknownOwner extends SettingsException +{ + public const int STATUS = 404; + + public const string TYPE = 'unknown-owner'; +} diff --git a/src/Exceptions/UnknownSetting.php b/src/Exceptions/UnknownSetting.php index 158f152..cef5773 100644 --- a/src/Exceptions/UnknownSetting.php +++ b/src/Exceptions/UnknownSetting.php @@ -7,4 +7,9 @@ /** * A strict store was asked for a key that has no definition. */ -final class UnknownSetting extends SettingsException {} +final class UnknownSetting extends SettingsException +{ + public const int STATUS = 404; + + public const string TYPE = 'unknown-setting'; +} diff --git a/src/Exceptions/UnknownStore.php b/src/Exceptions/UnknownStore.php index 3783ca5..b21ee6b 100644 --- a/src/Exceptions/UnknownStore.php +++ b/src/Exceptions/UnknownStore.php @@ -7,4 +7,9 @@ /** * A store was requested that is not configured. */ -final class UnknownStore extends SettingsException {} +final class UnknownStore extends SettingsException +{ + public const int STATUS = 404; + + public const string TYPE = 'unknown-store'; +} diff --git a/src/Exceptions/VerificationRequired.php b/src/Exceptions/VerificationRequired.php index d5c03a2..32cd1b1 100644 --- a/src/Exceptions/VerificationRequired.php +++ b/src/Exceptions/VerificationRequired.php @@ -13,6 +13,10 @@ */ final class VerificationRequired extends SettingsException { + public const int STATUS = 428; + + public const string TYPE = 'verification-required'; + public function __construct( public readonly Ability $ability, public readonly string $store, diff --git a/src/Facades/Settings.php b/src/Facades/Settings.php index 41daf06..b055f15 100644 --- a/src/Facades/Settings.php +++ b/src/Facades/Settings.php @@ -11,27 +11,41 @@ use Simtabi\Laranail\Settings\Data\Lookup; use Simtabi\Laranail\Settings\Data\OwnerRef; use Illuminate\Contracts\Auth\Authenticatable; +use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\SettingsManager; use Simtabi\Laranail\Settings\Testing\FakeLog; use Simtabi\Laranail\Settings\Audit\AuditQuery; +use Simtabi\Laranail\Settings\Data\HistoryDiff; +use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Actions\QueryAudit; +use Simtabi\Laranail\Settings\Actions\SetSetting; +use Simtabi\Laranail\Settings\Actions\WriteGuard; use Simtabi\Laranail\Settings\Contracts\Settable; +use Simtabi\Laranail\Settings\Data\ChangeRequest; +use Simtabi\Laranail\Settings\Actions\LockSetting; +use Simtabi\Laranail\Settings\Approvals\Approvals; use Simtabi\Laranail\Settings\Drivers\ArrayDriver; -use Simtabi\Laranail\Settings\Actions\StoreActions; use Simtabi\Laranail\Settings\Data\PromotionReport; +use Simtabi\Laranail\Settings\History\HistoryQuery; use Simtabi\Laranail\Settings\Testing\SettingsFake; +use Simtabi\Laranail\Settings\Actions\ForgetSetting; +use Simtabi\Laranail\Settings\Actions\UnlockSetting; use Simtabi\Laranail\Settings\Data\PromotionRequest; -use Simtabi\Laranail\Settings\Actions\SettingActions; use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Audit\InMemoryAuditSink; +use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; use Simtabi\Laranail\Settings\Categories\CategoryManager; +use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Services\Resolution\Resolver; +use Simtabi\Laranail\Settings\Actions\Reads\ListDefinitions; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; +use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; use Simtabi\Laranail\Settings\Contracts\Settings as SettingsContract; -use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; +use Simtabi\Laranail\Settings\Configuration\PersistedConfigurationEditor; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** @@ -66,6 +80,25 @@ * @method static CategoryManager categories() * @method static PromotionReport promote(?PromotionRequest $request = null) * @method static AuditQuery audit() + * @method static bool missing(string $key) + * @method static array many(array $keys) + * @method static array all(?string $prefix = null) + * @method static list definitions() + * @method static void setMany(array $values) + * @method static void forgetMany(iterable $keys) + * @method static mixed remember(string $key, callable $value) + * @method static void clearCache() + * @method static int warmCache() + * @method static HistoryQuery history() + * @method static int rollback(string $key, int $toVersion) + * @method static HistoryDiff historyDiff(string $key, int $from, int $to) + * @method static ChangeRequest propose(string $key, mixed $value) + * @method static Approvals approvals() + * @method static ExportDocument export(ExportMode $mode = ExportMode::Redacted) + * @method static ImportReport import(ExportDocument $document) + * @method static ImportReport previewImport(ExportDocument $document) + * @method static StoreDiff compare(ExportDocument $document) + * @method static PersistedConfigurationEditor persistedConfiguration() * * @see SettingsContract */ @@ -87,19 +120,21 @@ public static function fake(): SettingsFake $log = new FakeLog(new InMemoryAuditSink); $access = $app->make(AccessGuard::class); $access = $access->withAuditor($access->auditor()->alsoTo($log->audit)); - $writer = $app->make(SettingWriter::class); + $guard = new WriteGuard($access, $app->make(SettingWriter::class), $app->make(ProposeChange::class)); - $fake = new SettingsFake(new SettingsManager( - $stores, - $app->make(DefinitionRegistry::class), - new Resolver($stores, $app->make(ValuePipeline::class), self::fallbackLocale($app->make('config')->get('app.fallback_locale'))), - $writer, - actions: SettingActions::using($writer, $access), - access: $access, - runtime: $app->make(RuntimeConfiguration::class), - storeActions: $app->make(StoreActions::class), - auditQuery: new QueryAudit($stores, $access), - ), $log); + // The real engine, with the in-memory stores, the recording access guard and the writes + // that go through it; every other collaborator is the container's. + $fake = new SettingsFake($app->make(SettingsManager::class, [ + 'stores' => $stores, + 'resolver' => new Resolver($stores, $app->make(ValuePipeline::class), self::fallbackLocale($app->make('config')->get('app.fallback_locale'))), + 'access' => $access, + 'set' => $app->make(SetSetting::class, ['guard' => $guard]), + 'forget' => $app->make(ForgetSetting::class, ['guard' => $guard]), + 'lock' => $app->make(LockSetting::class, ['guard' => $guard]), + 'unlock' => $app->make(UnlockSetting::class, ['guard' => $guard]), + 'auditQuery' => new QueryAudit($stores, $access), + 'listDefinitions' => $app->make(ListDefinitions::class, ['access' => $access]), + ]), $log); self::swap($fake); $app->instance(SettingsContract::class, $fake); diff --git a/src/Http/ApiRoutes.php b/src/Http/ApiRoutes.php deleted file mode 100644 index 5fd2d26..0000000 --- a/src/Http/ApiRoutes.php +++ /dev/null @@ -1,119 +0,0 @@ -` (the owner form of a settings route - * adds `owners.`), through `http.middleware`, the `laranail-settings` rate limiter and, on writes, - * the idempotency middleware. Groups listed false in `http.routes` are left out. - */ -final readonly class ApiRoutes -{ - public const string NAME_PREFIX = 'laranail-settings.api.'; - - /** - * Every route: [method, uri under /v1, capability, controller, controller method]. - * - * @var list - */ - private const array ROUTES = [ - ['GET', 'stores', Capability::StoresIndex, StoresController::class, 'index'], - ['GET', 'stores/{store}/definitions', Capability::DefinitionsIndex, StoresController::class, 'definitions'], - ['GET', '{owner}settings', Capability::SettingsIndex, SettingsController::class, 'index'], - ['GET', '{owner}settings/{key}', Capability::SettingsShow, SettingsController::class, 'show'], - ['PUT', '{owner}settings/{key}', Capability::SettingsUpdate, SettingsController::class, 'update'], - ['DELETE', '{owner}settings/{key}', Capability::SettingsDestroy, SettingsController::class, 'destroy'], - ['POST', '{owner}settings/{key}/lock', Capability::SettingsLock, SettingsController::class, 'lock'], - ['DELETE', '{owner}settings/{key}/lock', Capability::SettingsUnlock, SettingsController::class, 'unlock'], - ['GET', '{owner}settings/{key}/explain', Capability::SettingsExplain, SettingsController::class, 'explain'], - ['GET', '{owner}settings/{key}/history', Capability::SettingsHistory, HistoryController::class, 'index'], - ['POST', '{owner}settings/{key}/rollback', Capability::SettingsRollback, HistoryController::class, 'rollback'], - ['GET', 'audit', Capability::AuditIndex, AuditController::class, 'index'], - ['GET', 'stores/{store}/changes', Capability::ChangesIndex, ChangesController::class, 'index'], - ['POST', 'stores/{store}/changes', Capability::ChangesStore, ChangesController::class, 'store'], - ['GET', 'stores/{store}/changes/{id}', Capability::ChangesShow, ChangesController::class, 'show'], - ['POST', 'stores/{store}/changes/{id}/approve', Capability::ChangesApprove, ChangesController::class, 'approve'], - ['POST', 'stores/{store}/changes/{id}/reject', Capability::ChangesReject, ChangesController::class, 'reject'], - ['POST', 'stores/{store}/changes/{id}/cancel', Capability::ChangesCancel, ChangesController::class, 'cancel'], - ['GET', 'stores/{store}/categories', Capability::CategoriesIndex, CategoriesController::class, 'index'], - ['POST', 'stores/{store}/categories', Capability::CategoriesStore, CategoriesController::class, 'store'], - ['PATCH', 'stores/{store}/categories/{slug}', Capability::CategoriesUpdate, CategoriesController::class, 'update'], - ['DELETE', 'stores/{store}/categories/{slug}', Capability::CategoriesDestroy, CategoriesController::class, 'destroy'], - ['GET', 'configuration', Capability::ConfigurationIndex, ConfigurationController::class, 'index'], - ['PUT', 'configuration/{kind}/{name}', Capability::ConfigurationUpdate, ConfigurationController::class, 'update'], - ['DELETE', 'configuration/{kind}/{name}', Capability::ConfigurationDestroy, ConfigurationController::class, 'destroy'], - ['PUT', 'stores/{store}/definitions/{key}', Capability::DefinitionsUpdate, ConfigurationController::class, 'updateDefinition'], - ['DELETE', 'stores/{store}/definitions/{key}', Capability::DefinitionsDestroy, ConfigurationController::class, 'destroyDefinition'], - ['POST', 'stores/{store}/export', Capability::TransferExport, TransferController::class, 'export'], - ['POST', 'stores/{store}/import', Capability::TransferImport, TransferController::class, 'import'], - ['POST', 'stores/{store}/diff', Capability::TransferDiff, TransferController::class, 'diff'], - ]; - - /** - * @return list - */ - public static function definitions(): array - { - $routes = []; - - foreach (self::ROUTES as [$method, $uri, $capability, $controller, $action]) { - $forms = str_starts_with($uri, '{owner}') - ? ['' => 'stores/{store}/', 'owners.' => 'stores/{store}/owners/{alias}/{id}/'] - : ['' => '']; - - foreach ($forms as $prefix => $path) { - $routes[] = [ - 'method' => $method, - 'uri' => $path . str_replace('{owner}', '', $uri), - 'name' => self::NAME_PREFIX . $prefix . $capability->value, - 'capability' => $capability, - 'controller' => $controller, - 'action' => $action, - ]; - } - } - - return $routes; - } - - /** - * @param list $middleware - * @param array $groups `http.routes` - */ - public static function register(Router $router, string $prefix, array $middleware, array $groups): void - { - $router->prefix(trim($prefix, '/') . '/v1') - ->middleware([FreshControllers::class, ...$middleware, 'throttle:laranail-settings']) - ->group(static function (Router $router) use ($groups): void { - foreach (self::definitions() as $route) { - if (($groups[$route['capability']->group()] ?? true) === false) { - continue; - } - - $registered = $router->addRoute($route['method'], $route['uri'], [$route['controller'], $route['action']]) - ->name($route['name']) - ->where(['store' => '[a-z][a-z0-9_]*', 'key' => '[A-Za-z0-9_.]+', 'alias' => '[a-z][a-z0-9_]*', 'kind' => 'stores|layers']); - - if ($route['method'] !== 'GET') { - $registered->middleware(IdempotentWrites::class); - } - } - }); - } -} diff --git a/src/Http/Controllers/AuditController.php b/src/Http/Controllers/AuditController.php index 4de3acf..3d8cc95 100644 --- a/src/Http/Controllers/AuditController.php +++ b/src/Http/Controllers/AuditController.php @@ -5,11 +5,9 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; use Carbon\CarbonImmutable; -use Illuminate\Http\JsonResponse; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\StoreName; -use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Data\AuditFilter; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Actions\QueryAudit; @@ -17,23 +15,19 @@ use Simtabi\Laranail\Settings\Data\Http\PageInput; use Simtabi\Laranail\Settings\Http\Support\ApiActor; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; +use Simtabi\Laranail\Settings\Http\Resources\AuditEntryResource; /** `/audit` (§16.8): the audit trail, filtered, newest first. Needs `view_audit`. */ final readonly class AuditController { - public function __construct( - private ApiActor $actors, - private QueryAudit $audit, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, QueryAudit $audit, ApiActor $actors): AnonymousResourceCollection { $page = $request->toData(); - $result = $this->audit->paginate($this->filter($page), $this->actors->of($request), $page->limit, $page->cursor); + $result = $audit->paginate($this->filter($page), $actors->of($request), $page->limit, $page->cursor); - return ListResponse::make(array_map(static fn (AuditEntry $entry): array => $entry->toArray(), $result->entries), $result->nextCursor); + return AuditEntryResource::collection($result->entries)->additional(['meta' => ['next_cursor' => $result->nextCursor]]); } private function filter(PageInput $page): AuditFilter diff --git a/src/Http/Controllers/CategoriesController.php b/src/Http/Controllers/CategoriesController.php index 0ccba25..062bae6 100644 --- a/src/Http/Controllers/CategoriesController.php +++ b/src/Http/Controllers/CategoriesController.php @@ -4,82 +4,64 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; +use Illuminate\Http\Response; use Illuminate\Http\JsonResponse; use Simtabi\Laranail\Settings\Data\Category; -use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Http\Support\ApiActor; -use Simtabi\Laranail\Settings\Http\Requests\BodyRequest; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; +use Simtabi\Laranail\Settings\Http\Requests\ReasonRequest; use Simtabi\Laranail\Settings\Actions\Categories\MoveCategory; use Simtabi\Laranail\Settings\Http\Resources\CategoryResource; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; use Simtabi\Laranail\Settings\Actions\Categories\DeleteCategory; use Simtabi\Laranail\Settings\Actions\Categories\ListCategories; use Simtabi\Laranail\Settings\Actions\Categories\RenameCategory; +use Simtabi\Laranail\Settings\Http\Requests\StoreCategoryRequest; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; +use Simtabi\Laranail\Settings\Http\Requests\UpdateCategoryRequest; /** `/stores/{store}/categories` (D-11): list, create, rename or move, delete. */ final readonly class CategoriesController { - public function __construct( - private ApiActor $actors, - private SettingTargets $targets, - private ListCategories $list, - private CreateCategory $create, - private RenameCategory $rename, - private MoveCategory $move, - private DeleteCategory $delete, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, ListCategories $list, SettingTargets $targets, ApiActor $actors): AnonymousResourceCollection { - $categories = $this->list->handle($this->targets->store($request->addressData()->store), $this->actors->of($request)); + $categories = $list->handle($targets->store($request->addressData()->store), $actors->of($request)); - return ListResponse::make(array_map(CategoryResource::fields(...), $categories)); + return CategoryResource::collection($categories)->additional(['meta' => ['next_cursor' => null]]); } - public function store(BodyRequest $request): JsonResponse + public function store(StoreCategoryRequest $request, CreateCategory $create, SettingTargets $targets, ApiActor $actors): JsonResponse { - $input = $request->toData(); - $category = $this->create->handle($this->targets->store($input->param('store')), new NewCategory( - (string) $input->text('slug'), - (string) $input->text('title'), - $input->text('parent'), - $input->text('description'), - $input->text('icon'), - $input->integer('sort_order'), - $input->array('titles'), - ), $this->actors->of($request)); + $category = $create->handle($targets->store((string) $request->route('store')), $request->toData(), $actors->of($request)); - return new JsonResponse(['data' => CategoryResource::fields($category)], 201); + return CategoryResource::make($category)->response()->setStatusCode(201); } - public function update(BodyRequest $request): JsonResponse + public function update(UpdateCategoryRequest $request, RenameCategory $rename, MoveCategory $move, ListCategories $list, SettingTargets $targets, ApiActor $actors): JsonResponse { - $input = $request->toData(); - $actor = $this->actors->of($request); - $store = $this->targets->store($input->param('store')); - $slug = $input->param('slug'); + $actor = $actors->of($request); + $store = $targets->store((string) $request->route('store')); + $slug = (string) $request->route('slug'); - if ($input->text('title') !== null) { - $this->rename->handle($store, $slug, $input->text('title'), $actor); + if ($request->title() !== null) { + $rename->handle($store, $slug, $request->title(), $actor); } - if ($input->hasParent) { - $this->move->handle($store, $slug, $input->text('parent'), $actor); + if ($request->movesParent()) { + $move->handle($store, $slug, $request->parent(), $actor); } - $categories = array_values(array_filter($this->list->handle($store, $actor), static fn (Category $category): bool => $category->slug->value === $slug)); + $found = array_values(array_filter($list->handle($store, $actor), static fn (Category $category): bool => $category->slug->value === $slug)); - return new JsonResponse(['data' => $categories === [] ? null : CategoryResource::fields($categories[0])]); + // The category is gone from the actor's view (moved out of reach): answered as no data. + return $found === [] ? new JsonResponse(['data' => null]) : CategoryResource::make($found[0])->response(); } - public function destroy(BodyRequest $request): JsonResponse + public function destroy(ReasonRequest $request, DeleteCategory $delete, SettingTargets $targets, ApiActor $actors): Response { - $input = $request->toData(); - $this->delete->handle($this->targets->store($input->param('store')), $input->param('slug'), $this->actors->of($request)); + $delete->handle($targets->store((string) $request->route('store')), (string) $request->route('slug'), $actors->of($request)); - return new JsonResponse(null, 204); + return new Response(status: 204); } } diff --git a/src/Http/Controllers/ChangesController.php b/src/Http/Controllers/ChangesController.php index c9379de..762f8fd 100644 --- a/src/Http/Controllers/ChangesController.php +++ b/src/Http/Controllers/ChangesController.php @@ -7,17 +7,13 @@ use Illuminate\Http\JsonResponse; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\ChangeFilter; -use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Enums\ChangeStatus; use Simtabi\Laranail\Settings\Data\ChangeDecision; use Simtabi\Laranail\Settings\Data\ChangeProposal; -use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Http\Support\ApiActor; -use Simtabi\Laranail\Settings\Data\Http\AddressInput; use Simtabi\Laranail\Settings\Http\Support\Addresses; -use Simtabi\Laranail\Settings\Http\Requests\BodyRequest; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; +use Simtabi\Laranail\Settings\Http\Requests\ReasonRequest; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Actions\Approvals\CancelChange; use Simtabi\Laranail\Settings\Actions\Approvals\QueryChanges; @@ -25,6 +21,8 @@ use Simtabi\Laranail\Settings\Actions\Approvals\ApproveChange; use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; use Simtabi\Laranail\Settings\Exceptions\UnknownChangeRequest; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; +use Simtabi\Laranail\Settings\Http\Requests\ProposeChangeRequest; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; use Simtabi\Laranail\Settings\Http\Resources\ChangeRequestResource; @@ -34,21 +32,10 @@ */ final readonly class ChangesController { - public function __construct( - private ApiActor $actors, - private Addresses $addresses, - private SettingTargets $targets, - private QueryChanges $query, - private ProposeChange $propose, - private ApproveChange $approve, - private RejectChange $reject, - private CancelChange $cancel, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, QueryChanges $query, SettingTargets $targets, ApiActor $actors): AnonymousResourceCollection { $page = $request->toData(); - $store = $this->targets->store($request->addressData()->store); + $store = $targets->store($request->addressData()->store); $status = $page->filter('status'); $key = $page->filter('key'); $filter = new ChangeFilter( @@ -56,66 +43,46 @@ public function index(PageRequest $request): JsonResponse $status === null ? null : (ChangeStatus::tryFrom($status) ?? throw new InvalidIdentifier(sprintf('status: [%s] is not a change status.', $status))), key: $key === null ? null : new Key($key), ); - $requests = $this->query->handle($filter, $this->actors->of($request), $page->limit + 1, $page->cursor); + $requests = $query->handle($filter, $actors->of($request), $page->limit + 1, $page->cursor); $next = count($requests) > $page->limit ? $requests[$page->limit - 1]->id : null; - return ListResponse::make(array_map(static fn (ChangeRequest $change): array => $change->toArray(), array_slice($requests, 0, $page->limit)), $next); + return ChangeRequestResource::collection(array_slice($requests, 0, $page->limit))->additional(['meta' => ['next_cursor' => $next]]); } - public function show(BodyRequest $request): JsonResponse + public function show(ReasonRequest $request, QueryChanges $query, SettingTargets $targets, ApiActor $actors): ChangeRequestResource { - $input = $request->toData(); - $store = $this->targets->store($input->param('store')); - $found = $this->query->handle(new ChangeFilter($store->name, id: $input->param('id')), $this->actors->of($request), 1); + $store = $targets->store((string) $request->route('store')); + $id = (string) $request->route('id'); + $found = $query->handle(new ChangeFilter($store->name, id: $id), $actors->of($request), 1); - return $this->render($found[0] ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store->name, $input->param('id')))); + return ChangeRequestResource::make($found[0] ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store->name, $id))); } - public function store(BodyRequest $request): JsonResponse + public function store(ProposeChangeRequest $request, ProposeChange $propose, Addresses $addresses, SettingTargets $targets, ApiActor $actors): JsonResponse { - $input = $request->toData(); - $owner = $input->array('owner'); - $address = $this->addresses->of(new AddressInput( - $input->param('store'), - (string) $input->text('key'), - is_string($owner['alias'] ?? null) ? $owner['alias'] : null, - is_string($owner['id'] ?? null) ? $owner['id'] : null, - $input->text('locale') ?? '', - )); - $operation = ChangeOperation::tryFrom($input->text('operation') ?? 'set') ?? ChangeOperation::Set; - $change = $this->propose->handle(new ChangeProposal($this->targets->target($address, $input->text('reason')), $operation, $input->value('value')), $this->actors->of($request, $input->text('reason'))); + $target = $targets->target($addresses->of($request->toData()), $request->reason()); + $change = $propose->handle(new ChangeProposal($target, $request->operation(), $request->input('value')), $actors->of($request, $request->reason())); - return $this->render($change, 202); + return ChangeRequestResource::make($change)->response()->setStatusCode(202); } - public function approve(BodyRequest $request): JsonResponse + public function approve(ReasonRequest $request, ApproveChange $approve, SettingTargets $targets, ApiActor $actors): ChangeRequestResource { - $input = $request->toData(); - - return $this->render($this->approve->handle($this->decision($input->param('store'), $input->param('id'), $input->text('reason')), $this->actors->of($request))); + return ChangeRequestResource::make($approve->handle($this->decision($request, $targets), $actors->of($request))); } - public function reject(BodyRequest $request): JsonResponse + public function reject(ReasonRequest $request, RejectChange $reject, SettingTargets $targets, ApiActor $actors): ChangeRequestResource { - $input = $request->toData(); - - return $this->render($this->reject->handle($this->decision($input->param('store'), $input->param('id'), $input->text('reason')), $this->actors->of($request))); - } - - public function cancel(BodyRequest $request): JsonResponse - { - $input = $request->toData(); - - return $this->render($this->cancel->handle($this->decision($input->param('store'), $input->param('id'), $input->text('reason')), $this->actors->of($request))); + return ChangeRequestResource::make($reject->handle($this->decision($request, $targets), $actors->of($request))); } - private function decision(string $store, string $id, ?string $reason): ChangeDecision + public function cancel(ReasonRequest $request, CancelChange $cancel, SettingTargets $targets, ApiActor $actors): ChangeRequestResource { - return new ChangeDecision($this->targets->store($store), $id, $reason); + return ChangeRequestResource::make($cancel->handle($this->decision($request, $targets), $actors->of($request))); } - private function render(ChangeRequest $change, int $status = 200): JsonResponse + private function decision(ReasonRequest $request, SettingTargets $targets): ChangeDecision { - return new JsonResponse(['data' => new ChangeRequestResource($change)->resolve()], $status); + return new ChangeDecision($targets->store((string) $request->route('store')), (string) $request->route('id'), $request->reason()); } } diff --git a/src/Http/Controllers/ConfigurationController.php b/src/Http/Controllers/ConfigurationController.php index 0b0a1a4..8bb0473 100644 --- a/src/Http/Controllers/ConfigurationController.php +++ b/src/Http/Controllers/ConfigurationController.php @@ -4,71 +4,60 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; -use Illuminate\Http\JsonResponse; +use Illuminate\Http\Response; use Simtabi\Laranail\Settings\Http\Support\ApiActor; use Simtabi\Laranail\Settings\Data\ConfigurationEntry; -use Simtabi\Laranail\Settings\Http\Requests\BodyRequest; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; +use Simtabi\Laranail\Settings\Http\Requests\ReasonRequest; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Simtabi\Laranail\Settings\Http\Resources\DefinitionResource; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; +use Simtabi\Laranail\Settings\Http\Requests\SaveDefinitionRequest; use Simtabi\Laranail\Settings\Actions\Configuration\SaveDefinition; use Simtabi\Laranail\Settings\Actions\Configuration\DeleteDefinition; +use Simtabi\Laranail\Settings\Http\Requests\SaveConfigurationRequest; +use Simtabi\Laranail\Settings\Http\Resources\ConfigurationEntryResource; use Simtabi\Laranail\Settings\Actions\Configuration\SaveConfigurationEntry; use Simtabi\Laranail\Settings\Actions\Configuration\DeleteConfigurationEntry; use Simtabi\Laranail\Settings\Actions\Configuration\ListConfigurationEntries; /** - * `/configuration/{stores|layers}/{name}` and `/configuration/definitions/{store}/{key}` (§16.11): + * `/configuration/{stores|layers}/{name}` and `/stores/{store}/definitions/{key}` (§16.11): * persisted configuration, edited as the actor, validated like the configuration file. */ final readonly class ConfigurationController { - public function __construct( - private ApiActor $actors, - private SettingTargets $targets, - private ListConfigurationEntries $list, - private SaveConfigurationEntry $save, - private DeleteConfigurationEntry $delete, - private SaveDefinition $saveDefinition, - private DeleteDefinition $deleteDefinition, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, ListConfigurationEntries $list, ApiActor $actors): AnonymousResourceCollection { - return ListResponse::make(array_map(static fn (ConfigurationEntry $entry): array => ['kind' => $entry->kind, 'name' => $entry->name, 'config' => (object) $entry->config], $this->list->handle($this->actors->of($request)))); + return ConfigurationEntryResource::collection($list->handle($actors->of($request)))->additional(['meta' => ['next_cursor' => null]]); } - public function update(BodyRequest $request): JsonResponse + public function update(SaveConfigurationRequest $request, SaveConfigurationEntry $save, ApiActor $actors): ConfigurationEntryResource { - $input = $request->toData(); - $entry = new ConfigurationEntry(rtrim($input->param('kind'), 's'), $input->param('name'), $input->array('config')); - $this->save->handle($entry, $this->actors->of($request)); + $entry = $request->toData(); + $save->handle($entry, $actors->of($request)); - return new JsonResponse(['data' => ['kind' => $entry->kind, 'name' => $entry->name, 'config' => (object) $entry->config]]); + return ConfigurationEntryResource::make($entry); } - public function destroy(BodyRequest $request): JsonResponse + public function destroy(ReasonRequest $request, DeleteConfigurationEntry $delete, ApiActor $actors): Response { - $input = $request->toData(); - $this->delete->handle(new ConfigurationEntry(rtrim($input->param('kind'), 's'), $input->param('name')), $this->actors->of($request)); + $delete->handle(new ConfigurationEntry(rtrim((string) $request->route('kind'), 's'), (string) $request->route('name')), $actors->of($request)); - return new JsonResponse(null, 204); + return new Response(status: 204); } - public function updateDefinition(BodyRequest $request): JsonResponse + public function updateDefinition(SaveDefinitionRequest $request, SaveDefinition $save, SettingTargets $targets, ApiActor $actors): DefinitionResource { - $input = $request->toData(); - $definition = $this->saveDefinition->handle($this->targets->store($input->param('store')), $input->param('key'), $input->array('attributes'), $this->actors->of($request)); + $definition = $save->handle($targets->store((string) $request->route('store')), (string) $request->route('key'), $request->definition(), $actors->of($request)); - return new JsonResponse(['data' => DefinitionResource::fields($definition)]); + return DefinitionResource::make($definition); } - public function destroyDefinition(BodyRequest $request): JsonResponse + public function destroyDefinition(ReasonRequest $request, DeleteDefinition $delete, SettingTargets $targets, ApiActor $actors): Response { - $input = $request->toData(); - $this->deleteDefinition->handle($this->targets->store($input->param('store')), $input->param('key'), $this->actors->of($request)); + $delete->handle($targets->store((string) $request->route('store')), (string) $request->route('key'), $actors->of($request)); - return new JsonResponse(null, 204); + return new Response(status: 204); } } diff --git a/src/Http/Controllers/HistoryController.php b/src/Http/Controllers/HistoryController.php index c5f5c35..faad4e1 100644 --- a/src/Http/Controllers/HistoryController.php +++ b/src/Http/Controllers/HistoryController.php @@ -5,47 +5,38 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; use Illuminate\Http\JsonResponse; -use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Http\Support\ApiActor; use Simtabi\Laranail\Settings\Http\Support\Addresses; use Simtabi\Laranail\Settings\Actions\RollbackSetting; use Simtabi\Laranail\Settings\Actions\Reads\ReadHistory; use Simtabi\Laranail\Settings\Actions\Reads\ReadSetting; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; use Simtabi\Laranail\Settings\Http\Resources\SettingResource; -use Simtabi\Laranail\Settings\Http\Requests\WriteSettingRequest; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; +use Simtabi\Laranail\Settings\Http\Resources\HistoryEntryResource; +use Simtabi\Laranail\Settings\Http\Requests\RollbackSettingRequest; /** `…/settings/{key}/history` and `…/rollback` (§4.3): a setting's versions, and returning to one. */ final readonly class HistoryController { - public function __construct( - private ApiActor $actors, - private Addresses $addresses, - private SettingTargets $targets, - private ReadHistory $history, - private RollbackSetting $rollback, - private ReadSetting $read, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, ReadHistory $history, Addresses $addresses, ApiActor $actors): AnonymousResourceCollection { $page = $request->toData(); - $result = $this->history->handle($this->addresses->of($request->addressData()), $this->actors->of($request), $page->limit, $page->cursor); + $result = $history->handle($addresses->of($request->addressData()), $actors->of($request), $page->limit, $page->cursor); - return ListResponse::make(array_map(static fn (HistoryEntry $entry): array => $entry->toArray(), $result->entries), $result->nextCursor); + return HistoryEntryResource::collection($result->entries)->additional(['meta' => ['next_cursor' => $result->nextCursor]]); } - public function rollback(WriteSettingRequest $request): JsonResponse + public function rollback(RollbackSettingRequest $request, RollbackSetting $rollback, ReadSetting $read, Addresses $addresses, SettingTargets $targets, ApiActor $actors): JsonResponse { $input = $request->toData(); - $actor = $this->actors->of($request, $input->reason); - $address = $this->addresses->of($input->address); + $actor = $actors->of($request, $input->reason); + $address = $addresses->of($input->address); - $this->rollback->handle($this->targets->target($address, $input->reason), $input->toVersion ?? 0, $actor); - $view = $this->read->handle($address, $actor); + $rollback->handle($targets->target($address, $input->reason), $input->toVersion ?? 0, $actor); + $view = $read->handle($address, $actor); - return new JsonResponse(['data' => SettingResource::fields($view)], 200, ['ETag' => $view->etag()]); + return SettingResource::make($view)->response()->header('ETag', $view->etag()); } } diff --git a/src/Http/Controllers/SettingsController.php b/src/Http/Controllers/SettingsController.php index 21d31c1..1a29384 100644 --- a/src/Http/Controllers/SettingsController.php +++ b/src/Http/Controllers/SettingsController.php @@ -4,6 +4,7 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; +use Illuminate\Http\Response; use Illuminate\Http\JsonResponse; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\SettingWrite; @@ -17,11 +18,11 @@ use Simtabi\Laranail\Settings\Http\Support\Addresses; use Simtabi\Laranail\Settings\Actions\Reads\ReadSetting; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; use Simtabi\Laranail\Settings\Actions\Reads\ReadSettings; use Simtabi\Laranail\Settings\Actions\Reads\ExplainSetting; use Simtabi\Laranail\Settings\Http\Requests\SettingRequest; use Simtabi\Laranail\Settings\Http\Resources\SettingResource; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; use Simtabi\Laranail\Settings\Http\Requests\WriteSettingRequest; use Simtabi\Laranail\Settings\Http\Resources\ExplanationResource; @@ -35,79 +36,66 @@ */ final readonly class SettingsController { - public function __construct( - private ApiActor $actors, - private Addresses $addresses, - private SettingTargets $targets, - private ReadSetting $read, - private ReadSettings $readMany, - private ExplainSetting $explain, - private SetSetting $set, - private ForgetSetting $forget, - private LockSetting $lock, - private UnlockSetting $unlock, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, ReadSettings $readMany, Addresses $addresses, ApiActor $actors): AnonymousResourceCollection { $page = $request->toData(); - $result = $this->readMany->handle($this->addresses->of($request->addressData()), $this->actors->of($request), $page->limit, $page->cursor); + $result = $readMany->handle($addresses->of($request->addressData()), $actors->of($request), $page->limit, $page->cursor); - return ListResponse::make(array_map(SettingResource::fields(...), $result['items']), $result['next']); + return SettingResource::collection($result['items'])->additional(['meta' => ['next_cursor' => $result['next']]]); } - public function show(SettingRequest $request): JsonResponse + public function show(SettingRequest $request, ReadSetting $read, Addresses $addresses, ApiActor $actors): JsonResponse { - $view = $this->read->handle($this->addresses->of($request->toData()), $this->actors->of($request)); + $view = $read->handle($addresses->of($request->toData()), $actors->of($request)); - return new JsonResponse(['data' => SettingResource::fields($view)], 200, ['ETag' => $view->etag()]); + return SettingResource::make($view)->response()->header('ETag', $view->etag()); } - public function explain(SettingRequest $request): JsonResponse + public function explain(SettingRequest $request, ExplainSetting $explain, Addresses $addresses, ApiActor $actors): ExplanationResource { - return new JsonResponse(['data' => ExplanationResource::fields($this->explain->handle($this->addresses->of($request->toData()), $this->actors->of($request)))]); + return ExplanationResource::make($explain->handle($addresses->of($request->toData()), $actors->of($request))); } - public function update(WriteSettingRequest $request): JsonResponse + public function update(WriteSettingRequest $request, SetSetting $set, ReadSetting $read, Addresses $addresses, SettingTargets $targets, ApiActor $actors): JsonResponse { $input = $request->toData(); - $actor = $this->actors->of($request, $input->reason); - $address = $this->addresses->of($input->address); - $expected = $this->expectedVersion($address, $input->ifMatch); - $change = $this->set->handle(new SettingWrite($this->targets->target($address, $input->reason), $input->value, $expected), $actor); + $actor = $actors->of($request, $input->reason); + $address = $addresses->of($input->address); + $expected = $this->expectedVersion($targets, $address, $input->ifMatch); + $change = $set->handle(new SettingWrite($targets->target($address, $input->reason), $input->value, $expected), $actor); - return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($address, $actor); + return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($read, $address, $actor); } - public function destroy(WriteSettingRequest $request): JsonResponse + public function destroy(WriteSettingRequest $request, ForgetSetting $forget, Addresses $addresses, SettingTargets $targets, ApiActor $actors): JsonResponse|Response { $input = $request->toData(); - $actor = $this->actors->of($request, $input->reason); - $address = $this->addresses->of($input->address); - $this->expectedVersion($address, $input->ifMatch); - $change = $this->forget->handle($this->targets->target($address, $input->reason), $actor); + $actor = $actors->of($request, $input->reason); + $address = $addresses->of($input->address); + $this->expectedVersion($targets, $address, $input->ifMatch); + $change = $forget->handle($targets->target($address, $input->reason), $actor); - return $change instanceof ChangeRequest ? $this->accepted($change) : new JsonResponse(null, 204); + return $change instanceof ChangeRequest ? $this->accepted($change) : new Response(status: 204); } - public function lock(WriteSettingRequest $request): JsonResponse + public function lock(WriteSettingRequest $request, LockSetting $lock, ReadSetting $read, Addresses $addresses, SettingTargets $targets, ApiActor $actors): JsonResponse { $input = $request->toData(); - $actor = $this->actors->of($request, $input->reason); - $address = $this->addresses->of($input->address); - $change = $this->lock->handle($this->targets->target($address, $input->reason), $actor); + $actor = $actors->of($request, $input->reason); + $address = $addresses->of($input->address); + $change = $lock->handle($targets->target($address, $input->reason), $actor); - return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($address, $actor); + return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($read, $address, $actor); } - public function unlock(WriteSettingRequest $request): JsonResponse + public function unlock(WriteSettingRequest $request, UnlockSetting $unlock, ReadSetting $read, Addresses $addresses, SettingTargets $targets, ApiActor $actors): JsonResponse { $input = $request->toData(); - $actor = $this->actors->of($request, $input->reason); - $address = $this->addresses->of($input->address); - $change = $this->unlock->handle($this->targets->target($address, $input->reason), $actor); + $actor = $actors->of($request, $input->reason); + $address = $addresses->of($input->address); + $change = $unlock->handle($targets->target($address, $input->reason), $actor); - return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($address, $actor); + return $change instanceof ChangeRequest ? $this->accepted($change) : $this->render($read, $address, $actor); } /** @@ -116,13 +104,13 @@ public function unlock(WriteSettingRequest $request): JsonResponse * * @throws ConcurrentModification */ - private function expectedVersion(SettingAddress $address, ?string $ifMatch): ?int + private function expectedVersion(SettingTargets $targets, SettingAddress $address, ?string $ifMatch): ?int { if ($ifMatch === null || $ifMatch === '*') { return null; } - $version = $this->targets->version($address); + $version = $targets->version($address); if (! in_array($address->etag($version), array_map(trim(...), explode(',', $ifMatch)), true)) { throw new ConcurrentModification(sprintf('Setting [%s] in store [%s] changed since it was read: its ETag no longer matches If-Match.', $address->key, $address->store)); @@ -131,15 +119,15 @@ private function expectedVersion(SettingAddress $address, ?string $ifMatch): ?in return $version; } - private function render(SettingAddress $address, Actor $actor): JsonResponse + private function render(ReadSetting $read, SettingAddress $address, Actor $actor): JsonResponse { - $view = $this->read->handle($address, $actor); + $view = $read->handle($address, $actor); - return new JsonResponse(['data' => SettingResource::fields($view)], 200, ['ETag' => $view->etag()]); + return SettingResource::make($view)->response()->header('ETag', $view->etag()); } private function accepted(ChangeRequest $change): JsonResponse { - return new JsonResponse(['data' => new ChangeRequestResource($change)->resolve()], 202); + return ChangeRequestResource::make($change)->response()->setStatusCode(202); } } diff --git a/src/Http/Controllers/StoresController.php b/src/Http/Controllers/StoresController.php index 646b5fc..ec6c384 100644 --- a/src/Http/Controllers/StoresController.php +++ b/src/Http/Controllers/StoresController.php @@ -4,35 +4,27 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; -use Illuminate\Http\JsonResponse; use Simtabi\Laranail\Settings\Http\Support\ApiActor; use Simtabi\Laranail\Settings\Actions\Reads\ListStores; use Simtabi\Laranail\Settings\Http\Requests\PageRequest; -use Simtabi\Laranail\Settings\Http\Support\ListResponse; use Simtabi\Laranail\Settings\Http\Resources\StoreResource; use Simtabi\Laranail\Settings\Actions\Reads\ListDefinitions; +use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Simtabi\Laranail\Settings\Http\Resources\DefinitionResource; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; /** `/stores` and `/stores/{store}/definitions`: what an API client can read and write. */ final readonly class StoresController { - public function __construct( - private ApiActor $actors, - private SettingTargets $targets, - private ListStores $stores, - private ListDefinitions $definitions, - ) {} - - public function index(PageRequest $request): JsonResponse + public function index(PageRequest $request, ListStores $stores, ApiActor $actors): AnonymousResourceCollection { - return ListResponse::make(array_map(StoreResource::fields(...), $this->stores->handle($this->actors->of($request)))); + return StoreResource::collection($stores->handle($actors->of($request)))->additional(['meta' => ['next_cursor' => null]]); } - public function definitions(PageRequest $request): JsonResponse + public function definitions(PageRequest $request, ListDefinitions $definitions, SettingTargets $targets, ApiActor $actors): AnonymousResourceCollection { - $definitions = $this->definitions->handle($this->targets->store($request->addressData()->store), $this->actors->of($request)); + $list = $definitions->handle($targets->store($request->addressData()->store), $actors->of($request)); - return ListResponse::make(array_map(DefinitionResource::fields(...), $definitions)); + return DefinitionResource::collection($list)->additional(['meta' => ['next_cursor' => null]]); } } diff --git a/src/Http/Controllers/TransferController.php b/src/Http/Controllers/TransferController.php index 871cccf..173aa68 100644 --- a/src/Http/Controllers/TransferController.php +++ b/src/Http/Controllers/TransferController.php @@ -4,17 +4,19 @@ namespace Simtabi\Laranail\Settings\Http\Controllers; -use Illuminate\Http\JsonResponse; -use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Http\Support\ApiActor; -use Simtabi\Laranail\Settings\Http\Requests\BodyRequest; use Simtabi\Laranail\Settings\Actions\Transfer\DiffStore; use Simtabi\Laranail\Settings\Data\Transfer\ExportRequest; use Simtabi\Laranail\Settings\Data\Transfer\ImportRequest; use Simtabi\Laranail\Settings\Actions\Transfer\ExportStore; use Simtabi\Laranail\Settings\Actions\Transfer\ImportStore; -use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; +use Simtabi\Laranail\Settings\Http\Requests\DiffStoreRequest; +use Simtabi\Laranail\Settings\Http\Requests\ExportStoreRequest; +use Simtabi\Laranail\Settings\Http\Requests\ImportStoreRequest; +use Simtabi\Laranail\Settings\Http\Resources\StoreDiffResource; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; +use Simtabi\Laranail\Settings\Http\Resources\ImportReportResource; +use Simtabi\Laranail\Settings\Http\Resources\ExportDocumentResource; /** * `/stores/{store}/export`, `/import` and `/diff` (G-42): the same document the console writes. @@ -23,40 +25,28 @@ */ final readonly class TransferController { - public function __construct( - private ApiActor $actors, - private SettingTargets $targets, - private ExportStore $export, - private ImportStore $import, - private DiffStore $diff, - ) {} - - public function export(BodyRequest $request): JsonResponse + public function export(ExportStoreRequest $request, ExportStore $export, SettingTargets $targets, ApiActor $actors): ExportDocumentResource { - $input = $request->toData(); - $mode = ExportMode::tryFrom($input->text('mode') ?? 'redacted') ?? ExportMode::Redacted; - $document = $this->export->handle(new ExportRequest($this->targets->store($input->param('store')), $mode), $this->actors->of($request)); + $document = $export->handle(new ExportRequest($targets->store((string) $request->route('store')), $request->mode()), $actors->of($request)); - return new JsonResponse(['data' => $document->toArray()]); + return ExportDocumentResource::make($document); } - public function import(BodyRequest $request): JsonResponse + public function import(ImportStoreRequest $request, ImportStore $import, SettingTargets $targets, ApiActor $actors): ImportReportResource { - $input = $request->toData(); - $report = $this->import->handle(new ImportRequest( - $this->targets->store($input->param('store')), - ExportDocument::fromArray($input->array('document')), - apply: $input->boolean('apply'), - ), $this->actors->of($request)); - - return new JsonResponse(['data' => $report->toArray()]); + $report = $import->handle(new ImportRequest( + $targets->store((string) $request->route('store')), + $request->document(), + apply: $request->boolean('apply'), + ), $actors->of($request)); + + return ImportReportResource::make($report); } - public function diff(BodyRequest $request): JsonResponse + public function diff(DiffStoreRequest $request, DiffStore $diff, SettingTargets $targets, ApiActor $actors): StoreDiffResource { - $input = $request->toData(); - $diff = $this->diff->handle($this->targets->store($input->param('store')), ExportDocument::fromArray($input->array('document')), $this->actors->of($request)); + $result = $diff->handle($targets->store((string) $request->route('store')), $request->document(), $actors->of($request)); - return new JsonResponse(['data' => $diff->toArray()]); + return StoreDiffResource::make($result); } } diff --git a/src/Http/Middleware/FreshControllers.php b/src/Http/Middleware/FreshControllers.php deleted file mode 100644 index f900478..0000000 --- a/src/Http/Middleware/FreshControllers.php +++ /dev/null @@ -1,31 +0,0 @@ -route(); - - if ($route instanceof Route) { - $route->flushController(); - } - - /** @var Response */ - return $next($request); - } -} diff --git a/src/Http/Requests/BodyRequest.php b/src/Http/Requests/BodyRequest.php deleted file mode 100644 index 33e7ee7..0000000 --- a/src/Http/Requests/BodyRequest.php +++ /dev/null @@ -1,79 +0,0 @@ -> */ - public function rules(): array - { - $name = (string) $this->route()?->getName(); - - return match (true) { - str_ends_with($name, 'changes.store') => [ - 'store' => ['nullable', 'string', 'max:64'], - 'key' => ['required', 'string', 'max:191'], - 'value' => ['nullable'], - 'owner' => ['nullable', 'array'], - 'owner.alias' => ['required_with:owner', 'string', 'max:64'], - 'owner.id' => ['required_with:owner', 'string', 'max:36'], - 'locale' => ['nullable', 'string', 'max:16'], - 'operation' => ['nullable', 'string', 'in:set,forget,lock,unlock'], - 'reason' => ['nullable', 'string', 'max:255'], - ], - str_ends_with($name, 'categories.store') => [ - 'slug' => ['required', 'string', 'max:128'], - 'title' => ['required', 'string', 'max:255'], - 'parent' => ['nullable', 'string', 'max:128'], - 'description' => ['nullable', 'string'], - 'icon' => ['nullable', 'string', 'max:255'], - 'sort_order' => ['nullable', 'integer', 'min:0'], - 'titles' => ['nullable', 'array'], - ], - str_ends_with($name, 'categories.update') => [ - 'title' => ['nullable', 'string', 'max:255'], - 'parent' => ['nullable', 'string', 'max:128'], - ], - str_ends_with($name, 'configuration.update') => ['config' => ['required', 'array']], - str_ends_with($name, 'definitions.update') => ['attributes' => ['present', 'array']], - str_ends_with($name, 'transfer.export') => ['mode' => ['nullable', 'string', 'in:redacted,ciphertext,plaintext']], - str_ends_with($name, 'transfer.import'), - str_ends_with($name, 'transfer.diff') => ['document' => ['required', 'array'], 'apply' => ['nullable', 'boolean']], - default => ['reason' => ['nullable', 'string', 'max:255']], - }; - } - - public function toData(): BodyInput - { - $params = []; - - foreach (['store', 'id', 'slug', 'kind', 'name', 'key'] as $parameter) { - $value = $this->route($parameter); - - if (is_string($value)) { - $params[$parameter] = $value; - } - } - - /** @var array $body */ - $body = $this->validated(); - - return new BodyInput($params, $body, $this->has('parent')); - } -} diff --git a/src/Http/Requests/DiffStoreRequest.php b/src/Http/Requests/DiffStoreRequest.php new file mode 100644 index 0000000..ef883d6 --- /dev/null +++ b/src/Http/Requests/DiffStoreRequest.php @@ -0,0 +1,32 @@ +> */ + public function rules(): array + { + return ['document' => ['required', 'array'], 'apply' => ['nullable', 'boolean']]; + } + + /** @throws InvalidImport */ + public function document(): ExportDocument + { + return ExportDocument::fromArray($this->array('document')); + } +} diff --git a/src/Http/Requests/ExportStoreRequest.php b/src/Http/Requests/ExportStoreRequest.php new file mode 100644 index 0000000..a73edc5 --- /dev/null +++ b/src/Http/Requests/ExportStoreRequest.php @@ -0,0 +1,30 @@ +> */ + public function rules(): array + { + return ['mode' => ['nullable', 'string', 'in:redacted,ciphertext,plaintext']]; + } + + public function mode(): ExportMode + { + return ExportMode::tryFrom($this->string('mode', 'redacted')->value()) ?? ExportMode::Redacted; + } +} diff --git a/src/Http/Requests/ImportStoreRequest.php b/src/Http/Requests/ImportStoreRequest.php new file mode 100644 index 0000000..3f432a8 --- /dev/null +++ b/src/Http/Requests/ImportStoreRequest.php @@ -0,0 +1,32 @@ +> */ + public function rules(): array + { + return ['document' => ['required', 'array'], 'apply' => ['nullable', 'boolean']]; + } + + /** @throws InvalidImport */ + public function document(): ExportDocument + { + return ExportDocument::fromArray($this->array('document')); + } +} diff --git a/src/Http/Requests/ProposeChangeRequest.php b/src/Http/Requests/ProposeChangeRequest.php new file mode 100644 index 0000000..63c5901 --- /dev/null +++ b/src/Http/Requests/ProposeChangeRequest.php @@ -0,0 +1,62 @@ +> */ + public function rules(): array + { + return [ + 'store' => ['nullable', 'string', 'max:64'], + 'key' => ['required', 'string', 'max:191'], + 'value' => ['nullable'], + 'owner' => ['nullable', 'array'], + 'owner.alias' => ['required_with:owner', 'string', 'max:64'], + 'owner.id' => ['required_with:owner', 'string', 'max:36'], + 'locale' => ['nullable', 'string', 'max:16'], + 'operation' => ['nullable', 'string', 'in:set,forget,lock,unlock'], + 'reason' => ['nullable', 'string', 'max:255'], + ]; + } + + /** The setting the change is for, as the URL and the body name it. */ + public function toData(): AddressInput + { + $alias = $this->input('owner.alias'); + $id = $this->input('owner.id'); + + return new AddressInput( + (string) $this->route('store'), + $this->string('key')->value(), + is_string($alias) ? $alias : null, + is_string($id) ? $id : null, + $this->string('locale')->value(), + ); + } + + public function operation(): ChangeOperation + { + return ChangeOperation::tryFrom($this->string('operation', 'set')->value()) ?? ChangeOperation::Set; + } + + public function reason(): ?string + { + return $this->filled('reason') ? $this->string('reason')->value() : null; + } +} diff --git a/src/Http/Requests/ReasonRequest.php b/src/Http/Requests/ReasonRequest.php new file mode 100644 index 0000000..ae05087 --- /dev/null +++ b/src/Http/Requests/ReasonRequest.php @@ -0,0 +1,30 @@ +> */ + public function rules(): array + { + return ['reason' => ['nullable', 'string', 'max:255']]; + } + + public function reason(): ?string + { + return $this->filled('reason') ? $this->string('reason')->value() : null; + } +} diff --git a/src/Http/Requests/RollbackSettingRequest.php b/src/Http/Requests/RollbackSettingRequest.php new file mode 100644 index 0000000..c84b9cd --- /dev/null +++ b/src/Http/Requests/RollbackSettingRequest.php @@ -0,0 +1,40 @@ +> */ + public function rules(): array + { + return $this->addressRules() + [ + 'reason' => ['nullable', 'string', 'max:255'], + 'version' => ['required', 'integer', 'min:1'], + ]; + } + + public function toData(): WriteInput + { + return new WriteInput( + $this->address(), + reason: $this->filled('reason') ? $this->string('reason')->value() : null, + toVersion: $this->integer('version'), + ); + } +} diff --git a/src/Http/Requests/SaveConfigurationRequest.php b/src/Http/Requests/SaveConfigurationRequest.php new file mode 100644 index 0000000..95c5f44 --- /dev/null +++ b/src/Http/Requests/SaveConfigurationRequest.php @@ -0,0 +1,31 @@ +> */ + public function rules(): array + { + return ['config' => ['required', 'array']]; + } + + public function toData(): ConfigurationEntry + { + return new ConfigurationEntry(rtrim((string) $this->route('kind'), 's'), (string) $this->route('name'), $this->array('config')); + } +} diff --git a/src/Http/Requests/SaveDefinitionRequest.php b/src/Http/Requests/SaveDefinitionRequest.php new file mode 100644 index 0000000..d4884e1 --- /dev/null +++ b/src/Http/Requests/SaveDefinitionRequest.php @@ -0,0 +1,31 @@ +` + * would hold them. + */ +final class SaveDefinitionRequest extends FormRequest +{ + public function authorize(): bool + { + return true; + } + + /** @return array> */ + public function rules(): array + { + return ['attributes' => ['present', 'array']]; + } + + /** @return array */ + public function definition(): array + { + return $this->array('attributes'); + } +} diff --git a/src/Http/Requests/StoreCategoryRequest.php b/src/Http/Requests/StoreCategoryRequest.php new file mode 100644 index 0000000..04d1905 --- /dev/null +++ b/src/Http/Requests/StoreCategoryRequest.php @@ -0,0 +1,46 @@ +> */ + public function rules(): array + { + return [ + 'slug' => ['required', 'string', 'max:128'], + 'title' => ['required', 'string', 'max:255'], + 'parent' => ['nullable', 'string', 'max:128'], + 'description' => ['nullable', 'string'], + 'icon' => ['nullable', 'string', 'max:255'], + 'sort_order' => ['nullable', 'integer', 'min:0'], + 'titles' => ['nullable', 'array'], + ]; + } + + public function toData(): NewCategory + { + return new NewCategory( + $this->string('slug')->value(), + $this->string('title')->value(), + $this->filled('parent') ? $this->string('parent')->value() : null, + $this->filled('description') ? $this->string('description')->value() : null, + $this->filled('icon') ? $this->string('icon')->value() : null, + $this->integer('sort_order'), + $this->array('titles'), + ); + } +} diff --git a/src/Http/Requests/UpdateCategoryRequest.php b/src/Http/Requests/UpdateCategoryRequest.php new file mode 100644 index 0000000..cad8acb --- /dev/null +++ b/src/Http/Requests/UpdateCategoryRequest.php @@ -0,0 +1,44 @@ +> */ + public function rules(): array + { + return [ + 'title' => ['nullable', 'string', 'max:255'], + 'parent' => ['nullable', 'string', 'max:128'], + ]; + } + + public function title(): ?string + { + return $this->filled('title') ? $this->string('title')->value() : null; + } + + /** Whether the body names `parent` at all. */ + public function movesParent(): bool + { + return $this->has('parent'); + } + + public function parent(): ?string + { + return $this->filled('parent') ? $this->string('parent')->value() : null; + } +} diff --git a/src/Http/Requests/WriteSettingRequest.php b/src/Http/Requests/WriteSettingRequest.php index c0b72ae..c7cfd7d 100644 --- a/src/Http/Requests/WriteSettingRequest.php +++ b/src/Http/Requests/WriteSettingRequest.php @@ -9,8 +9,8 @@ use Simtabi\Laranail\Settings\Http\Requests\Concerns\ReadsAddress; /** - * A write of one setting: `PUT` sends `{"value": …}`, `POST …/rollback` sends `{"version": n}`, - * and every write may send `reason`. `If-Match` makes it conditional on the ETag read. + * A write of one setting (update, forget, lock, unlock): `PUT` sends `{"value": …}`, and every + * write may send `reason`. `If-Match` makes it conditional on the ETag read. */ final class WriteSettingRequest extends FormRequest { @@ -30,17 +30,12 @@ public function rules(): array $rules['value'] = ['present']; } - if (str_ends_with($this->path(), '/rollback')) { - $rules['version'] = ['required', 'integer', 'min:1']; - } - return $rules; } public function toData(): WriteInput { $reason = $this->input('reason'); - $version = $this->input('version'); $ifMatch = $this->header('If-Match'); return new WriteInput( @@ -48,7 +43,6 @@ public function toData(): WriteInput $this->input('value'), is_string($reason) ? $reason : null, is_string($ifMatch) && $ifMatch !== '' ? $ifMatch : null, - is_numeric($version) ? (int) $version : null, ); } } diff --git a/src/Http/Resources/AuditEntryResource.php b/src/Http/Resources/AuditEntryResource.php new file mode 100644 index 0000000..037cdf2 --- /dev/null +++ b/src/Http/Resources/AuditEntryResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return $this->resource->toArray(); + } +} diff --git a/src/Http/Resources/CategoryResource.php b/src/Http/Resources/CategoryResource.php index 1639dd6..d678118 100644 --- a/src/Http/Resources/CategoryResource.php +++ b/src/Http/Resources/CategoryResource.php @@ -4,14 +4,29 @@ namespace Simtabi\Laranail\Settings\Http\Resources; +use Override; +use Illuminate\Http\Request; use Simtabi\Laranail\Settings\Data\Category; +use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Http\Resources\Attributes\PreserveKeys; -/** A category as the API returns it, by slug (its numeric id is internal, G-42). */ -final readonly class CategoryResource +/** + * A category as the API returns it, by slug (its numeric id is internal, G-42). + * + * @property Category $resource + */ +#[PreserveKeys] +final class CategoryResource extends JsonResource { + /** Always wrapped in `data`, whatever the application sets for its own resources. */ + public static $wrap = 'data'; + /** @return array */ - public static function fields(Category $category): array + #[Override] + public function toArray(Request $request): array { + $category = $this->resource; + return [ 'slug' => $category->slug->value, 'store' => $category->store->value, diff --git a/src/Http/Resources/ChangeRequestResource.php b/src/Http/Resources/ChangeRequestResource.php index 76b0986..26ebcc3 100644 --- a/src/Http/Resources/ChangeRequestResource.php +++ b/src/Http/Resources/ChangeRequestResource.php @@ -8,18 +8,18 @@ use Illuminate\Http\Request; use Illuminate\Http\Resources\Json\JsonResource; use Simtabi\Laranail\Settings\Data\ChangeRequest; +use Illuminate\Http\Resources\Attributes\PreserveKeys; /** * A change request (§16.7) without its proposed payload, which may be a secret. * * @property ChangeRequest $resource */ +#[PreserveKeys] final class ChangeRequestResource extends JsonResource { - public function __construct(ChangeRequest $request) - { - parent::__construct($request); - } + /** Always wrapped in `data`, whatever the application sets for its own resources. */ + public static $wrap = 'data'; /** @return array */ #[Override] diff --git a/src/Http/Resources/ConfigurationEntryResource.php b/src/Http/Resources/ConfigurationEntryResource.php new file mode 100644 index 0000000..4956bc1 --- /dev/null +++ b/src/Http/Resources/ConfigurationEntryResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return ['kind' => $this->resource->kind, 'name' => $this->resource->name, 'config' => (object) $this->resource->config]; + } +} diff --git a/src/Http/Resources/DefinitionResource.php b/src/Http/Resources/DefinitionResource.php index 5a39392..b2504e5 100644 --- a/src/Http/Resources/DefinitionResource.php +++ b/src/Http/Resources/DefinitionResource.php @@ -4,14 +4,28 @@ namespace Simtabi\Laranail\Settings\Http\Resources; +use Override; +use Illuminate\Http\Request; use Simtabi\Laranail\Settings\Data\Definition; +use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Http\Resources\Attributes\PreserveKeys; -/** A definition as the API lists it. An encrypted definition's default is left out. */ -final readonly class DefinitionResource +/** + * A definition as the API lists it. An encrypted definition's default is left out. + * + * @property Definition $resource + */ +#[PreserveKeys] +final class DefinitionResource extends JsonResource { + /** Always wrapped in `data`, whatever the application sets for its own resources. */ + public static $wrap = 'data'; + /** @return array */ - public static function fields(Definition $definition): array + #[Override] + public function toArray(Request $request): array { + $definition = $this->resource; $fields = [ 'store' => $definition->store->value, 'key' => $definition->key->value, diff --git a/src/Http/Resources/ExplanationResource.php b/src/Http/Resources/ExplanationResource.php index 9114626..7809572 100644 --- a/src/Http/Resources/ExplanationResource.php +++ b/src/Http/Resources/ExplanationResource.php @@ -4,21 +4,34 @@ namespace Simtabi\Laranail\Settings\Http\Resources; +use Override; +use Illuminate\Http\Request; +use Illuminate\Http\Resources\Json\JsonResource; use Simtabi\Laranail\Settings\Resolution\Explanation; +use Illuminate\Http\Resources\Attributes\PreserveKeys; -/** How a read resolved: the steps tried and the answer, its value left out when redacted. */ -final readonly class ExplanationResource +/** + * How a read resolved: the steps tried and the answer, its value left out when redacted. + * + * @property Explanation $resource + */ +#[PreserveKeys] +final class ExplanationResource extends JsonResource { + /** Always wrapped in `data`, whatever the application sets for its own resources. */ + public static $wrap = 'data'; + /** @return array */ - public static function fields(Explanation $explanation): array + #[Override] + public function toArray(Request $request): array { - $lookup = $explanation->lookup; + $lookup = $this->resource->lookup; $fields = [ 'found' => $lookup->isFound(), 'layer' => $lookup->layer(), 'from' => $lookup->scope()?->value, 'redacted' => $lookup->isRedacted(), - 'steps' => $explanation->steps, + 'steps' => $this->resource->steps, ]; if ($lookup->isFound() && ! $lookup->isRedacted()) { diff --git a/src/Http/Resources/ExportDocumentResource.php b/src/Http/Resources/ExportDocumentResource.php new file mode 100644 index 0000000..364771b --- /dev/null +++ b/src/Http/Resources/ExportDocumentResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return $this->resource->toArray(); + } +} diff --git a/src/Http/Resources/HistoryEntryResource.php b/src/Http/Resources/HistoryEntryResource.php new file mode 100644 index 0000000..0a6fca5 --- /dev/null +++ b/src/Http/Resources/HistoryEntryResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return $this->resource->toArray(); + } +} diff --git a/src/Http/Resources/ImportReportResource.php b/src/Http/Resources/ImportReportResource.php new file mode 100644 index 0000000..a81f2db --- /dev/null +++ b/src/Http/Resources/ImportReportResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return $this->resource->toArray(); + } +} diff --git a/src/Http/Resources/SettingResource.php b/src/Http/Resources/SettingResource.php index 2035318..b254835 100644 --- a/src/Http/Resources/SettingResource.php +++ b/src/Http/Resources/SettingResource.php @@ -10,6 +10,7 @@ use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\SettingView; use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Http\Resources\Attributes\PreserveKeys; /** * A setting as the API returns it. A value the actor may not see is left out (`redacted` true), @@ -17,16 +18,17 @@ * * @property SettingView $resource */ +#[PreserveKeys] final class SettingResource extends JsonResource { - public function __construct(SettingView $view) - { - parent::__construct($view); - } + /** Always wrapped in `data`, whatever the application sets for its own resources. */ + public static $wrap = 'data'; /** @return array */ - public static function fields(SettingView $view): array + #[Override] + public function toArray(Request $request): array { + $view = $this->resource; $fields = [ 'store' => $view->address->store, 'scope' => Scope::of($view->address->ownerRef())->value, @@ -45,11 +47,4 @@ public static function fields(SettingView $view): array return $fields; } - - /** @return array */ - #[Override] - public function toArray(Request $request): array - { - return self::fields($this->resource); - } } diff --git a/src/Http/Resources/StoreDiffResource.php b/src/Http/Resources/StoreDiffResource.php new file mode 100644 index 0000000..097e4a5 --- /dev/null +++ b/src/Http/Resources/StoreDiffResource.php @@ -0,0 +1,30 @@ + */ + #[Override] + public function toArray(Request $request): array + { + return $this->resource->toArray(); + } +} diff --git a/src/Http/Resources/StoreResource.php b/src/Http/Resources/StoreResource.php index 7eed0ff..2976693 100644 --- a/src/Http/Resources/StoreResource.php +++ b/src/Http/Resources/StoreResource.php @@ -4,24 +4,37 @@ namespace Simtabi\Laranail\Settings\Http\Resources; +use Override; +use Illuminate\Http\Request; use Simtabi\Laranail\Settings\Stores\Layer; use Simtabi\Laranail\Settings\Stores\Store; +use Illuminate\Http\Resources\Json\JsonResource; +use Illuminate\Http\Resources\Attributes\PreserveKeys; -/** A configured store as the API lists it: its name, mode, owners, layers and policies. */ -final readonly class StoreResource +/** + * A configured store as the API lists it: its name, mode, owners, layers and policies. + * + * @property Store $resource + */ +#[PreserveKeys] +final class StoreResource extends JsonResource { + /** Always wrapped in `data`, whatever the application sets for its own resources. */ + public static $wrap = 'data'; + /** @return array */ - public static function fields(Store $store): array + #[Override] + public function toArray(Request $request): array { return [ - 'name' => $store->name->value, - 'mode' => $store->mode->value, - 'owners' => $store->owners, - 'layers' => array_map(static fn (Layer $layer): string => $layer->name, $store->layers), - 'strict' => $store->strict, - 'inherits' => $store->inherits, - 'fallback' => $store->fallback?->value, - 'approvals' => $store->approvalKeys, + 'name' => $this->resource->name->value, + 'mode' => $this->resource->mode->value, + 'owners' => $this->resource->owners, + 'layers' => array_map(static fn (Layer $layer): string => $layer->name, $this->resource->layers), + 'strict' => $this->resource->strict, + 'inherits' => $this->resource->inherits, + 'fallback' => $this->resource->fallback?->value, + 'approvals' => $this->resource->approvalKeys, ]; } } diff --git a/src/Http/Support/Addresses.php b/src/Http/Support/Addresses.php index c4e9359..9c59ddd 100644 --- a/src/Http/Support/Addresses.php +++ b/src/Http/Support/Addresses.php @@ -6,14 +6,14 @@ use Simtabi\Laranail\Settings\Data\SettingAddress; use Simtabi\Laranail\Settings\Data\Http\AddressInput; -use Simtabi\Laranail\Settings\Contracts\OwnerResolver; use Simtabi\Laranail\Settings\Exceptions\UnknownOwner; +use Simtabi\Laranail\Settings\Owners\MorphMapOwnerResolver; /** Turns what a URL names into a {@see SettingAddress}, resolving the owner by alias and id. */ final readonly class Addresses { public function __construct( - private OwnerResolver $owners, + private MorphMapOwnerResolver $owners, ) {} /** @throws UnknownOwner */ diff --git a/src/Http/Support/ListResponse.php b/src/Http/Support/ListResponse.php deleted file mode 100644 index 2064ccc..0000000 --- a/src/Http/Support/ListResponse.php +++ /dev/null @@ -1,17 +0,0 @@ -> $items */ - public static function make(array $items, ?string $nextCursor = null): JsonResponse - { - return new JsonResponse(['data' => $items, 'meta' => ['next_cursor' => $nextCursor]]); - } -} diff --git a/src/Http/Support/Problems.php b/src/Http/Support/Problems.php index 427afd8..097b747 100644 --- a/src/Http/Support/Problems.php +++ b/src/Http/Support/Problems.php @@ -9,74 +9,34 @@ use Illuminate\Http\JsonResponse; use Illuminate\Auth\AuthenticationException; use Illuminate\Validation\ValidationException; -use Simtabi\Laranail\Settings\Exceptions\AccessDenied; -use Simtabi\Laranail\Settings\Exceptions\TypeMismatch; -use Simtabi\Laranail\Settings\Exceptions\UnknownOwner; -use Simtabi\Laranail\Settings\Exceptions\UnknownStore; -use Simtabi\Laranail\Settings\Exceptions\ActorRequired; -use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; -use Simtabi\Laranail\Settings\Exceptions\InvalidImport; -use Simtabi\Laranail\Settings\Exceptions\LockedSetting; -use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; +use Illuminate\Contracts\Translation\Translator; use Illuminate\Http\Exceptions\ThrottleRequestsException; -use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; -use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; -use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; -use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; -use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; -use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -use Simtabi\Laranail\Settings\Exceptions\HistoryUnavailable; -use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; -use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; -use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; -use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Exceptions\UnknownChangeRequest; -use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; -use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; -use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; /** - * RFC 9457 problem details (`application/problem+json`) for the REST API (§16.10): one `type` per - * exception, the status the design maps it to, and the exception's message as `detail` (the - * package's messages name stores, keys and scopes, never a value). Anything the package does not - * know is left to the application's own handler. + * RFC 9457 problem details (`application/problem+json`) for the REST API (§16.10). A package + * exception names its own status and problem type ({@see SettingsException::STATUS} and + * {@see SettingsException::TYPE}), and its message is the `detail` (the package's messages name + * stores, keys and scopes, never a value). Anything the package does not know is left to the + * application's own handler. + * + * Titles, and the details of problems that carry no exception message, are the + * `laranail/settings` translations; a type without a translated title (an `http-` + * problem) keeps the title derived from its type. */ final readonly class Problems { public const string TYPE_BASE = 'https://opensource.simtabi.com/documentation/laranail/settings/problems/'; - /** @var array, array{int, string}> */ - private const array MAP = [ - AccessDenied::class => [403, 'access-denied'], - ActorRequired::class => [401, 'actor-required'], - VerificationRequired::class => [428, 'verification-required'], - UnknownStore::class => [404, 'unknown-store'], - UnknownSetting::class => [404, 'unknown-setting'], - UnknownOwner::class => [404, 'unknown-owner'], - UnknownCategory::class => [404, 'unknown-category'], - UnknownChangeRequest::class => [404, 'unknown-change-request'], - InvalidSettingValue::class => [422, 'invalid-value'], - InvalidIdentifier::class => [422, 'invalid-identifier'], - InvalidImport::class => [422, 'invalid-import'], - InvalidDefinition::class => [422, 'invalid-definition'], - InvalidConfiguration::class => [422, 'invalid-configuration'], - TypeMismatch::class => [422, 'type-mismatch'], - CategoryCycle::class => [422, 'category-cycle'], - CategoryStoreMismatch::class => [422, 'category-store-mismatch'], - LockedSetting::class => [423, 'locked'], - ConcurrentModification::class => [412, 'precondition-failed'], - ApprovalUnavailable::class => [409, 'approval-unavailable'], - ChangeRequestClosed::class => [409, 'change-request-closed'], - OwnerNotAllowed::class => [409, 'owner-not-allowed'], - StoreNotWritable::class => [409, 'store-not-writable'], - HistoryUnavailable::class => [409, 'history-unavailable'], - DriverUnavailable::class => [503, 'unavailable'], - ]; + private const string LINES = 'laranail/settings::settings.'; + + public function __construct( + private Translator $translator, + ) {} /** The problem response for an exception raised by an API route, or null to leave it alone. */ - public static function render(Throwable $exception, Request $request): ?JsonResponse + public function render(Throwable $exception, Request $request): ?JsonResponse { $route = $request->route(); @@ -85,37 +45,33 @@ public static function render(Throwable $exception, Request $request): ?JsonResp } return match (true) { - $exception instanceof ValidationException => self::make(422, 'validation', 'The request is invalid.', $request, ['errors' => $exception->errors()]), - $exception instanceof AuthenticationException => self::make(401, 'unauthenticated', 'Authentication is required.', $request), - $exception instanceof ThrottleRequestsException => self::make(429, 'too-many-requests', 'Too many requests.', $request), - $exception instanceof SettingsException => self::forSettings($exception, $request), - $exception instanceof HttpExceptionInterface => self::make($exception->getStatusCode(), 'http-' . $exception->getStatusCode(), $exception->getMessage() !== '' ? $exception->getMessage() : 'The request failed.', $request), + $exception instanceof ValidationException => $this->make(422, 'validation', $this->line('problems.validation'), $request, ['errors' => $exception->errors()]), + $exception instanceof AuthenticationException => $this->make(401, 'unauthenticated', $this->line('problems.unauthenticated'), $request), + $exception instanceof ThrottleRequestsException => $this->make(429, 'too-many-requests', $this->line('problems.too-many-requests'), $request), + $exception instanceof SettingsException => $this->make($exception::STATUS, $exception::TYPE, $exception::TYPE === SettingsException::TYPE ? $this->line('problems.settings-error') : $exception->getMessage(), $request), + $exception instanceof HttpExceptionInterface => $this->make($exception->getStatusCode(), 'http-' . $exception->getStatusCode(), $exception->getMessage() !== '' ? $exception->getMessage() : $this->line('problems.http'), $request), default => null, }; } - /** - * @param array $extra - */ - public static function make(int $status, string $type, string $detail, ?Request $request = null, array $extra = []): JsonResponse + /** @param array $extra */ + public function make(int $status, string $type, string $detail, ?Request $request = null, array $extra = []): JsonResponse { + $title = $this->translator->get(self::LINES . 'problems.titles.' . $type); + return new JsonResponse([ 'type' => self::TYPE_BASE . $type, - 'title' => ucfirst(str_replace('-', ' ', $type)), + 'title' => is_string($title) && $title !== self::LINES . 'problems.titles.' . $type ? $title : ucfirst(str_replace('-', ' ', $type)), 'status' => $status, 'detail' => $detail, 'instance' => $request?->getRequestUri(), ] + $extra, $status, ['Content-Type' => 'application/problem+json']); } - private static function forSettings(SettingsException $exception, Request $request): JsonResponse + private function line(string $key): string { - foreach (self::MAP as $class => [$status, $type]) { - if ($exception instanceof $class) { - return self::make($status, $type, $exception->getMessage(), $request); - } - } + $line = $this->translator->get(self::LINES . $key); - return self::make(500, 'settings-error', 'The settings operation failed.', $request); + return is_string($line) ? $line : $key; } } diff --git a/src/Listeners/SendSettingsAlert.php b/src/Listeners/SendSettingsAlert.php index 5868766..0c5431b 100644 --- a/src/Listeners/SendSettingsAlert.php +++ b/src/Listeners/SendSettingsAlert.php @@ -4,12 +4,14 @@ namespace Simtabi\Laranail\Settings\Listeners; -use Closure; use Throwable; -use Carbon\CarbonImmutable; use Psr\Log\LoggerInterface; use Illuminate\Database\Eloquent\Model; +use Simtabi\Laranail\Settings\Data\Key; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Data\AlertRule; +use Simtabi\Laranail\Settings\Data\StoreName; +use Illuminate\Contracts\Translation\Translator; use Simtabi\Laranail\Settings\Data\AlertContext; use Illuminate\Notifications\AnonymousNotifiable; use Simtabi\Laranail\Settings\Events\AuditPruned; @@ -34,7 +36,9 @@ use Simtabi\Laranail\Settings\Events\DefinitionsSynced; use Simtabi\Laranail\Settings\Events\SettingRolledBack; use Simtabi\Laranail\Settings\Notifications\SettingsAlert; +use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Events\VerificationWasRequired; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Illuminate\Contracts\Notifications\Dispatcher as Notifications; /** @@ -78,15 +82,15 @@ /** * @param list $rules - * @param Closure(?string, ?string): bool $sensitive whether a store's key is sensitive or encrypted - * @param Closure(): CarbonImmutable $clock + * @param Definitions $definitions whether a store's key is sensitive or encrypted (code and runtime definitions only) */ public function __construct( private Notifications $notifications, private array $rules, - private Closure $sensitive, - private Closure $clock, + private Definitions $definitions, + private Clock $clock, private LoggerInterface $logger, + private Translator $translator, private ?Cache $cache = null, private int $throttle = 0, private string $prefix = 'laranail-settings', @@ -98,8 +102,8 @@ public function handle(object $event): void return; } - $probe = AlertContext::fromEvent($event, false, ($this->clock)()); - $context = AlertContext::fromEvent($event, ($this->sensitive)($probe->store, $probe->key), $probe->occurredAt); + $probe = AlertContext::fromEvent($event, false, $this->clock->now()); + $context = AlertContext::fromEvent($event, $this->sensitive($probe->store, $probe->key), $probe->occurredAt); foreach ($this->rules as $index => $rule) { if (! $rule->matches($event, $context) || $this->throttled($index, $context)) { @@ -131,18 +135,42 @@ private function send(AlertRule $rule, AlertContext $context): void } if ($channels !== []) { - $this->deliver($anonymous, new SettingsAlert($context, $channels), $rule->queue); + $this->deliver($anonymous, new SettingsAlert($context, $channels, texts: $this->texts()), $rule->queue); } if ($rule->database !== null) { $notifiable = $this->notifiable($rule->database); if ($notifiable instanceof Model) { - $this->deliver($notifiable, new SettingsAlert($context, ['database']), $rule->queue); + $this->deliver($notifiable, new SettingsAlert($context, ['database'], texts: $this->texts()), $rule->queue); } } } + /** + * The alert's labels and footer in the current locale. + * + * @return array + */ + private function texts(): array + { + return SettingsAlert::texts($this->translator); + } + + /** Whether the event's key is sensitive or encrypted, by its code or runtime definition. */ + private function sensitive(?string $store, ?string $key): bool + { + if ($store === null || $key === null) { + return false; + } + + try { + return $this->definitions->findInCode(new StoreName($store), new Key($key))?->isSensitive() ?? false; + } catch (SettingsException) { + return false; + } + } + private function deliver(object $notifiable, SettingsAlert $alert, ?string $queue): void { if ($queue === null) { diff --git a/src/Notifications/SettingsAlert.php b/src/Notifications/SettingsAlert.php index efaa08a..a287e18 100644 --- a/src/Notifications/SettingsAlert.php +++ b/src/Notifications/SettingsAlert.php @@ -8,6 +8,7 @@ use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Contracts\Translation\Translator; use Simtabi\Laranail\Settings\Data\AlertContext; use Illuminate\Notifications\Messages\MailMessage; @@ -17,6 +18,10 @@ * {@see AlertContext}, which holds identifiers only (store, key, scope, actor, outcome, time) and * never a setting's value, so no channel can show one. Queued on the rule's queue when it names * one; sent at once otherwise. + * + * The mail is the markdown view `laranail/settings::mail.alert`. Its labels and footer are the + * `laranail/settings` translations, resolved when the alert is built ({@see texts()}) so a queued + * copy carries plain strings; an alert built without them reads the translator when it renders. */ final class SettingsAlert extends Notification implements ShouldQueue { @@ -28,16 +33,57 @@ final class SettingsAlert extends Notification implements ShouldQueue */ public const string SLACK_MESSAGE = 'Illuminate\\Notifications\\Messages\\' . 'SlackMessage'; + /** The markdown mail view. */ + public const string VIEW = 'laranail/settings::mail.alert'; + + /** The translation namespace and file the alert's lines live in. */ + private const string NAMESPACE = 'laranail/settings::settings.'; + + /** The message keys an alert reads ({@see texts()}). */ + private const array KEYS = [ + 'alert.labels.event', + 'alert.labels.store', + 'alert.labels.key', + 'alert.labels.scope', + 'alert.labels.locale', + 'alert.labels.actor', + 'alert.labels.outcome', + 'alert.labels.at', + 'alert.yes', + 'alert.no', + 'alert.footer', + ]; + /** * @param list $channels the channels this copy is sent on * @param string $slackMessage the Slack message class to build (the Slack channel package's, by default) + * @param array $texts translated labels and footer by message key ({@see texts()}); read from the translator when empty */ public function __construct( public readonly AlertContext $context, public readonly array $channels, public readonly string $slackMessage = self::SLACK_MESSAGE, + public readonly array $texts = [], ) {} + /** + * The alert's labels and footer in the current locale, by message key: built once, when the + * alert is, so a queued alert serializes strings rather than a translator. + * + * @return array + */ + public static function texts(Translator $translator): array + { + $texts = []; + + foreach (self::KEYS as $key) { + $line = $translator->get(self::NAMESPACE . $key); + $texts[$key] = is_string($line) ? $line : $key; + } + + return $texts; + } + /** Whether Slack alerts can be sent (the Slack channel package is installed). */ public static function slackAvailable(): bool { @@ -52,15 +98,15 @@ public function via(object $notifiable): array public function toMail(object $notifiable): MailMessage { - $mail = new MailMessage() + return new MailMessage() ->subject($this->context->headline()) - ->line($this->context->headline() . '.'); - - foreach ($this->lines() as $label => $value) { - $mail->line(sprintf('%s: %s', $label, $value)); - } - - return $mail->line('Values are never included in alerts; read the setting or its history to see what changed.'); + // Larastan resolves views without the package's provider, so it cannot see the + // `laranail/settings` namespace this view lives in; PackageLayoutTest proves it exists. + ->markdown(self::VIEW, [ // @phpstan-ignore argument.type + 'headline' => $this->context->headline(), + 'lines' => $this->lines(), + 'footer' => $this->text('alert.footer'), + ]); } /** @return array */ @@ -103,20 +149,27 @@ public function toSlack(object $notifiable): ?object private function lines(): array { $lines = [ - 'Event' => $this->context->event, - 'Store' => $this->context->store ?? '-', - 'Key' => $this->context->key ?? '-', - 'Scope' => $this->context->scope ?? '-', - 'Locale' => $this->context->locale === null || $this->context->locale === '' ? '-' : $this->context->locale, - 'Actor' => $this->context->actor, - 'Outcome' => $this->context->outcome, - 'At' => $this->context->occurredAt->toIso8601String(), + $this->text('alert.labels.event') => $this->context->event, + $this->text('alert.labels.store') => $this->context->store ?? '-', + $this->text('alert.labels.key') => $this->context->key ?? '-', + $this->text('alert.labels.scope') => $this->context->scope ?? '-', + $this->text('alert.labels.locale') => $this->context->locale === null || $this->context->locale === '' ? '-' : $this->context->locale, + $this->text('alert.labels.actor') => $this->context->actor, + $this->text('alert.labels.outcome') => $this->context->outcome, + $this->text('alert.labels.at') => $this->context->occurredAt->toIso8601String(), ]; foreach ($this->context->details as $name => $value) { - $lines[ucfirst(str_replace('_', ' ', $name))] = is_bool($value) ? ($value ? 'yes' : 'no') : (string) ($value ?? '-'); + $lines[ucfirst(str_replace('_', ' ', $name))] = is_bool($value) ? $this->text($value ? 'alert.yes' : 'alert.no') : (string) ($value ?? '-'); } return $lines; } + + private function text(string $key): string + { + $line = $this->texts[$key] ?? __(self::NAMESPACE . $key); + + return is_string($line) ? $line : $key; + } } diff --git a/src/Owners/MorphMapOwnerResolver.php b/src/Owners/MorphMapOwnerResolver.php index 1300e3e..87f29aa 100644 --- a/src/Owners/MorphMapOwnerResolver.php +++ b/src/Owners/MorphMapOwnerResolver.php @@ -4,30 +4,33 @@ namespace Simtabi\Laranail\Settings\Owners; -use Closure; use Illuminate\Database\Eloquent\Model; +use Illuminate\Container\Attributes\Config; +use Illuminate\Container\Attributes\Scoped; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Contracts\Settable; -use Simtabi\Laranail\Settings\Contracts\OwnerResolver; +use Illuminate\Database\Eloquent\Relations\Relation; use Simtabi\Laranail\Settings\Exceptions\UnknownOwner; use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** - * The default {@see OwnerResolver}: the alias must be in the morph map (or in `http.owners`). A + * Resolves the owner a REST URL names: the alias must be in `http.owners` or the morph map. A * model that is {@see Settable} is loaded, so its parents take part in reads; a missing record is * UnknownOwner. Any other mapped class, or a model whose own morph alias differs (mapped only in * `http.owners`), is addressed by alias and id alone. */ -final readonly class MorphMapOwnerResolver implements OwnerResolver +#[Scoped] +final readonly class MorphMapOwnerResolver { - /** @param Closure(string): ?string $morphed the class an alias maps to */ + /** @param array $owners `http.owners`: alias => class, for aliases outside the morph map */ public function __construct( - private Closure $morphed, + #[Config('laranail.settings.http.owners', [])] + private array $owners = [], ) {} public function resolve(string $alias, string $id): Settable|OwnerRef { - $class = ($this->morphed)($alias); + $class = is_string($this->owners[$alias] ?? null) ? $this->owners[$alias] : Relation::getMorphedModel($alias); if (! is_string($class) || ! class_exists($class)) { throw new UnknownOwner(sprintf('Owner alias [%s] is not in the morph map.', $alias)); diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index b6a1c83..c11fc01 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -4,185 +4,117 @@ namespace Simtabi\Laranail\Settings\Providers; -use Closure; use Override; use Throwable; use Psr\Log\LogLevel; use Psr\Log\NullLogger; -use Carbon\CarbonImmutable; use Illuminate\Http\Request; use InvalidArgumentException; use Illuminate\Log\LogManager; -use Illuminate\Routing\Router; -use Illuminate\Http\JsonResponse; -use Illuminate\Database\Connection; use Illuminate\Filesystem\Filesystem; -use Simtabi\Laranail\Settings\Data\Key; +use Illuminate\Support\Facades\Route; use Illuminate\Cache\RateLimiting\Limit; -use Illuminate\Contracts\Session\Session; use Simtabi\Laranail\Settings\Data\Actor; -use Simtabi\Laranail\Settings\Data\Scope; use Illuminate\Contracts\Auth\Access\Gate; use Illuminate\Queue\Events\JobProcessing; use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Events\Dispatcher; -use Illuminate\Support\Facades\RateLimiter; use Simtabi\Laranail\Package\Tools\Package; -use Simtabi\Laranail\Settings\Stores\Store; -use Illuminate\Contracts\Validation\Factory; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Data\AlertRule; use Simtabi\Laranail\Settings\Data\StoreName; -use Simtabi\Laranail\Settings\Http\ApiRoutes; -use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\SettingsManager; use Illuminate\Database\Events\MigrationsEnded; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Contracts\Foundation\Application; +use Illuminate\Contracts\Translation\Translator; use Simtabi\Laranail\Settings\Actions\MakeStore; -use Simtabi\Laranail\Settings\Actions\WarmCache; use Simtabi\Laranail\Settings\Enums\AuditAction; use Illuminate\Contracts\Cache\Factory as Caches; +use Illuminate\Contracts\Foundation\CachesRoutes; use Simtabi\Laranail\Settings\Actions\ClearCache; -use Simtabi\Laranail\Settings\Actions\FlushScope; -use Simtabi\Laranail\Settings\Actions\PruneAudit; -use Simtabi\Laranail\Settings\Actions\QueryAudit; -use Simtabi\Laranail\Settings\Actions\SetSetting; -use Simtabi\Laranail\Settings\Actions\WriteGuard; use Simtabi\Laranail\Settings\Audit\LogAuditSink; use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -use Simtabi\Laranail\Settings\Actions\DiffHistory; -use Simtabi\Laranail\Settings\Actions\FindOrphans; -use Simtabi\Laranail\Settings\Actions\LockSetting; use Simtabi\Laranail\Settings\Audit\AutoAuditSink; use Simtabi\Laranail\Settings\Audit\NullAuditSink; use Simtabi\Laranail\Settings\Console\DiffCommand; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Data\ApprovalPolicy; -use Simtabi\Laranail\Settings\Events\LayerSkipped; use Simtabi\Laranail\Settings\Models\ModelContext; use Simtabi\Laranail\Settings\Typed\TypedSettings; use Illuminate\Cache\Repository as CacheRepository; -use Simtabi\Laranail\Settings\Actions\PromoteStore; -use Simtabi\Laranail\Settings\Actions\PruneHistory; -use Simtabi\Laranail\Settings\Actions\PruneOrphans; -use Simtabi\Laranail\Settings\Actions\QueryHistory; -use Simtabi\Laranail\Settings\Actions\StoreActions; use Simtabi\Laranail\Settings\Contracts\Authorizer; use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Database\SchemaShape; -use Simtabi\Laranail\Settings\Support\ConfigValues; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Illuminate\Contracts\Encryption\StringEncrypter; use Illuminate\Database\ConnectionResolverInterface; -use Illuminate\Database\Eloquent\Relations\Relation; -use Simtabi\Laranail\Settings\Actions\ForgetSetting; -use Simtabi\Laranail\Settings\Actions\UnlockSetting; use Simtabi\Laranail\Settings\Console\DoctorCommand; use Simtabi\Laranail\Settings\Console\ExportCommand; use Simtabi\Laranail\Settings\Console\ImportCommand; use Simtabi\Laranail\Settings\Http\Support\Problems; use Illuminate\Contracts\Auth\Factory as AuthFactory; use Illuminate\Contracts\Filesystem\Factory as Disks; -use Simtabi\Laranail\Settings\Actions\HistoryActions; -use Simtabi\Laranail\Settings\Actions\SettingActions; use Simtabi\Laranail\Settings\Console\HistoryCommand; -use Simtabi\Laranail\Settings\Console\OpenApiCommand; use Simtabi\Laranail\Settings\Console\PromoteCommand; use Simtabi\Laranail\Settings\Console\RescopeCommand; use Simtabi\Laranail\Settings\Drivers\ReadOnlyValues; use Simtabi\Laranail\Settings\Typed\SettingsMigrator; use Simtabi\Laranail\Settings\Actions\MigrateSettings; -use Simtabi\Laranail\Settings\Actions\RollbackSetting; use Simtabi\Laranail\Settings\Actions\SyncDefinitions; use Simtabi\Laranail\Settings\Audit\DatabaseAuditSink; use Simtabi\Laranail\Settings\Contracts\ActorResolver; -use Simtabi\Laranail\Settings\Contracts\OwnerResolver; use Simtabi\Laranail\Settings\Services\Access\Auditor; use Simtabi\Laranail\Settings\Typed\SettingsMigration; -use Simtabi\Laranail\Settings\Actions\DiagnoseSettings; use Simtabi\Laranail\Settings\Console\MakeStoreCommand; use Simtabi\Laranail\Settings\Console\ReencryptCommand; use Simtabi\Laranail\Settings\Console\WarmCacheCommand; -use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; -use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; -use Simtabi\Laranail\Settings\Contracts\ValueValidator; use Simtabi\Laranail\Settings\Support\RecordSerializer; use Simtabi\Laranail\Settings\Actions\FindForeignTables; use Simtabi\Laranail\Settings\Console\ClearCacheCommand; use Simtabi\Laranail\Settings\Console\PruneAuditCommand; use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Simtabi\Laranail\Settings\Verification\NullVerifier; -use Simtabi\Laranail\Settings\Actions\Transfer\DiffStore; use Simtabi\Laranail\Settings\Listeners\LogSettingsEvent; use Simtabi\Laranail\Settings\Console\PruneChangesCommand; use Simtabi\Laranail\Settings\Console\PruneHistoryCommand; use Simtabi\Laranail\Settings\Console\PruneOrphansCommand; -use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; use Simtabi\Laranail\Settings\Listeners\SendSettingsAlert; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; -use Simtabi\Laranail\Settings\Services\Transfer\Importers; use Simtabi\Laranail\Settings\Stores\InstallationEvidence; use Simtabi\Laranail\Package\Tools\Commands\InstallCommand; -use Simtabi\Laranail\Settings\Actions\Transfer\ExportStore; -use Simtabi\Laranail\Settings\Actions\Transfer\ImportStore; use Simtabi\Laranail\Settings\Authorization\GateAuthorizer; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -use Simtabi\Laranail\Settings\Owners\MorphMapOwnerResolver; use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; -use Simtabi\Laranail\Settings\Services\Resolution\Resolver; use Simtabi\Laranail\Settings\Authorization\ChainAuthorizer; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; -use Simtabi\Laranail\Settings\Database\SchemaReadinessProbe; -use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; -use Simtabi\Laranail\Settings\Support\LaravelValueValidator; -use Simtabi\Laranail\Settings\Actions\Approvals\CancelChange; -use Simtabi\Laranail\Settings\Actions\Approvals\PruneChanges; -use Simtabi\Laranail\Settings\Actions\Approvals\QueryChanges; -use Simtabi\Laranail\Settings\Actions\Approvals\RejectChange; use Simtabi\Laranail\Settings\Console\SyncDefinitionsCommand; use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; -use Simtabi\Laranail\Settings\Actions\Approvals\ApproveChange; -use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; -use Simtabi\Laranail\Settings\Actions\Categories\MoveCategory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; -use Simtabi\Laranail\Settings\Actions\Transfer\TransferActions; use Simtabi\Laranail\Settings\Http\Middleware\IdempotentWrites; -use Simtabi\Laranail\Settings\Services\Transfer\StoreSnapshots; -use Simtabi\Laranail\Settings\Actions\Approvals\ApprovalActions; -use Simtabi\Laranail\Settings\Actions\Categories\CreateCategory; -use Simtabi\Laranail\Settings\Actions\Categories\DeleteCategory; -use Simtabi\Laranail\Settings\Actions\Categories\RenameCategory; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Authentication\GuardActorResolver; -use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; -use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; use Simtabi\Laranail\Settings\Authentication\SanctumActorResolver; use Simtabi\Laranail\Settings\Authorization\PermissionsAuthorizer; use Simtabi\Laranail\Settings\Verification\ActorTimestampVerifier; -use Simtabi\Laranail\Settings\Actions\Configuration\SaveDefinition; +use Illuminate\Contracts\Notifications\Dispatcher as Notifications; use Simtabi\Laranail\Package\Tools\Providers\PackageServiceProvider; use Simtabi\Laranail\Settings\Services\Tenancy\TenantDiscriminators; -use Simtabi\Laranail\Settings\Actions\Configuration\DeleteDefinition; use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; use Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; use Simtabi\Laranail\Settings\Verification\PasswordConfirmationVerifier; -use Simtabi\Laranail\Settings\Actions\Configuration\ConfigurationActions; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; -use Simtabi\Laranail\Settings\Actions\Configuration\SaveConfigurationEntry; -use Illuminate\Contracts\Notifications\Dispatcher as NotificationDispatcher; use Simtabi\Laranail\Package\Tools\Support\Definitions\AutoSeederDefinition; use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; -use Simtabi\Laranail\Settings\Actions\Configuration\DeleteConfigurationEntry; -use Simtabi\Laranail\Settings\Actions\Configuration\ListConfigurationEntries; /** * Registers laranail/settings with the host application. @@ -192,10 +124,13 @@ * touches the database or the filesystem at boot: stores, drivers and definitions are built on * first use, and the encrypter is resolved only when a value is encrypted or decrypted. * - * Everything derived from a request (the actor resolver, the runtime configuration, the access - * guard, the auditor and the log) is bound `scoped`, so Octane and queue workers start each - * request and job clean. Configuration naming an unknown driver, sink or level raises - * InvalidConfiguration with its config path on first use. + * Most classes are autowired: their lifetime is a `#[Scoped]` or `#[Singleton]` attribute on the + * class, and their configuration a `#[Config]` attribute on the parameter. What is bound here is + * what configuration chooses or validates (drivers, sinks, authorizers, verifiers, resolvers, + * cache stores), and the few services whose collaborators are closures on purpose. Everything + * derived from a request is scoped, so Octane and queue workers start each request and job clean. + * Configuration naming an unknown driver, sink or level raises InvalidConfiguration with its + * config path on first use. */ final class SettingsServiceProvider extends PackageServiceProvider { @@ -205,6 +140,11 @@ public function configurePackage(Package $package): void ->name('laranail/settings') ->setPublishTagId('settings') ->hasConfigFile('settings') + // `laranail/settings::settings.*` (resources/lang) and the one view, the alert mail + // (`laranail/settings::mail.alert`); both publishable. The REST API's routes are + // loaded in packageBooted(), behind the http.enabled switch. + ->hasTranslations() + ->hasViews() ->hasMigrations(['create_laranail_settings_tables']) // Runs with the host's `php artisan db:seed`; the seeder itself honours seed.enabled. // Foreign keys stay checked (a child category needs its parent) and events fire (the @@ -212,7 +152,33 @@ public function configurePackage(Package $package): void ->hasPackageSeeders(AutoSeederDefinition::make('laranail/settings:defaults') ->seeders([DefaultCategoriesSeeder::class]) ->options(['disable_foreign_key_checks' => false, 'fire_events' => true])) - ->hasCommands([PromoteCommand::class, PruneOrphansCommand::class, PruneAuditCommand::class, PruneHistoryCommand::class, HistoryCommand::class, MakeStoreCommand::class, DoctorCommand::class, SyncDefinitionsCommand::class, WarmCacheCommand::class, ClearCacheCommand::class, PruneChangesCommand::class, ExportCommand::class, ImportCommand::class, DiffCommand::class, ReencryptCommand::class, RescopeCommand::class, OpenApiCommand::class]) + // The REST API's limit: `http.rate_limit` requests a minute per user (or IP); 0 is none. + ->registerRateLimiter('laranail-settings', static function (Request $request): Limit { + $perMinute = config()->integer('laranail.settings.http.rate_limit', 60); + $user = $request->user()?->getAuthIdentifier(); + + return $perMinute > 0 + ? Limit::perMinute($perMinute)->by(is_scalar($user) ? 'user:' . $user : 'ip:' . $request->ip()) + : Limit::none(); + }) + ->hasCommands([ + PromoteCommand::class, + PruneOrphansCommand::class, + PruneAuditCommand::class, + PruneHistoryCommand::class, + PruneChangesCommand::class, + HistoryCommand::class, + MakeStoreCommand::class, + DoctorCommand::class, + SyncDefinitionsCommand::class, + WarmCacheCommand::class, + ClearCacheCommand::class, + ExportCommand::class, + ImportCommand::class, + DiffCommand::class, + ReencryptCommand::class, + RescopeCommand::class, + ]) ->hasInstallCommand(static function (InstallCommand $command): void { $command ->startWith(static function (InstallCommand $command): void { @@ -227,35 +193,49 @@ public function configurePackage(Package $package): void }); } + #[Override] + public function packageRegistered(): void + { + $this->app->scoped(Settings::class, SettingsManager::class); + + $this->registerTenancy(); + $this->registerStores(); + $this->registerDefinitions(); + $this->registerAccess(); + $this->registerHttp(); + $this->registerTyped(); + } + #[Override] public function packageBooted(): void { - // db-tools memoises readiness in a singleton: forget it once the schema may have changed - // and at the start of every queued job (and Octane request, when Octane is installed). $app = $this->app; - $flush = static function () use ($app): void { - $app->make(ReadinessProbe::class)->flush(); - }; $events = $app->make(Dispatcher::class); + $config = $app->make(Repository::class); - $events->listen(MigrationsEnded::class, $flush); - $events->listen(JobProcessing::class, $flush); - $events->listen('Laravel\\Octane\\Events\\RequestReceived', $flush); + // db-tools memoises readiness in a singleton: forget it once the schema may have changed, + // at the start of every queued job and Octane request, and on the tenant switches the + // tenancy packages announce (`readiness.flush_on`; db-tools has no hook of its own). + $flush = static function () use ($app): void { + $app->make(SchemaReadinessInterface::class)->flush(); + }; - // Tenant switches (db-tools has no hook of its own): the tenancy packages' events, by name. - foreach (self::strings($app, 'laranail.settings.readiness.flush_on') as $event) { + foreach ([MigrationsEnded::class, JobProcessing::class, 'Laravel\\Octane\\Events\\RequestReceived', ...self::strings($config, 'laranail.settings.readiness.flush_on')] as $event) { $events->listen($event, $flush); } - // Built-in listeners (`listeners.*`): registered by class, so nothing is built until an - // event fires. Reading configuration here touches neither the database nor the cache. - $config = $app->make(Repository::class); + // Each typed settings class `typed.classes` lists resolves loaded, through the request's handle. + foreach (self::strings($config, 'laranail.settings.typed.classes') as $class) { + if (is_subclass_of($class, TypedSettings::class)) { + $app->bind($class, static fn (Application $app): TypedSettings => $class::load($app->make(Settings::class))); + } + } - // The REST API (§16.10): nothing is registered unless it is switched on. if (filter_var($config->get('laranail.settings.http.enabled', false), FILTER_VALIDATE_BOOL)) { - $this->bootHttp($app, $config); + $this->bootHttp($config); } + // The built-in listeners, registered by class: nothing is built until an event fires. if ($config->get('laranail.settings.listeners.log', false) === true) { $events->listen(LogSettingsEvent::EVENTS, LogSettingsEvent::class); } @@ -265,269 +245,26 @@ public function packageBooted(): void } } - #[Override] - public function packageRegistered(): void + /** `cache.enabled`: on unless set to a false value. */ + private static function cacheEnabled(Application $app): bool { - $this->registerTenancy(); - - $this->app->singleton(CasterRegistry::class); - $this->app->singleton(ValueEncoder::class); - $this->app->singleton(RecordSerializer::class); - - $this->app->singleton(ValueValidator::class, static fn (Application $app): ValueValidator => new LaravelValueValidator($app->make(Factory::class))); - - $this->app->singleton(ValueEncrypter::class, static fn (Application $app): ValueEncrypter => new LaravelValueEncrypter( - static fn (): StringEncrypter => $app->make(StringEncrypter::class), - )); - - $this->app->singleton(DefinitionRegistry::class, static fn (Application $app): DefinitionRegistry => new DefinitionRegistry( - new StoreName(self::string($app, 'laranail.settings.default', 'settings')), - $app->make(CasterRegistry::class), - in_array('config', self::definitionSources($app), true) ? self::array($app, 'laranail.settings.definitions') : [], - )); - - $this->app->singleton(ReadinessProbe::class, static fn (Application $app): ReadinessProbe => new SchemaReadinessProbe( - $app->make(SchemaReadinessInterface::class), - )); - - $this->app->singleton(DriverFactory::class, static fn (Application $app): DriverFactory => new DriverFactory( - $app->make(Disks::class), - $app->make(Repository::class), - new ReadOnlyValues($app->make(ValueEncoder::class)), - $app->make(RecordSerializer::class), - $app->basePath(), - $app->make(ConnectionResolverInterface::class), - SchemaNames::fromConfig(self::array($app, 'laranail.settings.tables')), - static fn (): ReadinessProbe => $app->make(ReadinessProbe::class), - static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), - static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), - )); - - // The recorded schema shape (§4.0). Scoped: read once per request or job, never at boot. - $this->app->scoped(SchemaShapeRepository::class, static function (Application $app): SchemaShapeRepository { - $path = $app->make(Repository::class)->get('laranail.settings.schema.path'); - - return new SchemaShapeRepository( - $app->make(Filesystem::class), - is_string($path) && $path !== '' ? $path : $app->databasePath('settings-schema.php'), - static fn (): SchemaShape => SchemaShape::fromConfig( - self::array($app, 'laranail.settings'), - $app->make(Repository::class)->get('laranail.db-tools.id_type'), - ), - ); - }); - - // Evidence that the application is being installed: the operator's flag, or - // laranail/installer-headless (suggested, so class_exists-guarded) reporting an install - // in progress. Read on first use, never at boot. - $this->app->scoped(BootstrapEvidence::class, static function (Application $app): BootstrapEvidence { - $installer = 'Simtabi\\Laranail\\Installer\\Headless\\Support\\InstallationState'; - - return new InstallationEvidence( - $app->make(Repository::class)->get('laranail.settings.bootstrap', false) === true, - class_exists($installer) ? static function () use ($app, $installer): bool { - $state = $app->make($installer); - - return is_object($state) && method_exists($state, 'isInstalling') && $state->isInstalling() === true; - } : null, - ); - }); - - // Scoped: rebuilt per request and per queued job under Octane and Horizon, so no - // per-request state can survive into the next one. - $this->app->scoped(RuntimeConfiguration::class, static fn (Application $app): RuntimeConfiguration => new RuntimeConfiguration( - $app->make(DriverFactory::class), - self::string($app, 'laranail.settings.default', 'settings'), - self::array($app, 'laranail.settings.stores'), - self::array($app, 'laranail.settings.layers'), - $app->make(CasterRegistry::class), - static function (string $change) use ($app): void { - $app->make(OperationalLogger::class)->info('laranail/settings runtime configuration: ' . $change); - $app->make(Auditor::class)->record(AuditAction::Configure, AuditOutcome::Allowed, null, null, meta: ['change' => $change]); - }, - )); - - $this->app->scoped(StoreRegistry::class, static fn (Application $app): StoreRegistry => new StoreRegistry( - $app->make(DriverFactory::class), - self::string($app, 'laranail.settings.default', 'settings'), - self::array($app, 'laranail.settings.stores'), - self::array($app, 'laranail.settings.layers'), - runtime: $app->make(RuntimeConfiguration::class), - evidence: $app->make(BootstrapEvidence::class), - onLayerSkipped: static function (string $store, string $layer, string $reason) use ($app): void { - $app->make(Dispatcher::class)->dispatch(new LayerSkipped($store, $layer, $reason)); - }, - cache: self::cacheEnabled($app) ? $app->make(SettingsCache::class) : null, - persisted: $app->make(PersistedConfiguration::class), - sources: self::configurationSources($app), - )); - - $this->app->singleton(ValuePipeline::class); - - $this->app->scoped(Resolver::class, static fn (Application $app): Resolver => new Resolver( - $app->make(StoreRegistry::class), - $app->make(ValuePipeline::class), - self::string($app, 'app.fallback_locale', 'en'), - tenant: $app->make(TenantDiscriminator::class), - )); - - $this->app->singleton(SettingWriter::class, static fn (Application $app): SettingWriter => new SettingWriter( - $app->make(ValuePipeline::class), - $app->make(Dispatcher::class), - self::clock(), - $app->make(Repository::class)->get('laranail.settings.writes.retry_on_conflict', true) !== false, - static function (Store $store, Key $key, Scope $scope) use ($app): void { - $app->make(OperationalLogger::class)->info(sprintf('laranail/settings retried a write of [%s] in store [%s] for scope [%s] after a concurrent change.', $key, $store->name, $scope), [ - 'store' => $store->name->value, - 'key' => $key->value, - 'scope' => $scope->value, - ]); - }, - )); - - $this->registerAccess(); - $this->registerCache(); - $this->registerListeners(); - - $this->registerPersistedConfiguration(); - $this->registerApprovals(); - $this->registerTransfer(); - $this->registerHttp(); - $this->registerTyped(); - - $this->app->scoped(SettingActions::class, static fn (Application $app): SettingActions => SettingActions::using( - $app->make(SettingWriter::class), - $app->make(AccessGuard::class), - $app->make(ApprovalActions::class)->propose, - )); - - $this->app->scoped(StoreActions::class, static function (Application $app): StoreActions { - $access = $app->make(AccessGuard::class); - $events = $app->make(Dispatcher::class); - $flush = new FlushScope($access, $events); - - return new StoreActions( - CategoryActions::using($access, $events), - new PromoteStore( - $app->make(ValuePipeline::class), - $access, - $events, - $app->make(Caches::class), - self::definitionLookup($app), - ), - $flush, - new WarmCache($access), - new ClearCache( - $access, - self::cacheEnabled($app) ? $app->make(SettingsCache::class) : null, - new StoreName(self::string($app, 'laranail.settings.default', 'settings')), - ), - ); - }); - - $this->app->scoped(WarmCache::class, static fn (Application $app): WarmCache => $app->make(StoreActions::class)->warmCache ?? new WarmCache($app->make(AccessGuard::class))); - $this->app->scoped(ClearCache::class, static fn (Application $app): ClearCache => $app->make(StoreActions::class)->clearCache ?? new ClearCache($app->make(AccessGuard::class), null)); - - $this->app->scoped(DatabaseDefinitions::class, static fn (Application $app): DatabaseDefinitions => new DatabaseDefinitions( - $app->make(CasterRegistry::class), - $app->make(ValueEncoder::class), - self::strings($app, 'laranail.settings.definitions.allowed_rules'), - in_array('database', self::definitionSources($app), true), - )); - - $this->app->scoped(SyncDefinitions::class, static fn (Application $app): SyncDefinitions => new SyncDefinitions( - $app->make(StoreRegistry::class), - $app->make(DefinitionRegistry::class), - $app->make(ValueEncoder::class), - $app->make(AccessGuard::class), - $app->make(Dispatcher::class), - )); - - $this->app->scoped(QueryAudit::class, static fn (Application $app): QueryAudit => new QueryAudit( - $app->make(StoreRegistry::class), - $app->make(AccessGuard::class), - )); - - $this->app->scoped(FindOrphans::class, static fn (Application $app): FindOrphans => new FindOrphans( - $app->make(StoreRegistry::class), - static fn (string $alias): ?string => Relation::getMorphedModel($alias), - )); - - $this->app->scoped(PruneOrphans::class, static fn (Application $app): PruneOrphans => new PruneOrphans( - $app->make(StoreRegistry::class), - $app->make(StoreActions::class)->flush, - static fn (string $alias): ?string => Relation::getMorphedModel($alias), - $app->make(AccessGuard::class), - $app->make(Dispatcher::class), - )); - - $this->app->scoped(HistoryActions::class, static function (Application $app): HistoryActions { - $access = $app->make(AccessGuard::class); - $writer = $app->make(SettingWriter::class); - $pipeline = $app->make(ValuePipeline::class); - - return new HistoryActions( - new QueryHistory($app->make(StoreRegistry::class), $access), - new RollbackSetting($writer, new WriteGuard($access, $writer), $pipeline, $app->make(Dispatcher::class)), - new DiffHistory($access, $pipeline), - ); - }); - - $this->app->scoped(PruneHistory::class, static fn (Application $app): PruneHistory => new PruneHistory( - $app->make(StoreRegistry::class), - $app->make(AccessGuard::class), - $app->make(Dispatcher::class), - )); - - $this->app->scoped(PruneAudit::class, static fn (Application $app): PruneAudit => new PruneAudit( - $app->make(StoreRegistry::class), - $app->make(AccessGuard::class), - $app->make(Dispatcher::class), - )); - - $this->app->bind(MakeStore::class, static fn (Application $app): MakeStore => new MakeStore( - $app->make(Filesystem::class), - dirname(__DIR__, 2) . '/database/migrations/' . MakeStore::MIGRATION . '.php', - $app->databasePath('migrations'), - $app->make(SchemaShapeRepository::class), - )); - - $this->app->scoped(Settings::class, static fn (Application $app): Settings => new SettingsManager( - $app->make(StoreRegistry::class), - $app->make(DefinitionRegistry::class), - $app->make(Resolver::class), - $app->make(SettingWriter::class), - actions: $app->make(SettingActions::class), - access: $app->make(AccessGuard::class), - runtime: $app->make(RuntimeConfiguration::class), - storeActions: $app->make(StoreActions::class), - auditQuery: $app->make(QueryAudit::class), - databaseDefinitions: $app->make(DatabaseDefinitions::class), - historyActions: $app->make(HistoryActions::class), - approvalActions: $app->make(ApprovalActions::class), - transferActions: $app->make(TransferActions::class), - configurationActions: $app->make(ConfigurationActions::class), - )); - - $this->app->bind(DiagnoseSettings::class, static fn (Application $app): DiagnoseSettings => new DiagnoseSettings( - $app->make(StoreRegistry::class), - $app->make(SchemaShapeRepository::class), - $app->make(ValueEncrypter::class), - static fn (): array => $app->make(PersistedConfiguration::class)->problems(), - )); + return filter_var($app->make(Repository::class)->get('laranail.settings.cache.enabled', true), FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) ?? true; } - /** - * The definition a key resolves to, as a handle resolves it: runtime definitions first, then - * code and config, then the definitions table (D-6). - * - * @return Closure(Store, Key): ?Definition - */ - private static function definitionLookup(Application $app): Closure + /** A Laravel cache repository by store name (null: the default store), or InvalidConfiguration naming `$path`. */ + private static function cacheStore(Application $app, mixed $name, string $path): CacheRepository { - return static fn (Store $store, Key $key): ?Definition => $app->make(RuntimeConfiguration::class)->findDefinition($store->name, $key) - ?? $app->make(DefinitionRegistry::class)->find($store->name, $key) - ?? $app->make(DatabaseDefinitions::class)->find($store, $key); + if ($name !== null && (! is_string($name) || $name === '')) { + throw new InvalidConfiguration($path . ': a cache store name, or null for the default store.'); + } + + try { + $cache = $app->make(Caches::class)->store($name); + } catch (InvalidArgumentException $exception) { + throw new InvalidConfiguration(sprintf('%s: %s', $path, $exception->getMessage()), $exception->getCode(), previous: $exception); + } + + return $cache instanceof CacheRepository ? $cache : throw new InvalidConfiguration(sprintf('%s: [%s] is not a Laravel cache repository.', $path, get_debug_type($cache))); } /** @@ -536,9 +273,9 @@ private static function definitionLookup(Application $app): Closure * * @return list */ - private static function configurationSources(Application $app): array + private static function configurationSources(Repository $config): array { - $sources = $app->make(Repository::class)->get('laranail.settings.configuration.sources', ['config', 'database', 'runtime']); + $sources = $config->get('laranail.settings.configuration.sources', ['config', 'database', 'runtime']); $names = is_array($sources) ? array_values(array_filter($sources, is_string(...))) : null; if ($names === null || count($names) !== count($sources) || array_diff($names, ['config', 'database', 'runtime']) !== [] || count(array_unique($names)) !== count($names)) { @@ -548,38 +285,15 @@ private static function configurationSources(Application $app): array return $names; } - /** `cache.enabled`: on unless set to a false value. */ - private static function cacheEnabled(Application $app): bool - { - return filter_var($app->make(Repository::class)->get('laranail.settings.cache.enabled', true), FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) ?? true; - } - - /** - * Install refuses to publish migrations over a table of the same name that is not this - * package's (D-4): rename the package's tables with `tables.prefix` or `stores..table`. - */ - private static function refuseForeignTables(InstallCommand $command): void - { - $foreign = $command->getLaravel()->make(FindForeignTables::class)->handle(); - - if ($foreign !== []) { - throw new InvalidConfiguration(sprintf( - 'These tables already exist and are not laranail/settings tables: %s. Set laranail.settings.tables.prefix (or stores..table, tables.categories, tables.audit) and install again.', - implode(', ', $foreign), - )); - } - } - /** * `definitions.sources` (D-6): which of `code`, `config` and `database` are read. Code - * definitions are registered by packages and the application in code and are always read. + * definitions are registered in code and are always read. * * @return list */ - private static function definitionSources(Application $app): array + private static function definitionSources(Repository $config): array { - $sources = $app->make(Repository::class)->get('laranail.settings.definitions.sources', ['code', 'config', 'database']); - + $sources = $config->get('laranail.settings.definitions.sources', ['code', 'config', 'database']); $names = is_array($sources) ? array_values(array_filter($sources, is_string(...))) : null; if ($names === null || count($names) !== count($sources) || array_diff($names, ['code', 'config', 'database']) !== []) { @@ -589,59 +303,36 @@ private static function definitionSources(Application $app): array return $names; } - /** - * Record the schema the published migrations will produce (§4.0), so the runtime reads that - * record rather than live configuration. An existing record is kept and only new stores are - * added to it. - */ - private static function recordSchema(InstallCommand $command): void - { - $shapes = $command->getLaravel()->make(SchemaShapeRepository::class); - $shapes->record(); - $command->info('Recorded the settings schema in ' . $shapes->path()); - } - - /** Copy code and config definitions into the definitions table, when it exists already. */ - private static function syncDefinitions(InstallCommand $command): void + /** @return list the strings of the array at `$key` (other entries dropped) */ + private static function strings(Repository $config, string $key): array { - try { - $report = $command->getLaravel()->make(SyncDefinitions::class)->handle(Actor::system('laranail::settings.install')); - } catch (SettingsException) { - $command->comment('Definitions were not synced (run the migrations, then laranail::settings.sync-definitions).'); - - return; - } - - if ($report['synced'] > 0) { - $command->info(sprintf('Synced %d definition(s) into the definitions table.', $report['synced'])); - } + return array_values(array_filter($config->array($key, []), is_string(...))); } private static function authorizer(Application $app, mixed $driver, string $path): Authorizer { return match ($driver) { 'gate' => new GateAuthorizer($app->make(Gate::class)), - 'permissions' => new PermissionsAuthorizer(self::array($app, 'laranail.settings.authorization.permissions')), + 'permissions' => new PermissionsAuthorizer($app->make(Repository::class)->array('laranail.settings.authorization.permissions', [])), default => self::instance($app, $driver, Authorizer::class, $path), }; } private static function auditSink(Application $app, mixed $sink, string $path): AuditSink { + // The database sink finds its store per entry, so it reaches the registry through a + // closure: the registry's own collaborators audit through this sink. + $database = static fn (): DatabaseAuditSink => new DatabaseAuditSink(static fn (): StoreRegistry => $app->make(StoreRegistry::class)); + return match ($sink) { - 'auto' => new AutoAuditSink(self::databaseSink($app), new LogAuditSink($app->make(OperationalLogger::class))), - 'database' => self::databaseSink($app), + 'auto' => new AutoAuditSink($database(), new LogAuditSink($app->make(OperationalLogger::class))), + 'database' => $database(), 'log' => new LogAuditSink($app->make(OperationalLogger::class)), 'null' => new NullAuditSink, default => self::instance($app, $sink, AuditSink::class, $path), }; } - private static function databaseSink(Application $app): DatabaseAuditSink - { - return new DatabaseAuditSink(static fn (): StoreRegistry => $app->make(StoreRegistry::class)); - } - /** * A custom implementation named by class in config: it must exist and implement the contract. * @@ -662,473 +353,267 @@ private static function instance(Application $app, mixed $class, string $contrac return $instance instanceof $contract ? $instance : throw new InvalidConfiguration(sprintf('%s: [%s] did not build a %s.', $path, $class, $contract)); } - /** @return Closure(): CarbonImmutable */ - private static function clock(): Closure - { - return static fn (): CarbonImmutable => now()->toImmutable(); - } - - private static function integer(Application $app, string $key, int $default): int - { - return self::config($app)->integer($key, $default); - } - - /** @return list */ - private static function strings(Application $app, string $key): array - { - return self::config($app)->strings($key); - } - - private static function string(Application $app, string $key, string $default): string - { - return self::config($app)->string($key, $default); - } - - /** @return array */ - private static function array(Application $app, string $key): array + /** + * Install refuses to publish migrations over a table of the same name that is not this + * package's (D-4): rename the package's tables with `tables.prefix` or `stores..table`. + */ + private static function refuseForeignTables(InstallCommand $command): void { - return self::config($app)->array($key); - } + $foreign = $command->getLaravel()->make(FindForeignTables::class)->handle(); - private static function config(Application $app): ConfigValues - { - return new ConfigValues($app->make(Repository::class)); + if ($foreign !== []) { + throw new InvalidConfiguration(sprintf( + 'These tables already exist and are not laranail/settings tables: %s. Set laranail.settings.tables.prefix (or stores..table, tables.categories, tables.audit) and install again.', + implode(', ', $foreign), + )); + } } /** - * Persisted configuration (§16.11): read lazily from the settings_stores table on the default - * store's database connection (as the configuration file names it), validated by building the - * stores it would produce, and bound `scoped`. + * Record the schema the published migrations will produce (§4.0), so the runtime reads that + * record rather than live configuration. An existing record is kept and only new stores are + * added to it. */ - private function registerPersistedConfiguration(): void + private static function recordSchema(InstallCommand $command): void { - $this->app->scoped(PersistedConfiguration::class, static function (Application $app): PersistedConfiguration { - $stores = self::array($app, 'laranail.settings.stores'); - $layers = self::array($app, 'laranail.settings.layers'); - $default = self::string($app, 'laranail.settings.default', 'settings'); - $persisted = $app->make(Repository::class)->get('laranail.settings.configuration.persisted', false); - - return new PersistedConfiguration( - filter_var($persisted, FILTER_VALIDATE_BOOL), - static function () use ($app, $stores, $layers, $default): Connection { - $connection = null; - - foreach ((array) (is_array($stores[$default] ?? null) ? ($stores[$default]['layers'] ?? []) : []) as $layer) { - $config = is_string($layer) ? ($layers[$layer] ?? null) : null; - - if (is_array($config) && ($config['driver'] ?? null) === 'database') { - $connection = is_string($config['connection'] ?? null) ? $config['connection'] : null; - - break; - } - } - - $resolved = $app->make(ConnectionResolverInterface::class)->connection($connection); - - return $resolved instanceof Connection ? $resolved : throw new InvalidConfiguration('laranail.settings.configuration: the default store\'s database connection is not a database connection.'); - }, - static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), - static function (array $persistedStores, array $persistedLayers) use ($app, $stores, $layers, $default): void { - new StoreRegistry($app->make(DriverFactory::class), $default, array_replace($stores, $persistedStores), array_replace($layers, $persistedLayers))->validate(); - }, - $stores, - static function (string $problem) use ($app): void { - $app->make(OperationalLogger::class)->warning($problem); - }, - ); - }); - - $this->app->scoped(ConfigurationActions::class, static function (Application $app): ConfigurationActions { - $access = $app->make(AccessGuard::class); - $stores = $app->make(StoreRegistry::class); - $persisted = $app->make(PersistedConfiguration::class); - - return new ConfigurationActions( - new SaveConfigurationEntry($stores, $persisted, $access), - new DeleteConfigurationEntry($stores, $persisted, $access), - new ListConfigurationEntries($stores, $persisted, $access), - new SaveDefinition($app->make(DefinitionRegistry::class), $app->make(DatabaseDefinitions::class), $app->make(ValueEncoder::class), $access), - new DeleteDefinition($app->make(DatabaseDefinitions::class), $app->make(ValueEncoder::class), $access), - ); - }); + $shapes = $command->getLaravel()->make(SchemaShapeRepository::class); + $shapes->record(); + $command->info('Recorded the settings schema in ' . $shapes->path()); } - /** Export, import and store diff (G-42), and the importers (G-43). */ - private function registerTransfer(): void + /** Copy code and config definitions into the definitions table, when it exists already. */ + private static function syncDefinitions(InstallCommand $command): void { - $this->app->singleton(StoreSnapshots::class, static fn (Application $app): StoreSnapshots => new StoreSnapshots( - $app->make(ValueEncrypter::class), - $app->make(ValueEncoder::class), - )); - - $this->app->scoped(TransferActions::class, static function (Application $app): TransferActions { - $access = $app->make(AccessGuard::class); - $snapshots = $app->make(StoreSnapshots::class); - $actions = $app->make(SettingActions::class); - - return new TransferActions( - new ExportStore($access, $snapshots), - new ImportStore( - $access, - $snapshots, - $app->make(ValuePipeline::class), - $app->make(ValueEncoder::class), - $actions->set, - $actions->lock, - $app->make(StoreActions::class)->categories->create, - self::definitionLookup($app), - ), - new DiffStore($access, $snapshots), - ); - }); + try { + $report = $command->getLaravel()->make(SyncDefinitions::class)->handle(Actor::system('laranail::settings.install')); + } catch (SettingsException) { + $command->comment('Definitions were not synced (run the migrations, then laranail::settings.sync-definitions).'); - $this->app->singleton(Importers::class, static fn (Application $app): Importers => new Importers( - self::array($app, 'laranail.settings.importers'), - static function (string $class) use ($app): object { - $importer = $app->make($class); + return; + } - return is_object($importer) ? $importer : throw new InvalidConfiguration(sprintf('laranail.settings.importers: [%s] did not build an object.', $class)); - }, - )); + if ($report['synced'] > 0) { + $command->info(sprintf('Synced %d definition(s) into the definitions table.', $report['synced'])); + } } /** - * The REST API: its rate limiter, its routes under `http.prefix`/v1 and problem details for - * the errors its routes raise. Reads configuration only; touches neither database nor cache. + * The REST API (§16.10): routes/api.php under `http.prefix`/v1 (an empty prefix mounts it at + * /v1), and problem details for the errors its routes raise. Reads configuration only. */ - private function bootHttp(Application $app, Repository $config): void + private function bootHttp(Repository $config): void { - $perMinute = self::integer($app, 'laranail.settings.http.rate_limit', 60); - - RateLimiter::for('laranail-settings', static function (Request $request) use ($perMinute): Limit { - $user = $request->user()?->getAuthIdentifier(); - - return $perMinute > 0 - ? Limit::perMinute($perMinute)->by(is_scalar($user) ? 'user:' . $user : 'ip:' . $request->ip()) - : Limit::none(); - }); - $middleware = $config->get('laranail.settings.http.middleware'); $middleware = is_array($middleware) ? array_values(array_filter($middleware, is_string(...))) : ['api', class_exists('Laravel\\Sanctum\\Sanctum') ? 'auth:sanctum' : 'auth']; + $prefix = trim($config->string('laranail.settings.http.prefix', 'api/settings'), '/'); + + if (! $this->app instanceof CachesRoutes || ! $this->app->routesAreCached()) { + Route::prefix(ltrim($prefix . '/v1', '/')) + ->name('laranail-settings.api.') + ->middleware([...$middleware, 'throttle:laranail-settings']) + ->where(['store' => '[a-z][a-z0-9_]*', 'key' => '[A-Za-z0-9_.]+', 'alias' => '[a-z][a-z0-9_]*', 'kind' => 'stores|layers']) + ->group($this->package->basePath('/routes/api.php')); + } - ApiRoutes::register( - $app->make(Router::class), - self::string($app, 'laranail.settings.http.prefix', 'api/settings'), - $middleware, - self::array($app, 'laranail.settings.http.routes'), - ); - - $handler = $app->make(ExceptionHandler::class); + $handler = $this->app->make(ExceptionHandler::class); + $app = $this->app; if (method_exists($handler, 'renderable')) { - $handler->renderable(static fn (Throwable $exception, Request $request): ?JsonResponse => Problems::render($exception, $request)); + $handler->renderable(static fn (Throwable $exception, Request $request): mixed => $app->make(Problems::class)->render($exception, $request)); } } /** - * Typed settings (Phase 5): a typed settings class resolved from the container is loaded - * through the request's settings handle; classes listed in `typed.classes` register their - * definitions when the definition registry is first built; settings migrations get their - * migrator. Nothing is read at boot. + * Tenancy (Amendment B): who the current tenant is, and the context the Eloquent models read + * it from. `tenancy.discriminator`: `auto`, `null`, `stancl`, `spatie`, or a class + * implementing TenantDiscriminator. */ - private function registerTyped(): void + private function registerTenancy(): void { - $this->app->scoped(MigrateSettings::class, static fn (Application $app): MigrateSettings => new MigrateSettings( - $app->make(StoreRegistry::class), - $app->make(SettingWriter::class), - $app->make(ValuePipeline::class), - $app->make(AccessGuard::class), - self::definitionLookup($app), - )); - - $app = $this->app; - SettingsMigration::resolveMigratorUsing(static fn (): SettingsMigrator => new SettingsMigrator( - $app->make(MigrateSettings::class), - new StoreName(self::string($app, 'laranail.settings.default', 'settings')), - Actor::system('settings migration'), - )); - - $this->app->afterResolving(DefinitionRegistry::class, static function (DefinitionRegistry $registry) use ($app): void { - foreach (self::strings($app, 'laranail.settings.typed.classes') as $class) { - if (! is_subclass_of($class, TypedSettings::class)) { - throw new InvalidConfiguration(sprintf('laranail.settings.typed.classes: [%s] is not a typed settings class.', $class)); - } + $this->app->scoped(TenantDiscriminator::class, static function (Application $app): TenantDiscriminator { + $config = $app->make(Repository::class); + $binding = $config->get('multitenancy.current_tenant_container_key', 'currentTenant'); - $class::register($registry); - } + return new TenantDiscriminators($app, is_string($binding) ? $binding : 'currentTenant') + ->make($config->get('laranail.settings.tenancy.discriminator', 'auto')); }); - $this->app->beforeResolving(static function (mixed $abstract, array $parameters, Application $app): void { - if (is_string($abstract) && is_subclass_of($abstract, TypedSettings::class) && ! $app->bound($abstract)) { - $app->bind($abstract, static fn (Application $app): TypedSettings => $abstract::load($app->make(Settings::class))); - } - }); + $app = $this->app; + ModelContext::use( + static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), + static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), + static fn (): string => $app->make(Repository::class)->string('laranail.settings.default', 'settings'), + ); } - /** What the REST API's controllers are built from (bound always; cheap, and used only by routes). */ - private function registerHttp(): void + /** Drivers, the recorded schema, the stores, the runtime configuration and the cache. */ + private function registerStores(): void { - $this->app->scoped(SettingTargets::class, static fn (Application $app): SettingTargets => new SettingTargets( - $app->make(StoreRegistry::class), - self::definitionLookup($app), + // A singleton, so a driver registered with extend() lasts; the scoped services it hands + // to database drivers are closures, resolved for the request that uses them. + $this->app->singleton(DriverFactory::class, static fn (Application $app): DriverFactory => new DriverFactory( + $app->make(Disks::class), + $app->make(Repository::class), + new ReadOnlyValues($app->make(ValueEncoder::class)), + $app->make(RecordSerializer::class), + $app->basePath(), + $app->make(ConnectionResolverInterface::class), + SchemaNames::fromConfig($app->make(Repository::class)->array('laranail.settings.tables', [])), + static fn (): SchemaReadinessInterface => $app->make(SchemaReadinessInterface::class), + static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), + static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), )); - $this->app->scoped(OwnerResolver::class, static function (Application $app): OwnerResolver { - $owners = self::array($app, 'laranail.settings.http.owners'); - - return new MorphMapOwnerResolver(static fn (string $alias): ?string => is_string($owners[$alias] ?? null) ? $owners[$alias] : Relation::getMorphedModel($alias)); - }); - - $this->app->bind(IdempotentWrites::class, static function (Application $app): IdempotentWrites { - $store = $app->make(Repository::class)->get('laranail.settings.http.idempotency.cache'); - $cache = $app->make(Caches::class)->store(is_string($store) && $store !== '' ? $store : null); + $this->app->scoped(SchemaShapeRepository::class, static function (Application $app): SchemaShapeRepository { + $path = $app->make(Repository::class)->get('laranail.settings.schema.path'); - return new IdempotentWrites( - $cache instanceof CacheRepository ? $cache : throw new InvalidConfiguration('laranail.settings.http.idempotency.cache: not a cache repository.'), - self::integer($app, 'laranail.settings.http.idempotency.ttl', 86400), - self::string($app, 'laranail.settings.cache.prefix', 'laranail-settings'), - ); + return new SchemaShapeRepository($app->make(Filesystem::class), is_string($path) && $path !== '' ? $path : $app->databasePath('settings-schema.php'), $app->make(Repository::class)); }); - // Each action a controller takes is the instance the PHP API uses (§16.2). - $this->app->scoped(SetSetting::class, static fn (Application $app): SetSetting => $app->make(SettingActions::class)->set); - $this->app->scoped(ForgetSetting::class, static fn (Application $app): ForgetSetting => $app->make(SettingActions::class)->forget); - $this->app->scoped(LockSetting::class, static fn (Application $app): LockSetting => $app->make(SettingActions::class)->lock); - $this->app->scoped(UnlockSetting::class, static fn (Application $app): UnlockSetting => $app->make(SettingActions::class)->unlock); - $this->app->scoped(RollbackSetting::class, static fn (Application $app): RollbackSetting => $app->make(HistoryActions::class)->rollback); - $this->app->scoped(ProposeChange::class, static fn (Application $app): ProposeChange => $app->make(ApprovalActions::class)->propose); - $this->app->scoped(ApproveChange::class, static fn (Application $app): ApproveChange => $app->make(ApprovalActions::class)->approve); - $this->app->scoped(RejectChange::class, static fn (Application $app): RejectChange => $app->make(ApprovalActions::class)->reject); - $this->app->scoped(CancelChange::class, static fn (Application $app): CancelChange => $app->make(ApprovalActions::class)->cancel); - $this->app->scoped(QueryChanges::class, static fn (Application $app): QueryChanges => $app->make(ApprovalActions::class)->query); - $this->app->scoped(CreateCategory::class, static fn (Application $app): CreateCategory => $app->make(StoreActions::class)->categories->create); - $this->app->scoped(RenameCategory::class, static fn (Application $app): RenameCategory => $app->make(StoreActions::class)->categories->rename); - $this->app->scoped(MoveCategory::class, static fn (Application $app): MoveCategory => $app->make(StoreActions::class)->categories->move); - $this->app->scoped(DeleteCategory::class, static fn (Application $app): DeleteCategory => $app->make(StoreActions::class)->categories->delete); - $this->app->scoped(SaveConfigurationEntry::class, static fn (Application $app): SaveConfigurationEntry => $app->make(ConfigurationActions::class)->save); - $this->app->scoped(DeleteConfigurationEntry::class, static fn (Application $app): DeleteConfigurationEntry => $app->make(ConfigurationActions::class)->delete); - $this->app->scoped(ListConfigurationEntries::class, static fn (Application $app): ListConfigurationEntries => $app->make(ConfigurationActions::class)->list); - $this->app->scoped(SaveDefinition::class, static fn (Application $app): SaveDefinition => $app->make(ConfigurationActions::class)->saveDefinition); - $this->app->scoped(DeleteDefinition::class, static fn (Application $app): DeleteDefinition => $app->make(ConfigurationActions::class)->deleteDefinition); - $this->app->scoped(ExportStore::class, static fn (Application $app): ExportStore => $app->make(TransferActions::class)->export); - $this->app->scoped(ImportStore::class, static fn (Application $app): ImportStore => $app->make(TransferActions::class)->import); - $this->app->scoped(DiffStore::class, static fn (Application $app): DiffStore => $app->make(TransferActions::class)->diff); - } - - /** Four-eyes approvals (§16.7): the policy from `approvals.*`, and the actions over it. */ - private function registerApprovals(): void - { - $this->app->scoped(ApprovalPolicy::class, static function (Application $app): ApprovalPolicy { - $config = $app->make(Repository::class); - $days = static function (string $key, ?int $default) use ($config): ?int { - $value = $config->get('laranail.settings.approvals.' . $key, $default); - - return $value === null ? null : (is_numeric($value) ? (int) $value : throw new InvalidConfiguration(sprintf('laranail.settings.approvals.%s: a number of days, or null.', $key))); - }; + // The operator's flag, or laranail/installer-headless (suggested) reporting an install. + $this->app->scoped(InstallationEvidence::class, static function (Application $app): InstallationEvidence { + $installer = 'Simtabi\\Laranail\\Installer\\Headless\\Support\\InstallationState'; - return new ApprovalPolicy( - self::integer($app, 'laranail.settings.approvals.min_approvals', 1), - $config->get('laranail.settings.approvals.allow_self', false) === true, - $days('expire_after', 7), - $days('keep_days', 90), - ); - }); + return new InstallationEvidence( + $app->make(Repository::class)->get('laranail.settings.bootstrap', false) === true, + class_exists($installer) ? static function () use ($app, $installer): bool { + $state = $app->make($installer); - $this->app->scoped(ApprovalActions::class, static function (Application $app): ApprovalActions { - $access = $app->make(AccessGuard::class); - $events = $app->make(Dispatcher::class); - $policy = $app->make(ApprovalPolicy::class); - $definitions = self::definitionLookup($app); - - return new ApprovalActions( - new ProposeChange($access, $app->make(ValuePipeline::class), $events, $policy), - new ApproveChange($access, $app->make(SettingWriter::class), $app->make(ValuePipeline::class), $events, $definitions, $policy), - new RejectChange($access, $events, $definitions), - new CancelChange($access, $events), - new QueryChanges($app->make(StoreRegistry::class), $access), - new PruneChanges($app->make(StoreRegistry::class), $access, $policy), + return is_object($state) && method_exists($state, 'isInstalling') && $state->isInstalling() === true; + } : null, ); }); - } - - /** - * The settings cache (§7.5), built on first use, never at boot: the configured cache store - * (null for the application's default), keyed per tenant, reporting cache failures to the - * operational log. Scoped, so the bags it holds in memory last one request or job. - */ - private function registerCache(): void - { - $this->app->scoped(SettingsCache::class, static function (Application $app): SettingsCache { - $name = $app->make(Repository::class)->get('laranail.settings.cache.store'); - if ($name !== null && (! is_string($name) || $name === '')) { - throw new InvalidConfiguration('laranail.settings.cache.store: a cache store name, or null for the default store.'); - } + // Its change log is a closure: the logger and the auditor read the runtime configuration. + $this->app->scoped(RuntimeConfiguration::class, static fn (Application $app): RuntimeConfiguration => new RuntimeConfiguration( + $app->make(DriverFactory::class), + $app->make(Repository::class)->string('laranail.settings.default', 'settings'), + $app->make(Repository::class)->array('laranail.settings.stores', []), + $app->make(Repository::class)->array('laranail.settings.layers', []), + $app->make(CasterRegistry::class), + static function (string $change) use ($app): void { + $app->make(OperationalLogger::class)->info('laranail/settings runtime configuration: ' . $change); + $app->make(Auditor::class)->record(AuditAction::Configure, AuditOutcome::Allowed, null, null, meta: ['change' => $change]); + }, + )); - try { - $cache = $app->make(Caches::class)->store($name); - } catch (InvalidArgumentException $exception) { - throw new InvalidConfiguration(sprintf('laranail.settings.cache.store: %s', $exception->getMessage()), $exception->getCode(), previous: $exception); - } + $this->app->scoped(StoreRegistry::class, static fn (Application $app): StoreRegistry => new StoreRegistry( + $app->make(DriverFactory::class), + $app->make(Repository::class)->string('laranail.settings.default', 'settings'), + $app->make(Repository::class)->array('laranail.settings.stores', []), + $app->make(Repository::class)->array('laranail.settings.layers', []), + runtime: $app->make(RuntimeConfiguration::class), + evidence: $app->make(InstallationEvidence::class), + events: $app->make(Dispatcher::class), + cache: self::cacheEnabled($app) ? $app->make(SettingsCache::class) : null, + persisted: $app->make(PersistedConfiguration::class), + sources: self::configurationSources($app->make(Repository::class)), + )); - if (! $cache instanceof CacheRepository) { - throw new InvalidConfiguration(sprintf('laranail.settings.cache.store: [%s] is not a Laravel cache repository.', get_debug_type($cache))); - } + // The settings cache (§7.5): the configured cache store, null for the default one. + $this->app->scoped(SettingsCache::class, static function (Application $app): SettingsCache { + $config = $app->make(Repository::class); return new SettingsCache( - $cache, - self::string($app, 'laranail.settings.cache.prefix', 'laranail-settings'), - self::integer($app, 'laranail.settings.cache.ttl', 3600), - self::integer($app, 'laranail.settings.cache.stale', 300), - static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), - static function (string $operation, Throwable $exception) use ($app): void { - $app->make(OperationalLogger::class)->warning(sprintf('laranail/settings: the settings cache failed (%s): %s. Reads fall back to the database; a failed invalidation leaves bags stale until they expire or clear-cache runs.', $operation, $exception->getMessage()), [ - 'operation' => $operation, - 'exception' => $exception::class, - ]); - }, + self::cacheStore($app, $config->get('laranail.settings.cache.store'), 'laranail.settings.cache.store'), + $config->string('laranail.settings.cache.prefix', 'laranail-settings'), + $config->integer('laranail.settings.cache.ttl', 3600), + $config->integer('laranail.settings.cache.stale', 300), + $app->make(TenantDiscriminator::class), + $app->make(OperationalLogger::class), ); }); - } - /** - * The built-in listeners, resolved when an event fires: the operational log, and alerts with - * their rules (validated then, with each rule's config path in the error), the throttle cache - * and the sensitive-key check that `sensitive_only` rules use. - */ - private function registerListeners(): void - { - $this->app->bind(LogSettingsEvent::class, static fn (Application $app): LogSettingsEvent => new LogSettingsEvent($app->make(OperationalLogger::class))); - - $this->app->bind(SendSettingsAlert::class, static function (Application $app): SendSettingsAlert { - $config = $app->make(Repository::class); - $cache = $config->get('laranail.settings.alerts.cache'); - $throttle = self::integer($app, 'laranail.settings.alerts.throttle', 300); - $repository = null; + $this->app->bind(ClearCache::class, static fn (Application $app): ClearCache => new ClearCache( + $app->make(AccessGuard::class), + self::cacheEnabled($app) ? $app->make(SettingsCache::class) : null, + new StoreName($app->make(Repository::class)->string('laranail.settings.default', 'settings')), + )); - if ($throttle > 0) { - $store = $app->make(Caches::class)->store(is_string($cache) && $cache !== '' ? $cache : null); - $repository = $store instanceof CacheRepository ? $store : null; - } + $this->app->bind(MakeStore::class, static fn (Application $app): MakeStore => new MakeStore( + $app->make(Filesystem::class), + dirname(__DIR__, 2) . '/database/migrations/' . MakeStore::MIGRATION . '.php', + $app->databasePath('migrations'), + $app->make(SchemaShapeRepository::class), + )); - return new SendSettingsAlert( - $app->make(NotificationDispatcher::class), - array_values(array_map( - static fn (mixed $rule, int|string $index): AlertRule => is_array($rule) - ? AlertRule::fromConfig($rule, $index) - : throw new InvalidConfiguration(sprintf('laranail.settings.alerts.rules.%s: each rule is an array.', $index)), - self::array($app, 'laranail.settings.alerts.rules'), - array_keys(self::array($app, 'laranail.settings.alerts.rules')), - )), - static function (?string $store, ?string $key) use ($app): bool { - if ($store === null || $key === null) { - return false; - } - - try { - $name = new StoreName($store); - $setting = new Key($key); - } catch (SettingsException) { - return false; - } - - return ($app->make(RuntimeConfiguration::class)->findDefinition($name, $setting) - ?? $app->make(DefinitionRegistry::class)->find($name, $setting))?->isSensitive() ?? false; - }, - self::clock(), - $app->make(OperationalLogger::class), - $repository, - $throttle, - self::string($app, 'laranail.settings.cache.prefix', 'laranail-settings'), - ); - }); + // Resolved only when a value is encrypted or decrypted, so an application without an + // APP_KEY yet still boots and reads its unencrypted settings. + $this->app->singleton(LaravelValueEncrypter::class, static fn (Application $app): LaravelValueEncrypter => new LaravelValueEncrypter( + static fn (): StringEncrypter => $app->make(StringEncrypter::class), + )); } - /** - * Tenancy (Amendment B): who the current tenant is, and the context the Eloquent models read - * it from. `tenancy.discriminator`: `auto` (stancl/tenancy, then spatie/laravel-multitenancy, - * when installed; otherwise none), `null`, `stancl`, `spatie`, or a class implementing - * TenantDiscriminator. Bound `scoped`: the tenant changes between requests and jobs. - */ - private function registerTenancy(): void + /** Code and config definitions, the definitions table (D-6) and the approval policy (§16.7). */ + private function registerDefinitions(): void { - $this->app->scoped(TenantDiscriminator::class, static function (Application $app): TenantDiscriminator { - $binding = $app->make(Repository::class)->get('multitenancy.current_tenant_container_key', 'currentTenant'); + $this->app->singleton(DefinitionRegistry::class, static fn (Application $app): DefinitionRegistry => new DefinitionRegistry( + new StoreName($app->make(Repository::class)->string('laranail.settings.default', 'settings')), + $app->make(CasterRegistry::class), + in_array('config', self::definitionSources($app->make(Repository::class)), true) ? $app->make(Repository::class)->array('laranail.settings.definitions', []) : [], + )); - return new TenantDiscriminators($app, is_string($binding) ? $binding : 'currentTenant') - ->make($app->make(Repository::class)->get('laranail.settings.tenancy.discriminator', 'auto')); - }); + $this->app->scoped(DatabaseDefinitions::class, static fn (Application $app): DatabaseDefinitions => new DatabaseDefinitions( + $app->make(CasterRegistry::class), + $app->make(ValueEncoder::class), + self::strings($app->make(Repository::class), 'laranail.settings.definitions.allowed_rules'), + in_array('database', self::definitionSources($app->make(Repository::class)), true), + )); - $app = $this->app; - ModelContext::use( - static fn (): SchemaShape => $app->make(SchemaShapeRepository::class)->current(), - static fn (): ?string => $app->make(TenantDiscriminator::class)->current(), - static fn (): string => self::string($app, 'laranail.settings.default', 'settings'), - ); + $this->app->scoped(ApprovalPolicy::class, static fn (Application $app): ApprovalPolicy => ApprovalPolicy::fromConfig($app->make(Repository::class)->array('laranail.settings.approvals', []))); } /** Actor resolution, authorization, verification, audit and the operational log. */ private function registerAccess(): void { $this->app->scoped(OperationalLogger::class, static function (Application $app): OperationalLogger { - $channel = $app->make(Repository::class)->get('laranail.settings.logging.channel'); + $config = $app->make(Repository::class); + $channel = $config->get('laranail.settings.logging.channel'); return new OperationalLogger( $channel === false ? new NullLogger : $app->make(LogManager::class)->channel(is_string($channel) ? $channel : null), - self::string($app, 'laranail.settings.logging.level', LogLevel::INFO), + $config->string('laranail.settings.logging.level', LogLevel::INFO), $app->make(RuntimeConfiguration::class), ); }); - $this->app->scoped(Auditor::class, static fn (Application $app): Auditor => new Auditor( - array_map( - static fn (mixed $sink, int|string $index): AuditSink => self::auditSink($app, $sink, 'laranail.settings.audit.sinks.' . $index), - self::array($app, 'laranail.settings.audit.sinks'), - array_keys(self::array($app, 'laranail.settings.audit.sinks')), - ), - self::clock(), - $app->make(RuntimeConfiguration::class), - )); + $this->app->scoped(Auditor::class, static function (Application $app): Auditor { + $sinks = $app->make(Repository::class)->array('laranail.settings.audit.sinks', []); + + return new Auditor( + array_values(array_map(static fn (mixed $sink, int|string $index): AuditSink => self::auditSink($app, $sink, 'laranail.settings.audit.sinks.' . $index), $sinks, array_keys($sinks))), + $app->make(Clock::class), + $app->make(RuntimeConfiguration::class), + ); + }); $this->app->scoped(Authorizer::class, static function (Application $app): Authorizer { $driver = $app->make(Repository::class)->get('laranail.settings.authorization.driver', 'gate'); - if (is_array($driver)) { - return new ChainAuthorizer(array_values(array_map( - static fn (mixed $name, int|string $index): Authorizer => self::authorizer($app, $name, 'laranail.settings.authorization.driver.' . $index), - $driver, - array_keys($driver), - ))); - } - - return self::authorizer($app, $driver, 'laranail.settings.authorization.driver'); + return is_array($driver) + ? new ChainAuthorizer(array_values(array_map(static fn (mixed $name, int|string $index): Authorizer => self::authorizer($app, $name, 'laranail.settings.authorization.driver.' . $index), $driver, array_keys($driver)))) + : self::authorizer($app, $driver, 'laranail.settings.authorization.driver'); }); - $this->app->scoped(Verifier::class, static function (Application $app): Verifier { - $driver = $app->make(Repository::class)->get('laranail.settings.verification.driver', 'password_confirmation'); - - return match ($driver) { - 'password_confirmation' => new PasswordConfirmationVerifier( - static fn (): ?Session => $app->bound('request') && $app->make('request') instanceof Request && $app->make('request')->hasSession() - ? $app->make('request')->session() - : null, - self::integer($app, 'auth.password_timeout', 10800), - self::clock(), - ), - 'actor' => new ActorTimestampVerifier(self::integer($app, 'laranail.settings.verification.ttl', 900), self::clock()), - 'none' => new NullVerifier, - default => self::instance($app, $driver, Verifier::class, 'laranail.settings.verification.driver'), - }; + $this->app->scoped(Verifier::class, static fn (Application $app): Verifier => match ($driver = $app->make(Repository::class)->get('laranail.settings.verification.driver', 'password_confirmation')) { + // The session is read per call: the request changes under this scoped verifier. + 'password_confirmation' => new PasswordConfirmationVerifier( + static fn () => $app->bound('request') && $app->make('request') instanceof Request && $app->make('request')->hasSession() ? $app->make('request')->session() : null, + $app->make(Repository::class)->integer('auth.password_timeout', 10800), + $app->make(Clock::class), + ), + 'actor' => $app->make(ActorTimestampVerifier::class), + 'none' => new NullVerifier, + default => self::instance($app, $driver, Verifier::class, 'laranail.settings.verification.driver'), }); $this->app->scoped(ActorResolver::class, static function (Application $app): ActorResolver { - $resolver = $app->make(Repository::class)->get('laranail.settings.authentication.resolver', 'guard'); - $guards = self::strings($app, 'laranail.settings.authentication.guards'); + $guards = self::strings($app->make(Repository::class), 'laranail.settings.authentication.guards'); $request = static fn (): ?Request => $app->bound('request') && $app->make('request') instanceof Request ? $app->make('request') : null; - return match ($resolver) { + return match ($resolver = $app->make(Repository::class)->get('laranail.settings.authentication.resolver', 'guard')) { 'guard' => new GuardActorResolver($app->make(AuthFactory::class), $guards, $request), 'sanctum' => new SanctumActorResolver($app->make(AuthFactory::class), $guards, $request), default => self::instance($app, $resolver, ActorResolver::class, 'laranail.settings.authentication.resolver'), @@ -1136,7 +621,8 @@ private function registerAccess(): void }); $this->app->scoped(AccessGuard::class, static function (Application $app): AccessGuard { - $undefined = $app->make(Repository::class)->get('laranail.settings.authorization.undefined', 'deny'); + $config = $app->make(Repository::class); + $undefined = $config->get('laranail.settings.authorization.undefined', 'deny'); if (! in_array($undefined, ['allow', 'deny'], true)) { throw new InvalidConfiguration('laranail.settings.authorization.undefined: use [allow] or [deny].'); @@ -1149,15 +635,74 @@ private function registerAccess(): void $app->make(Auditor::class), $app->make(OperationalLogger::class), array_map( - static fn (string $ability): Ability => Ability::tryFrom($ability) - ?? throw new InvalidConfiguration(sprintf('laranail.settings.verification.abilities: unknown ability [%s].', $ability)), - self::strings($app, 'laranail.settings.verification.abilities'), + static fn (string $ability): Ability => Ability::tryFrom($ability) ?? throw new InvalidConfiguration(sprintf('laranail.settings.verification.abilities: unknown ability [%s].', $ability)), + self::strings($config, 'laranail.settings.verification.abilities'), ), $undefined === 'allow', - $app->make(Repository::class)->get('laranail.settings.authorization.require_actor', false) === true, + $config->get('laranail.settings.authorization.require_actor', false) === true, $app->make(RuntimeConfiguration::class), $app->make(Dispatcher::class), ); }); } + + /** The REST API's idempotency cache, and the alert listener with its rules and throttle. */ + private function registerHttp(): void + { + $this->app->bind(IdempotentWrites::class, static fn (Application $app): IdempotentWrites => new IdempotentWrites( + self::cacheStore($app, $app->make(Repository::class)->get('laranail.settings.http.idempotency.cache'), 'laranail.settings.http.idempotency.cache'), + $app->make(Repository::class)->integer('laranail.settings.http.idempotency.ttl', 86400), + $app->make(Repository::class)->string('laranail.settings.cache.prefix', 'laranail-settings'), + )); + + $this->app->bind(SendSettingsAlert::class, static function (Application $app): SendSettingsAlert { + $config = $app->make(Repository::class); + $throttle = $config->integer('laranail.settings.alerts.throttle', 300); + $rules = $config->array('laranail.settings.alerts.rules', []); + $cache = $config->get('laranail.settings.alerts.cache'); + $store = $throttle > 0 ? $app->make(Caches::class)->store(is_string($cache) && $cache !== '' ? $cache : null) : null; + + return new SendSettingsAlert( + $app->make(Notifications::class), + array_values(array_map( + static fn (mixed $rule, int|string $index): AlertRule => is_array($rule) ? AlertRule::fromConfig($rule, $index) : throw new InvalidConfiguration(sprintf('laranail.settings.alerts.rules.%s: each rule is an array.', $index)), + $rules, + array_keys($rules), + )), + $app->make(Definitions::class), + $app->make(Clock::class), + $app->make(OperationalLogger::class), + $app->make(Translator::class), + $store instanceof CacheRepository ? $store : null, + $throttle, + $config->string('laranail.settings.cache.prefix', 'laranail-settings'), + ); + }); + } + + /** + * Typed settings (Phase 5): each class in `typed.classes` registers its definitions when the + * definition registry is first built (and is bound at boot); settings migrations get their + * migrator. + */ + private function registerTyped(): void + { + $app = $this->app; + + $app->afterResolving(DefinitionRegistry::class, static function (DefinitionRegistry $registry) use ($app): void { + foreach (self::strings($app->make(Repository::class), 'laranail.settings.typed.classes') as $class) { + if (! is_subclass_of($class, TypedSettings::class)) { + throw new InvalidConfiguration(sprintf('laranail.settings.typed.classes: [%s] is not a typed settings class.', $class)); + } + + $class::register($registry); + } + }); + + SettingsMigration::resolveMigratorUsing(static fn (): SettingsMigrator => new SettingsMigrator( + $app->make(MigrateSettings::class), + new StoreName($app->make(Repository::class)->string('laranail.settings.default', 'settings')), + Actor::system('settings migration'), + )); + } } diff --git a/src/Services/Access/AccessGuard.php b/src/Services/Access/AccessGuard.php index 3d6e58c..cd81917 100644 --- a/src/Services/Access/AccessGuard.php +++ b/src/Services/Access/AccessGuard.php @@ -5,7 +5,6 @@ namespace Simtabi\Laranail\Settings\Services\Access; use Psr\Log\NullLogger; -use Carbon\CarbonImmutable; use Illuminate\Http\Request; use Psr\Log\LoggerInterface; use Simtabi\Laranail\Settings\Data\Actor; @@ -13,6 +12,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Data\Decision; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; @@ -53,14 +53,14 @@ public function __construct( private ?Dispatcher $events = null, ) {} - /** A guard that denies every actor and audits nowhere: the safe default for a hand-built manager. */ + /** A guard that denies every actor and audits nowhere: the safe default for anything built by hand. */ public static function closed(): self { return new self( new ClosureAuthorizer(static fn (): null => null), new NullVerifier, new ClosureActorResolver(static fn (): null => null), - new Auditor([], static fn (): CarbonImmutable => CarbonImmutable::now()), + new Auditor([], new Clock), new NullLogger, ); } diff --git a/src/Services/Access/Auditor.php b/src/Services/Access/Auditor.php index 012b34d..643f529 100644 --- a/src/Services/Access/Auditor.php +++ b/src/Services/Access/Auditor.php @@ -4,11 +4,10 @@ namespace Simtabi\Laranail\Settings\Services\Access; -use Closure; -use Carbon\CarbonImmutable; use Illuminate\Support\Str; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; @@ -21,13 +20,10 @@ */ final readonly class Auditor { - /** - * @param list $sinks - * @param Closure(): CarbonImmutable $clock - */ + /** @param list $sinks */ public function __construct( private array $sinks, - private Closure $clock, + private Clock $clock, private ?RuntimeConfiguration $runtime = null, ) {} @@ -52,7 +48,7 @@ public function record( $entry = new AuditEntry( id: (string) Str::ulid(), - occurredAt: ($this->clock)(), + occurredAt: $this->clock->now(), action: $action, outcome: $outcome, store: $subject?->store->value, diff --git a/src/Services/Cache/SettingsCache.php b/src/Services/Cache/SettingsCache.php index 394cb4c..bc8d683 100644 --- a/src/Services/Cache/SettingsCache.php +++ b/src/Services/Cache/SettingsCache.php @@ -13,6 +13,8 @@ use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\CacheTarget; use Simtabi\Laranail\Settings\Support\BagCodec; +use Simtabi\Laranail\Settings\Logging\OperationalLogger; +use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** @@ -37,7 +39,7 @@ * `scoped`, so Octane and queue workers start each request and job empty). * * A failing cache never fails a read: the bag is read from the database and the failure is - * reported through `$onFailure`. A failing invalidation is reported the same way. + * reported to the operational log. A failing invalidation is reported the same way. */ final class SettingsCache { @@ -50,16 +52,16 @@ final class SettingsCache /** * @param int $ttl seconds a bag is fresh * @param int $stale seconds after that a stale bag is still answered while it is refreshed - * @param (Closure(): ?string)|null $tenant the current tenant, null outside any tenant - * @param (Closure(string, Throwable): void)|null $onFailure told (operation, exception) when the cache fails + * @param ?TenantDiscriminator $tenant the current tenant, none outside any tenant + * @param ?OperationalLogger $log told when the cache fails */ public function __construct( private readonly Repository $cache, private readonly string $prefix = 'laranail-settings', private readonly int $ttl = 3600, private readonly int $stale = 300, - private readonly ?Closure $tenant = null, - private readonly ?Closure $onFailure = null, + private readonly ?TenantDiscriminator $tenant = null, + private readonly ?OperationalLogger $log = null, private readonly BagCodec $codec = new BagCodec, ) { if ($prefix === '' || $ttl < 1 || $stale < 0) { @@ -313,7 +315,7 @@ private function hash(array $parts): string private function currentTenant(): string { - return ($this->tenant instanceof Closure ? ($this->tenant)() : null) ?? ''; + return $this->tenant?->current() ?? ''; } /** Seconds a bag (and a scope token) is kept: fresh plus stale. */ @@ -345,8 +347,9 @@ private function unique(array $scopes): array private function failed(string $operation, Throwable $exception): void { - if ($this->onFailure instanceof Closure) { - ($this->onFailure)($operation, $exception); - } + $this->log?->warning(sprintf('laranail/settings: the settings cache failed (%s): %s. Reads fall back to the database; a failed invalidation leaves bags stale until they expire or clear-cache runs.', $operation, $exception->getMessage()), [ + 'operation' => $operation, + 'exception' => $exception::class, + ]); } } diff --git a/src/Services/Casting/CasterRegistry.php b/src/Services/Casting/CasterRegistry.php index 3b4eb9d..f7bdfb4 100644 --- a/src/Services/Casting/CasterRegistry.php +++ b/src/Services/Casting/CasterRegistry.php @@ -5,6 +5,7 @@ namespace Simtabi\Laranail\Settings\Services\Casting; use BackedEnum; +use Illuminate\Container\Attributes\Singleton; use Simtabi\Laranail\Settings\Contracts\Caster; use Simtabi\Laranail\Settings\Casting\EnumCaster; use Simtabi\Laranail\Settings\Casting\ArrayCaster; @@ -19,6 +20,7 @@ * Maps type aliases (`string`, `bool`, `enum:plan`) to casters. A stored `type` is always an * alias resolved here, so data can never make the package instantiate an arbitrary class. */ +#[Singleton] final class CasterRegistry { /** @var array */ diff --git a/src/Services/Configuration/PersistedConfiguration.php b/src/Services/Configuration/PersistedConfiguration.php index 19ab662..93b5ccb 100644 --- a/src/Services/Configuration/PersistedConfiguration.php +++ b/src/Services/Configuration/PersistedConfiguration.php @@ -4,19 +4,25 @@ namespace Simtabi\Laranail\Settings\Services\Configuration; -use Closure; use Exception; use Carbon\CarbonImmutable; use Illuminate\Support\Str; use Illuminate\Database\Connection; use Illuminate\Database\Query\Builder; +use Illuminate\Container\Attributes\Config; +use Illuminate\Container\Attributes\Scoped; use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Database\SchemaShape; +use Illuminate\Database\ConnectionResolverInterface; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; +use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** * Store and layer configuration saved through the API (§16.11, `configuration.persisted`), kept in @@ -28,6 +34,7 @@ * A persisted store may not change the layers of a store the configuration file defines: moving a * store's data between drivers is `promote`'s job, not an edit's. */ +#[Scoped] final class PersistedConfiguration { /** @var array{stores: array>, layers: array>}|null */ @@ -39,24 +46,30 @@ final class PersistedConfiguration private int $generation = 0; /** - * @param Closure(): Connection $connection the default store's database connection - * @param Closure(): SchemaShape $shape the recorded schema shape - * @param Closure(array, array): void $validate builds stores and layers, raising InvalidConfiguration + * @param ConnectionResolverInterface $db the default store's database connection is read from it + * @param DriverFactory $drivers validates an entry by building the stores it would produce + * @param mixed $enabled `configuration.persisted` * @param array $configStores `laranail.settings.stores`, which a persisted entry may not re-layer - * @param (Closure(string): void)|null $log told about each skipped entry + * @param array $configLayers `laranail.settings.layers` */ public function __construct( - private readonly bool $enabled, - private readonly Closure $connection, - private readonly Closure $shape, - private readonly Closure $validate, + private readonly ConnectionResolverInterface $db, + private readonly SchemaShapeRepository $shapes, + private readonly DriverFactory $drivers, + private readonly OperationalLogger $log, + #[Config('laranail.settings.configuration.persisted', false)] + private readonly mixed $enabled = false, + #[Config('laranail.settings.stores', [])] private readonly array $configStores = [], - private readonly ?Closure $log = null, + #[Config('laranail.settings.layers', [])] + private readonly array $configLayers = [], + #[Config('laranail.settings.default', 'settings')] + private readonly string $default = 'settings', ) {} public function isEnabled(): bool { - return $this->enabled && ($this->shape)()->storesTable; + return filter_var($this->enabled, FILTER_VALIDATE_BOOL) && $this->shape()->storesTable; } /** Changes whenever an entry is saved or deleted, so registries rebuild. */ @@ -221,16 +234,14 @@ private function check(string $kind, string $name, array $config, array $stores, throw new InvalidConfiguration(sprintf('Persisted store [%s] would change the layers the configuration file gives it; change them there and promote the data.', $name)); } - ($this->validate)($stores, $layers); + new StoreRegistry($this->drivers, $this->default, array_replace($this->configStores, $stores), array_replace($this->configLayers, $layers))->validate(); } private function skip(string $problem): void { $this->problems[] = $problem; - if ($this->log instanceof Closure) { - ($this->log)('laranail/settings skipped a persisted configuration entry: ' . $problem); - } + $this->log->warning('laranail/settings skipped a persisted configuration entry: ' . $problem); } private function changed(): void @@ -249,11 +260,37 @@ private function assertEnabled(): void private function table(): Builder { try { - $connection = ($this->connection)(); + $connection = $this->connection(); } catch (Exception $exception) { throw new DriverFailure('The persisted configuration connection is unavailable.', 0, $exception); } - return $connection->table(($this->shape)()->names->stores()); + return $connection->table($this->shape()->names->stores()); + } + + private function shape(): SchemaShape + { + return $this->shapes->current(); + } + + /** The connection of the default store's first database layer, as the configuration file names it. */ + private function connection(): Connection + { + $default = $this->configStores[$this->default] ?? null; + $connection = null; + + foreach ((array) (is_array($default) ? ($default['layers'] ?? []) : []) as $layer) { + $config = is_string($layer) ? ($this->configLayers[$layer] ?? null) : null; + + if (is_array($config) && ($config['driver'] ?? null) === 'database') { + $connection = is_string($config['connection'] ?? null) ? $config['connection'] : null; + + break; + } + } + + $resolved = $this->db->connection($connection); + + return $resolved instanceof Connection ? $resolved : throw new InvalidConfiguration('laranail.settings.configuration: the default store\'s database connection is not a database connection.'); } } diff --git a/src/Services/Database/SchemaShapeRepository.php b/src/Services/Database/SchemaShapeRepository.php index eeb97f1..111c208 100644 --- a/src/Services/Database/SchemaShapeRepository.php +++ b/src/Services/Database/SchemaShapeRepository.php @@ -4,9 +4,9 @@ namespace Simtabi\Laranail\Settings\Services\Database; -use Closure; use Throwable; use Illuminate\Filesystem\Filesystem; +use Illuminate\Contracts\Config\Repository; use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Database\StoreSchema; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; @@ -22,11 +22,11 @@ final class SchemaShapeRepository { private ?SchemaShape $current = null; - /** @param Closure(): SchemaShape $configured the shape the current configuration describes */ + /** @param Repository $config the configuration the configured shape is described by */ public function __construct( private readonly Filesystem $files, private readonly string $path, - private readonly Closure $configured, + private readonly Repository $config, ) {} public function path(): string @@ -64,7 +64,9 @@ public function recorded(): ?SchemaShape /** The shape the current configuration describes. */ public function configured(): SchemaShape { - return ($this->configured)(); + $settings = $this->config->get('laranail.settings'); + + return SchemaShape::fromConfig(is_array($settings) ? $settings : [], $this->config->get('laranail.db-tools.id_type')); } /** What the runtime and the migrations use: the recorded shape, else the configured one. */ diff --git a/src/Services/Definitions/DatabaseDefinitions.php b/src/Services/Definitions/DatabaseDefinitions.php index f63f18a..f339275 100644 --- a/src/Services/Definitions/DatabaseDefinitions.php +++ b/src/Services/Definitions/DatabaseDefinitions.php @@ -11,7 +11,6 @@ use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Enums\TranslationsMode; use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; @@ -44,16 +43,6 @@ public function __construct( private readonly bool $enabled = true, ) {} - /** - * A label as text: itself, or (json mode) the entry for any locale, else the first one. - * - * @deprecated 0.1 Use {@see Translations::nullableText()}; this forwards to it and is removed in 1.0. - */ - public static function localised(?string $stored, bool $json): ?string - { - return new Translations($json ? TranslationsMode::Json : TranslationsMode::Lang)->nullableText($stored); - } - /** Forget the store's loaded rows, so the next read sees a definition just saved or deleted. */ public function forget(Store $store): void { diff --git a/src/Services/Definitions/Definitions.php b/src/Services/Definitions/Definitions.php new file mode 100644 index 0000000..be805b7 --- /dev/null +++ b/src/Services/Definitions/Definitions.php @@ -0,0 +1,40 @@ +findInCode($store->name, $key) ?? $this->database->find($store, $key); + } + + /** + * Runtime, then code and config, without the definitions table: what an alert listener reads, + * so delivering an alert never queries the database. + */ + public function findInCode(StoreName $store, Key $key): ?Definition + { + return $this->runtime->findDefinition($store, $key) ?? $this->registry->find($store, $key); + } +} diff --git a/src/Services/Drivers/DriverFactory.php b/src/Services/Drivers/DriverFactory.php index 7c0d023..7e4bd97 100644 --- a/src/Services/Drivers/DriverFactory.php +++ b/src/Services/Drivers/DriverFactory.php @@ -19,9 +19,9 @@ use Illuminate\Contracts\Filesystem\Factory as Disks; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Drivers\ReadOnlyValues; -use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Support\RecordSerializer; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; /** * Builds a layer's driver. Built-in names resolve through {@see DriverType} and an exhaustive @@ -120,7 +120,7 @@ private function database(LayerConfig $layer): DatabaseDriver SchemaNames::assertTable($table, sprintf('laranail.settings.layers.%s.table', $layer->name)); } - /** @var Closure(): ReadinessProbe $probe */ + /** @var Closure(): SchemaReadinessInterface $probe */ $probe = $this->probe; /** @var (Closure(): SchemaShape)|null $shape */ diff --git a/src/Services/Resolution/Resolver.php b/src/Services/Resolution/Resolver.php index 1623772..3aa2bbe 100644 --- a/src/Services/Resolution/Resolver.php +++ b/src/Services/Resolution/Resolver.php @@ -8,6 +8,8 @@ use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\Lookup; +use Illuminate\Container\Attributes\Config; +use Illuminate\Container\Attributes\Scoped; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\RecordSet; @@ -29,11 +31,13 @@ * application's fallback locale and then to the unlocalised value. Absence moves on; a stored * null is an answer. Each store is read once per resolution, whatever the number of steps. */ +#[Scoped] final readonly class Resolver { public function __construct( private StoreRegistry $stores, private ValuePipeline $pipeline, + #[Config('app.fallback_locale', 'en')] private string $fallbackLocale, private PreloadedRecords $preloaded = new PreloadedRecords, private ?TenantDiscriminator $tenant = null, diff --git a/src/Services/Resolution/ScopeKeys.php b/src/Services/Resolution/ScopeKeys.php new file mode 100644 index 0000000..e982837 --- /dev/null +++ b/src/Services/Resolution/ScopeKeys.php @@ -0,0 +1,42 @@ + */ + public function keys(Store $store, Scope $scope): array + { + $keys = []; + + foreach ($store->load([$scope]) as $records) { + foreach ($records->all() as $record) { + $keys[$record->key->value] = true; + } + } + + foreach ($this->definitions->all() as $definition) { + if ($definition->store->value === $store->name->value) { + $keys[$definition->key->value] = true; + } + } + + $keys = array_map(strval(...), array_keys($keys)); + sort($keys); + + return $keys; + } +} diff --git a/src/Services/Resolution/SettingTargets.php b/src/Services/Resolution/SettingTargets.php index 1aca29a..f697856 100644 --- a/src/Services/Resolution/SettingTargets.php +++ b/src/Services/Resolution/SettingTargets.php @@ -4,7 +4,6 @@ namespace Simtabi\Laranail\Settings\Services\Resolution; -use Closure; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Scope; @@ -12,12 +11,12 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Data\StoreName; -use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Data\SettingTarget; use Simtabi\Laranail\Settings\Data\SettingAddress; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; /** * Turns a {@see SettingAddress} (how a caller outside PHP names a setting) into what the actions @@ -26,10 +25,9 @@ */ final readonly class SettingTargets { - /** @param Closure(Store, Key): ?Definition $definitions */ public function __construct( private StoreRegistry $stores, - private Closure $definitions, + private Definitions $definitions, ) {} public function store(string $name): Store @@ -48,7 +46,7 @@ public function target(SettingAddress $address, ?string $reason = null): Setting throw new OwnerNotAllowed(sprintf('Store [%s] does not accept owner alias [%s].', $store->name, $owner->alias)); } - return new SettingTarget($store, $key, new Locale($address->locale), $owner, ($this->definitions)($store, $key), $reason); + return new SettingTarget($store, $key, new Locale($address->locale), $owner, $this->definitions->find($store, $key), $reason); } /** The settings handle reading this address's store, owner and locale as the actor. */ diff --git a/src/Services/Stores/SettingWriter.php b/src/Services/Stores/SettingWriter.php index 93b54ca..52a78e7 100644 --- a/src/Services/Stores/SettingWriter.php +++ b/src/Services/Stores/SettingWriter.php @@ -4,17 +4,17 @@ namespace Simtabi\Laranail\Settings\Services\Stores; -use Closure; -use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\Record; +use Illuminate\Container\Attributes\Config; use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Stores\Layer; use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Events\SettingSaved; use Simtabi\Laranail\Settings\Events\SettingLocked; @@ -27,6 +27,7 @@ use Simtabi\Laranail\Settings\Events\SettingForgetting; use Simtabi\Laranail\Settings\Exceptions\LockedSetting; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; +use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; @@ -51,16 +52,14 @@ */ final readonly class SettingWriter { - /** - * @param Closure(): CarbonImmutable $clock - * @param (Closure(Store, Key, Scope, ConcurrentModification): void)|null $onRetry told before a retry (logging) - */ + /** @param bool $retryOnConflict `writes.retry_on_conflict`; a retry is logged */ public function __construct( private ValuePipeline $pipeline, private Dispatcher $events, - private Closure $clock, - private bool $retryOnConflict = false, - private ?Closure $onRetry = null, + private Clock $clock, + private OperationalLogger $log, + #[Config('laranail.settings.writes.retry_on_conflict', true)] + private bool $retryOnConflict = true, private ?Actor $causer = null, private ?string $reason = null, ) {} @@ -68,7 +67,7 @@ public function __construct( /** A copy whose history entries name this causer and reason (null causer: the system). */ public function causedBy(?Actor $causer, ?string $reason = null): self { - return new self($this->pipeline, $this->events, $this->clock, $this->retryOnConflict, $this->onRetry, $causer, $reason); + return new self($this->pipeline, $this->events, $this->clock, $this->log, $this->retryOnConflict, $causer, $reason); } /** @@ -155,9 +154,12 @@ private function write(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, throw $conflict; } - if ($this->onRetry instanceof Closure) { - ($this->onRetry)($store, $key, $this->scope($owner), $conflict); - } + $scope = $this->scope($owner); + $this->log->info(sprintf('laranail/settings retried a write of [%s] in store [%s] for scope [%s] after a concurrent change.', $key, $store->name, $scope), [ + 'store' => $store->name->value, + 'key' => $key->value, + 'scope' => $scope->value, + ]); } } } @@ -188,7 +190,7 @@ private function writeOnce(Store $store, Key $key, Locale $locale, ?OwnerRef $ow encrypted: $definition instanceof Definition && $definition->encrypted, locked: $existing->locked ?? false, version: $version, - writtenAt: ($this->clock)(), + writtenAt: $this->clock->now(), group: $definition?->group(), category: $definition?->category, public: $definition instanceof Definition && $definition->public, @@ -233,7 +235,7 @@ private function persist(Store $store, Layer $layer, HistoryOperation $operation $history->database()->transaction(function () use ($store, $layer, $history, $operation, $before, $after): void { $layer->driver->put($store->name, $after); - $history->record($store->name, $operation, $before, $after, $after->version, $history->database()->reference($store->name, $after->scope, $after->key, $after->locale), $this->causer, $this->reason, ($this->clock)()); + $history->record($store->name, $operation, $before, $after, $after->version, $history->database()->reference($store->name, $after->scope, $after->key, $after->locale), $this->causer, $this->reason, $this->clock->now()); }, $store->name); } @@ -270,7 +272,7 @@ private function remove(Store $store, Key $key, Locale $locale, ?OwnerRef $owner $history->database()->transaction(function () use ($store, $layer, $history, $scope, $key, $locale, $existing): void { $reference = $history->database()->reference($store->name, $scope, $key, $locale); $layer->driver->forget($store->name, $scope, $key, $locale); - $history->record($store->name, HistoryOperation::Forget, $existing, null, $existing->version, $reference, $this->causer, $this->reason, ($this->clock)()); + $history->record($store->name, HistoryOperation::Forget, $existing, null, $existing->version, $reference, $this->causer, $this->reason, $this->clock->now()); }, $store->name); } else { $layer->driver->forget($store->name, $scope, $key, $locale); @@ -299,7 +301,7 @@ private function storeLock(Store $store, Key $key, Locale $locale, ?OwnerRef $ow $existing->encrypted, $locked, $existing->version + 1, - ($this->clock)(), + $this->clock->now(), $definition?->group(), $definition?->category, $definition instanceof Definition && $definition->public, diff --git a/src/Services/Stores/StoreRegistry.php b/src/Services/Stores/StoreRegistry.php index 59f3cb4..3f40e8a 100644 --- a/src/Services/Stores/StoreRegistry.php +++ b/src/Services/Stores/StoreRegistry.php @@ -5,6 +5,7 @@ namespace Simtabi\Laranail\Settings\Services\Stores; use Closure; +use Illuminate\Contracts\Events\Dispatcher; use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Stores\Layer; use Simtabi\Laranail\Settings\Stores\Store; @@ -12,15 +13,14 @@ use Simtabi\Laranail\Settings\Contracts\Driver; use Simtabi\Laranail\Settings\Data\LayerConfig; use Simtabi\Laranail\Settings\Enums\DriverType; +use Simtabi\Laranail\Settings\Events\LayerSkipped; use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Database\StoreSchema; -use Simtabi\Laranail\Settings\Support\ConfigValues; use Simtabi\Laranail\Settings\Drivers\CachingDriver; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\UnknownStore; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; -use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; use Simtabi\Laranail\Settings\Stores\InstallationEvidence; use Simtabi\Laranail\Settings\Drivers\BootstrapGatedDriver; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; @@ -45,7 +45,7 @@ final class StoreRegistry /** * @param array $storeConfig `laranail.settings.stores` * @param array $layerConfig `laranail.settings.layers` - * @param (Closure(string, string, string): void)|null $onLayerSkipped told (store, layer, reason) when bootstrap mode skips a layer + * @param ?Dispatcher $events told ({@see LayerSkipped}) when bootstrap mode skips a layer * @param list $sources `configuration.sources`: the merge order of config, database (persisted) and runtime entries, later wins */ public function __construct( @@ -55,8 +55,8 @@ public function __construct( private readonly array $layerConfig, private readonly ?Driver $override = null, private readonly ?RuntimeConfiguration $runtime = null, - private readonly ?BootstrapEvidence $evidence = null, - private readonly ?Closure $onLayerSkipped = null, + private readonly ?InstallationEvidence $evidence = null, + private readonly ?Dispatcher $events = null, private readonly ?SettingsCache $cache = null, private readonly ?PersistedConfiguration $persisted = null, private readonly array $sources = ['config', 'database', 'runtime'], @@ -65,7 +65,7 @@ public function __construct( /** A copy whose every layer is replaced by one driver (used by the fake). */ public function withEveryLayer(Driver $driver): self { - return new self($this->drivers, $this->default, $this->storeConfig, $this->layerConfig, $driver, $this->runtime, $this->evidence, $this->onLayerSkipped, $this->cache, $this->persisted, $this->sources); + return new self($this->drivers, $this->default, $this->storeConfig, $this->layerConfig, $driver, $this->runtime, $this->evidence, $this->events, $this->cache, $this->persisted, $this->sources); } /** @@ -220,16 +220,7 @@ private function gatedLayer(Layer $layer, StoreName $store, bool $bootstrap): La return $layer; } - $onSkip = $this->onLayerSkipped; - - return new Layer($name, new BootstrapGatedDriver( - $layer->driver, - $store, - $this->evidence ?? new InstallationEvidence(false), - $onSkip instanceof Closure ? static function (string $reason) use ($onSkip, $store, $name): void { - $onSkip($store->value, $name, $reason); - } : null, - ), $layer->type); + return new Layer($name, new BootstrapGatedDriver($layer->driver, $store, $this->evidence ?? new InstallationEvidence(false), $this->events, $name), $layer->type); } /** @param array $extra options the store adds (the database table) */ @@ -320,9 +311,15 @@ private function approvalKeys(mixed $approvals, string $path): array return $globs; } - /** @return list */ + /** @return list a list of strings, or InvalidConfiguration naming `$path` */ private function strings(mixed $value, string $path): array { - return ConfigValues::listOfStrings($value, $path); + $strings = is_array($value) ? array_values(array_filter($value, is_string(...))) : null; + + if ($strings === null || count($strings) !== count($value)) { + throw new InvalidConfiguration($path . ': a list of strings is required.'); + } + + return $strings; } } diff --git a/src/Services/Transfer/Importers.php b/src/Services/Transfer/Importers.php index 494a97a..5c3b0ec 100644 --- a/src/Services/Transfer/Importers.php +++ b/src/Services/Transfer/Importers.php @@ -4,7 +4,8 @@ namespace Simtabi\Laranail\Settings\Services\Transfer; -use Closure; +use Illuminate\Container\Attributes\Config; +use Illuminate\Contracts\Container\Container; use Simtabi\Laranail\Settings\Contracts\Importer; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; @@ -16,12 +17,13 @@ final readonly class Importers { /** + * @param Container $container builds a configured importer with its dependencies * @param array $classes `laranail.settings.importers` - * @param Closure(class-string): object $make builds a class with its dependencies */ public function __construct( - private array $classes, - private Closure $make, + private Container $container, + #[Config('laranail.settings.importers', [])] + private array $classes = [], ) {} /** @return list */ @@ -38,7 +40,7 @@ public function get(string $name): Importer throw new InvalidConfiguration(sprintf('laranail.settings.importers.%s: [%s] is not a class implementing %s (known importers: %s).', $name, is_string($class) ? $class : 'missing', Importer::class, implode(', ', $this->names()))); } - $importer = ($this->make)($class); + $importer = $this->container->make($class); return $importer instanceof Importer ? $importer : throw new InvalidConfiguration(sprintf('laranail.settings.importers.%s: [%s] did not build an importer.', $name, $class)); } diff --git a/src/Services/Transfer/StoreSnapshots.php b/src/Services/Transfer/StoreSnapshots.php index 9c8665f..6302907 100644 --- a/src/Services/Transfer/StoreSnapshots.php +++ b/src/Services/Transfer/StoreSnapshots.php @@ -11,10 +11,10 @@ use Simtabi\Laranail\Settings\Enums\ExportMode; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; -use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Data\Transfer\ExportedSetting; +use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Data\Transfer\ExportedCategory; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; @@ -26,7 +26,7 @@ final readonly class StoreSnapshots { public function __construct( - private ValueEncrypter $encrypter, + private LaravelValueEncrypter $encrypter, private ValueEncoder $encoder, ) {} diff --git a/src/Services/Values/ValuePipeline.php b/src/Services/Values/ValuePipeline.php index e911077..50f01f5 100644 --- a/src/Services/Values/ValuePipeline.php +++ b/src/Services/Values/ValuePipeline.php @@ -6,22 +6,24 @@ use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Record; +use Illuminate\Container\Attributes\Singleton; use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Support\ValueEncoder; -use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; -use Simtabi\Laranail\Settings\Contracts\ValueValidator; +use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; +use Simtabi\Laranail\Settings\Support\LaravelValueValidator; use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; /** * Turns a caller's value into a stored payload (validate raw → cast → encode → encrypt) and a * stored record back into a value (decrypt → decode → cast). */ +#[Singleton] final readonly class ValuePipeline { public function __construct( private CasterRegistry $casters, - private ValueValidator $validator, - private ValueEncrypter $encrypter, + private LaravelValueValidator $validator, + private LaravelValueEncrypter $encrypter, private ValueEncoder $encoder, ) {} diff --git a/src/SettingsManager.php b/src/SettingsManager.php index 647e169..c043093 100644 --- a/src/SettingsManager.php +++ b/src/SettingsManager.php @@ -25,86 +25,107 @@ use Simtabi\Laranail\Settings\Data\HistoryEntry; use Simtabi\Laranail\Settings\Data\SettingWrite; use Simtabi\Laranail\Settings\Actions\ClearCache; +use Simtabi\Laranail\Settings\Actions\FlushScope; use Simtabi\Laranail\Settings\Actions\QueryAudit; +use Simtabi\Laranail\Settings\Actions\SetSetting; use Simtabi\Laranail\Settings\Contracts\Settable; use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Data\ChangeRequest; use Simtabi\Laranail\Settings\Data\HistoryFilter; use Simtabi\Laranail\Settings\Data\SettingTarget; +use Simtabi\Laranail\Settings\Actions\DiffHistory; +use Simtabi\Laranail\Settings\Actions\LockSetting; use Simtabi\Laranail\Settings\Approvals\Approvals; use Simtabi\Laranail\Settings\Data\ChangeProposal; -use Simtabi\Laranail\Settings\Actions\StoreActions; +use Simtabi\Laranail\Settings\Actions\PromoteStore; +use Simtabi\Laranail\Settings\Actions\QueryHistory; use Simtabi\Laranail\Settings\Data\PromotionReport; use Simtabi\Laranail\Settings\History\HistoryQuery; +use Simtabi\Laranail\Settings\Actions\ForgetSetting; +use Simtabi\Laranail\Settings\Actions\UnlockSetting; use Simtabi\Laranail\Settings\Data\PromotionRequest; use Simtabi\Laranail\Settings\Enums\ChangeOperation; -use Simtabi\Laranail\Settings\Actions\HistoryActions; -use Simtabi\Laranail\Settings\Actions\SettingActions; +use Simtabi\Laranail\Settings\Exceptions\InvalidKey; use Simtabi\Laranail\Settings\Resolution\Explanation; +use Simtabi\Laranail\Settings\Actions\RollbackSetting; use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; +use Simtabi\Laranail\Settings\Exceptions\AccessDenied; use Simtabi\Laranail\Settings\Exceptions\TypeMismatch; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; +use Simtabi\Laranail\Settings\Actions\Transfer\DiffStore; use Simtabi\Laranail\Settings\Categories\CategoryManager; use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; use Simtabi\Laranail\Settings\Exceptions\OwnerNotAllowed; use Simtabi\Laranail\Settings\Data\Transfer\ExportRequest; use Simtabi\Laranail\Settings\Data\Transfer\ImportRequest; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; +use Simtabi\Laranail\Settings\Actions\Transfer\ExportStore; +use Simtabi\Laranail\Settings\Actions\Transfer\ImportStore; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Services\Resolution\Resolver; -use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; +use Simtabi\Laranail\Settings\Actions\Reads\ListDefinitions; +use Simtabi\Laranail\Settings\Services\Resolution\ScopeKeys; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Actions\Transfer\TransferActions; -use Simtabi\Laranail\Settings\Actions\Approvals\ApprovalActions; +use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; -use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; -use Simtabi\Laranail\Settings\Actions\Configuration\ConfigurationActions; use Simtabi\Laranail\Settings\Configuration\PersistedConfigurationEditor; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** * The {@see Settings} implementation: an immutable handle over the store, owner, locale and * actor it targets. Reads go through the {@see Resolver} after the {@see AccessGuard} has - * checked them; writes go through the {@see SettingActions}, which authorize and audit. + * checked them; writes go through the write actions, which authorize and audit. Every fluent + * method returns a copy, so a handle is never changed in place. */ -final readonly class SettingsManager implements Settings +final class SettingsManager implements Settings { - private SettingActions $actions; + private ?StoreName $storeName = null; - private AccessGuard $access; + private ?OwnerRef $owner = null; + + /** @var list */ + private array $parents = []; + + private ?Locale $selectedLocale = null; + + private ?Actor $actingAs = null; + + private ?string $reason = null; /** - * The trailing collaborators are optional so a hand-built manager keeps working: without an - * access guard every actor is denied (fail closed) while trusted calls behave as before. - * - * @param list $parents + * Every collaborator is required and built by the container; what a handle targets (store, + * owner, locale, actor, reason) is set on a copy by the fluent methods ({@see with()}). */ public function __construct( - private StoreRegistry $stores, - private DefinitionRegistry $definitions, - private Resolver $resolver, - private SettingWriter $writer, - private ?StoreName $storeName = null, - private ?OwnerRef $owner = null, - private array $parents = [], - private ?Locale $selectedLocale = null, - ?SettingActions $actions = null, - ?AccessGuard $access = null, - private ?RuntimeConfiguration $runtime = null, - private ?Actor $actingAs = null, - private ?string $reason = null, - private ?StoreActions $storeActions = null, - private ?QueryAudit $auditQuery = null, - private ?DatabaseDefinitions $databaseDefinitions = null, - private ?HistoryActions $historyActions = null, - private ?ApprovalActions $approvalActions = null, - private ?TransferActions $transferActions = null, - private ?ConfigurationActions $configurationActions = null, - ) { - $this->access = $access ?? AccessGuard::closed(); - $this->actions = $actions ?? SettingActions::using($writer, $this->access); - } + private readonly StoreRegistry $stores, + private readonly DefinitionRegistry $registry, + private readonly Definitions $definitions, + private readonly Resolver $resolver, + private readonly AccessGuard $access, + private readonly RuntimeConfiguration $runtime, + private readonly SetSetting $set, + private readonly ForgetSetting $forget, + private readonly LockSetting $lock, + private readonly UnlockSetting $unlock, + private readonly FlushScope $flushScope, + private readonly ClearCache $clearCache, + private readonly WarmCache $warmCache, + private readonly PromoteStore $promote, + private readonly QueryAudit $auditQuery, + private readonly QueryHistory $historyQuery, + private readonly RollbackSetting $rollback, + private readonly DiffHistory $diffHistory, + private readonly ProposeChange $propose, + private readonly ExportStore $export, + private readonly ImportStore $import, + private readonly DiffStore $diffStore, + private readonly ListDefinitions $listDefinitions, + private readonly CategoryManager $categories, + private readonly Approvals $approvals, + private readonly PersistedConfigurationEditor $configurationEditor, + ) {} public function store(string $name): static { @@ -156,7 +177,7 @@ public function actor(): ?Actor public function configuration(): RuntimeConfiguration { - return $this->runtime ?? throw new LogicException('This settings handle was built without runtime configuration; resolve Settings from the container.'); + return $this->runtime; } public function withConfiguration(callable $change, callable $run): mixed @@ -185,6 +206,57 @@ public function has(string $key): bool return $this->lookup($key)->isFound(); } + public function missing(string $key): bool + { + return ! $this->has($key); + } + + public function many(array $keys): array + { + $values = []; + + foreach ($keys as $key => $default) { + if (is_int($key)) { + $key = is_string($default) ? $default : throw new InvalidKey('many() takes setting keys, or key => default pairs.'); + $default = null; + } + + $values[$key] = $this->get($key, $default); + } + + return $values; + } + + public function all(?string $prefix = null): array + { + $store = $this->targetStore(); + $prefix = $prefix === null ? null : new Key(rtrim($prefix, '.'))->value; + $values = []; + + foreach (new ScopeKeys($this->registry)->keys($store, $this->scope()) as $key) { + if ($prefix !== null && $key !== $prefix && ! str_starts_with($key, $prefix . '.')) { + continue; + } + + try { + $lookup = $this->lookup($key); + } catch (AccessDenied|UnknownSetting) { + continue; + } + + if ($lookup->isFound()) { + $values[$key] = $lookup->value(); + } + } + + return $values; + } + + public function definitions(): array + { + return $this->listDefinitions->handle($this->targetStore(), $this->actingAs); + } + public function string(string $key): string { $value = $this->required($key); @@ -237,7 +309,7 @@ public function set(string $key, mixed $value): void $target = $this->writeTarget($key); try { - $this->actions->set->handle(new SettingWrite($target, $value), $this->actingAs); + $this->set->handle(new SettingWrite($target, $value), $this->actingAs); } finally { $this->resolver->forgetPreloaded($target->store, $this->scope()); } @@ -248,18 +320,46 @@ public function forget(string $key): void $target = $this->writeTarget($key); try { - $this->actions->forget->handle($target, $this->actingAs); + $this->forget->handle($target, $this->actingAs); } finally { $this->resolver->forgetPreloaded($target->store, $this->scope()); } } + public function setMany(array $values): void + { + foreach ($values as $key => $value) { + $this->set($key, $value); + } + } + + public function forgetMany(iterable $keys): void + { + foreach ($keys as $key) { + $this->forget($key); + } + } + + public function remember(string $key, callable $value): mixed + { + $lookup = $this->lookup($key); + + if ($lookup->isFound()) { + return $lookup->value(); + } + + $computed = $value(); + $this->set($key, $computed); + + return $this->get($key, $computed); + } + public function lock(string $key): void { $target = $this->writeTarget($key); try { - $this->actions->lock->handle($target, $this->actingAs); + $this->lock->handle($target, $this->actingAs); } finally { $this->resolver->forgetPreloaded($target->store, $this->scope()); } @@ -270,7 +370,7 @@ public function unlock(string $key): void $target = $this->writeTarget($key); try { - $this->actions->unlock->handle($target, $this->actingAs); + $this->unlock->handle($target, $this->actingAs); } finally { $this->resolver->forgetPreloaded($target->store, $this->scope()); } @@ -282,7 +382,7 @@ public function flush(): void $owner = $this->owner ?? throw new LogicException('flush() removes one owner\'s values; call for($owner) first.'); try { - $this->storeActions()->flush->handle($store, $owner, $this->actingAs); + $this->flushScope->handle($store, $owner, $this->actingAs); } finally { $this->resolver->forgetPreloaded($store, $this->scope()); } @@ -290,12 +390,12 @@ public function flush(): void public function clearCache(): void { - $this->clearCacheAction()->handle($this->targetStore(), $this->owner, $this->actingAs); + $this->clearCache->handle($this->targetStore(), $this->owner, $this->actingAs); } public function warmCache(): int { - return $this->warmCacheAction()->handle($this->targetStore(), $this->owner, $this->actingAs); + return $this->warmCache->handle($this->targetStore(), $this->owner, $this->actingAs); } public function preload(iterable $owners): void @@ -325,20 +425,17 @@ public function preload(iterable $owners): void public function categories(): CategoryManager { - return new CategoryManager($this->targetStore(), $this->actingAs, $this->storeActions()->categories, $this->access); + return $this->categories->in($this->targetStore(), $this->actingAs); } public function promote(?PromotionRequest $request = null): PromotionReport { - return $this->storeActions()->promote->handle($this->targetStore(), $request ?? new PromotionRequest, $this->actingAs); + return $this->promote->handle($this->targetStore(), $request ?? new PromotionRequest, $this->actingAs); } public function audit(): AuditQuery { - $query = new AuditQuery( - $this->auditQuery ?? throw new LogicException('This settings handle was built without the audit query; resolve Settings from the container.'), - $this->actingAs, - ); + $query = new AuditQuery($this->auditQuery, $this->actingAs); return $this->storeName instanceof StoreName ? $query->store($this->storeName->value) : $query; } @@ -350,7 +447,7 @@ public function history(): HistoryQuery $actor = $this->actingAs; return new HistoryQuery( - $this->historyActions()->query, + $this->historyQuery, $actor, $filter, $actor instanceof Actor ? function (HistoryEntry $entry) use ($actor): bool { @@ -369,7 +466,7 @@ public function rollback(string $key, int $toVersion): int $target = $this->writeTarget($key); try { - return $this->historyActions()->rollback->handle($target, $toVersion, $this->actingAs); + return $this->rollback->handle($target, $toVersion, $this->actingAs); } finally { $this->resolver->forgetPreloaded($target->store, $this->scope()); } @@ -377,76 +474,42 @@ public function rollback(string $key, int $toVersion): int public function historyDiff(string $key, int $from, int $to): HistoryDiff { - return $this->historyActions()->diff->handle($this->writeTarget($key), $from, $to, $this->actingAs); + return $this->diffHistory->handle($this->writeTarget($key), $from, $to, $this->actingAs); } public function propose(string $key, mixed $value): ChangeRequest { - return $this->approvalActions()->propose->handle(new ChangeProposal($this->writeTarget($key), ChangeOperation::Set, $value), $this->actingAs); + return $this->propose->handle(new ChangeProposal($this->writeTarget($key), ChangeOperation::Set, $value), $this->actingAs); } public function approvals(): Approvals { - return new Approvals($this->approvalActions(), $this->targetStore(), $this->actingAs); + return $this->approvals->in($this->targetStore(), $this->actingAs); } public function export(ExportMode $mode = ExportMode::Redacted): ExportDocument { - return $this->transferActions()->export->handle(new ExportRequest($this->targetStore(), $mode), $this->actingAs); + return $this->export->handle(new ExportRequest($this->targetStore(), $mode), $this->actingAs); } public function import(ExportDocument $document): ImportReport { - return $this->transferActions()->import->handle(new ImportRequest($this->targetStore(), $document, apply: true, reason: $this->reason ?? $this->actingAs?->context->reason), $this->actingAs); + return $this->import->handle(new ImportRequest($this->targetStore(), $document, apply: true, reason: $this->reason ?? $this->actingAs?->context->reason), $this->actingAs); } public function previewImport(ExportDocument $document): ImportReport { - return $this->transferActions()->import->handle(new ImportRequest($this->targetStore(), $document), $this->actingAs); + return $this->import->handle(new ImportRequest($this->targetStore(), $document), $this->actingAs); } public function compare(ExportDocument $document): StoreDiff { - return $this->transferActions()->diff->handle($this->targetStore(), $document, $this->actingAs); + return $this->diffStore->handle($this->targetStore(), $document, $this->actingAs); } public function persistedConfiguration(): PersistedConfigurationEditor { - return new PersistedConfigurationEditor( - $this->configurationActions ?? throw new LogicException('This settings handle was built without the configuration actions; resolve Settings from the container.'), - $this->targetStore(), - $this->actingAs, - ); - } - - private function transferActions(): TransferActions - { - return $this->transferActions ?? throw new LogicException('This settings handle was built without the transfer actions; resolve Settings from the container.'); - } - - private function approvalActions(): ApprovalActions - { - return $this->approvalActions ?? throw new LogicException('This settings handle was built without the approval actions; resolve Settings from the container.'); - } - - private function historyActions(): HistoryActions - { - return $this->historyActions ?? throw new LogicException('This settings handle was built without the history actions; resolve Settings from the container.'); - } - - private function storeActions(): StoreActions - { - return $this->storeActions ?? throw new LogicException('This settings handle was built without store actions; resolve Settings from the container.'); - } - - private function clearCacheAction(): ClearCache - { - return $this->storeActions()->clearCache ?? throw new LogicException('This settings handle was built without the cache actions; resolve Settings from the container.'); - } - - private function warmCacheAction(): WarmCache - { - return $this->storeActions()->warmCache ?? throw new LogicException('This settings handle was built without the cache actions; resolve Settings from the container.'); + return $this->configurationEditor->in($this->targetStore(), $this->actingAs); } private function scope(): Scope @@ -522,9 +585,7 @@ private function activeLocale(): Locale */ private function definition(Store $store, Key $key): ?Definition { - return $this->runtime?->findDefinition($store->name, $key) - ?? $this->definitions->find($store->name, $key) - ?? $this->databaseDefinitions?->find($store, $key); + return $this->definitions->find($store, $key); } private function required(string $key): mixed @@ -548,27 +609,14 @@ private function with( ?Actor $actor = null, ?string $reason = null, ): self { - return new self( - $this->stores, - $this->definitions, - $this->resolver, - $this->writer, - $storeName ?? $this->storeName, - $owner ?? $this->owner, - $parents ?? $this->parents, - $locale ?? $this->selectedLocale, - $this->actions, - $this->access, - $this->runtime, - $actor ?? $this->actingAs, - $reason ?? $this->reason, - $this->storeActions, - $this->auditQuery, - $this->databaseDefinitions, - $this->historyActions, - $this->approvalActions, - $this->transferActions, - $this->configurationActions, - ); + $handle = clone $this; + $handle->storeName = $storeName ?? $this->storeName; + $handle->owner = $owner ?? $this->owner; + $handle->parents = $parents ?? $this->parents; + $handle->selectedLocale = $locale ?? $this->selectedLocale; + $handle->actingAs = $actor ?? $this->actingAs; + $handle->reason = $reason ?? $this->reason; + + return $handle; } } diff --git a/src/Stores/InstallationEvidence.php b/src/Stores/InstallationEvidence.php index aa4c0ce..8034767 100644 --- a/src/Stores/InstallationEvidence.php +++ b/src/Stores/InstallationEvidence.php @@ -5,7 +5,6 @@ namespace Simtabi\Laranail\Settings\Stores; use Closure; -use Simtabi\Laranail\Settings\Contracts\BootstrapEvidence; /** * Bootstrap evidence from the operator's flag (`laranail.settings.bootstrap`, set for the install @@ -13,7 +12,7 @@ * `isInstalled()` is deliberately not used: with its marker missing it probes the live database, * which answers "not installed" during an outage. */ -final readonly class InstallationEvidence implements BootstrapEvidence +final readonly class InstallationEvidence { /** @param (Closure(): bool)|null $installing installer-headless' `isInstalling()`, when that package is present */ public function __construct( diff --git a/src/Support/Clock.php b/src/Support/Clock.php new file mode 100644 index 0000000..c7c70f3 --- /dev/null +++ b/src/Support/Clock.php @@ -0,0 +1,20 @@ +travelTo()` and `Date::use()` reach + * every timestamp the package writes. The one place the package reads the clock. + */ +final readonly class Clock +{ + public function now(): CarbonImmutable + { + return CarbonImmutable::instance(Date::now()); + } +} diff --git a/src/Support/ConfigValues.php b/src/Support/ConfigValues.php deleted file mode 100644 index 2b82a93..0000000 --- a/src/Support/ConfigValues.php +++ /dev/null @@ -1,69 +0,0 @@ - - */ - public static function listOfStrings(mixed $value, string $path): array - { - if (! is_array($value)) { - throw new InvalidConfiguration($path . ': a list of strings is required.'); - } - - $strings = array_values(array_filter($value, is_string(...))); - - if (count($strings) !== count($value)) { - throw new InvalidConfiguration($path . ': a list of strings is required.'); - } - - return $strings; - } - - public function string(string $key, string $default): string - { - $value = $this->config->get($key, $default); - - return is_string($value) ? $value : $default; - } - - /** An integer, or a string of digits; anything else is the default. */ - public function integer(string $key, int $default): int - { - $value = $this->config->get($key, $default); - - return is_int($value) || (is_string($value) && ctype_digit($value)) ? (int) $value : $default; - } - - /** @return array the array at `$key`, or [] */ - public function array(string $key): array - { - $value = $this->config->get($key, []); - - return is_array($value) ? $value : []; - } - - /** @return list the strings of the array at `$key` (other entries dropped) */ - public function strings(string $key): array - { - return array_values(array_filter($this->array($key), is_string(...))); - } -} diff --git a/src/Support/LaravelValueEncrypter.php b/src/Support/LaravelValueEncrypter.php index 41169f3..7e3b408 100644 --- a/src/Support/LaravelValueEncrypter.php +++ b/src/Support/LaravelValueEncrypter.php @@ -8,7 +8,6 @@ use Illuminate\Encryption\MissingAppKeyException; use Illuminate\Contracts\Encryption\StringEncrypter; use Illuminate\Contracts\Encryption\DecryptException; -use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Exceptions\UndecryptableValue; use Simtabi\Laranail\Settings\Exceptions\EncryptionUnavailable; @@ -17,7 +16,7 @@ * without an APP_KEY yet (before install) still boots and reads its unencrypted settings. * Laravel's encrypter already tries APP_PREVIOUS_KEYS when decrypting. */ -final class LaravelValueEncrypter implements ValueEncrypter +final class LaravelValueEncrypter { private ?StringEncrypter $encrypter = null; diff --git a/src/Support/LaravelValueValidator.php b/src/Support/LaravelValueValidator.php index e2e94eb..34713ef 100644 --- a/src/Support/LaravelValueValidator.php +++ b/src/Support/LaravelValueValidator.php @@ -6,17 +6,21 @@ use Simtabi\Laranail\Settings\Data\Key; use Illuminate\Contracts\Validation\Factory; -use Simtabi\Laranail\Settings\Contracts\ValueValidator; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; /** * Validates a raw value against a definition's rules with Laravel's validator, before casting, * so rules such as `email` and `in:` see what the caller passed. */ -final readonly class LaravelValueValidator implements ValueValidator +final readonly class LaravelValueValidator { public function __construct(private Factory $validator) {} + /** + * @param list $rules + * + * @throws InvalidSettingValue naming the key and the failed rule, never the value + */ public function validate(Key $key, mixed $value, array $rules): void { if ($rules === []) { diff --git a/src/Support/RecordSerializer.php b/src/Support/RecordSerializer.php index 569c3d2..8e815e1 100644 --- a/src/Support/RecordSerializer.php +++ b/src/Support/RecordSerializer.php @@ -9,11 +9,13 @@ use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\Record; +use Illuminate\Container\Attributes\Singleton; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; /** * Converts records to and from the plain arrays file layers store. */ +#[Singleton] final readonly class RecordSerializer { /** @return array */ diff --git a/src/Support/ValueEncoder.php b/src/Support/ValueEncoder.php index 09533e1..ca05e34 100644 --- a/src/Support/ValueEncoder.php +++ b/src/Support/ValueEncoder.php @@ -6,12 +6,14 @@ use JsonException; use Simtabi\Laranail\Settings\Data\Key; +use Illuminate\Container\Attributes\Singleton; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; /** * Encodes values as JSON for storage. A stored null becomes the string `null`, which keeps it * distinct from "no value" (a null payload). */ +#[Singleton] final readonly class ValueEncoder { private const int FLAGS = JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; diff --git a/src/Testing/SettingsFake.php b/src/Testing/SettingsFake.php index 9dc729a..9d4027b 100644 --- a/src/Testing/SettingsFake.php +++ b/src/Testing/SettingsFake.php @@ -113,6 +113,26 @@ public function has(string $key): bool return $this->inner->has($key); } + public function missing(string $key): bool + { + return $this->inner->missing($key); + } + + public function many(array $keys): array + { + return $this->inner->many($keys); + } + + public function all(?string $prefix = null): array + { + return $this->inner->all($prefix); + } + + public function definitions(): array + { + return $this->inner->definitions(); + } + public function string(string $key): string { return $this->inner->string($key); @@ -155,6 +175,37 @@ public function forget(string $key): void $this->log->forgotten[] = $key; } + /** Each write goes through this fake's own set(), so assertSaved() sees every key. */ + public function setMany(array $values): void + { + foreach ($values as $key => $value) { + $this->set($key, $value); + } + } + + /** Each key goes through this fake's own forget(), so assertForgotten() sees every key. */ + public function forgetMany(iterable $keys): void + { + foreach ($keys as $key) { + $this->forget($key); + } + } + + /** The write, when one is made, goes through this fake's own set(), so assertSaved() sees it. */ + public function remember(string $key, callable $value): mixed + { + $lookup = $this->inner->lookup($key); + + if ($lookup->isFound()) { + return $lookup->value(); + } + + $computed = $value(); + $this->set($key, $computed); + + return $this->inner->get($key, $computed); + } + public function lock(string $key): void { $this->inner->lock($key); diff --git a/src/Verification/ActorTimestampVerifier.php b/src/Verification/ActorTimestampVerifier.php index 1503e12..23ecbaa 100644 --- a/src/Verification/ActorTimestampVerifier.php +++ b/src/Verification/ActorTimestampVerifier.php @@ -4,10 +4,11 @@ namespace Simtabi\Laranail\Settings\Verification; -use Closure; use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Actor; +use Illuminate\Container\Attributes\Config; use Simtabi\Laranail\Settings\Data\Subject; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Contracts\Verifier; /** @@ -16,10 +17,11 @@ */ final readonly class ActorTimestampVerifier implements Verifier { - /** @param Closure(): CarbonImmutable $clock */ + /** @param int $ttl `verification.ttl`: seconds a verification stays fresh */ public function __construct( + #[Config('laranail.settings.verification.ttl', 900)] private int $ttl, - private Closure $clock, + private Clock $clock, ) {} /** Whether a verification at `$at` is still fresh at `$now`; a timestamp in the future is not. */ @@ -34,6 +36,6 @@ public static function fresh(?CarbonImmutable $at, CarbonImmutable $now, int $tt public function isVerified(Actor $actor, Subject $subject): bool { - return self::fresh($actor->verifiedAt, ($this->clock)(), $this->ttl); + return self::fresh($actor->verifiedAt, $this->clock->now(), $this->ttl); } } diff --git a/src/Verification/PasswordConfirmationVerifier.php b/src/Verification/PasswordConfirmationVerifier.php index 1a1c4e6..3736c7b 100644 --- a/src/Verification/PasswordConfirmationVerifier.php +++ b/src/Verification/PasswordConfirmationVerifier.php @@ -9,6 +9,7 @@ use Illuminate\Contracts\Session\Session; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Contracts\Verifier; /** @@ -22,18 +23,18 @@ public const string SESSION_KEY = 'auth.password_confirmed_at'; /** - * @param Closure(): ?Session $session the current session, or null outside HTTP - * @param Closure(): CarbonImmutable $clock + * @param Closure(): ?Session $session the current session, or null outside HTTP; a closure + * because the request changes under this scoped service */ public function __construct( private Closure $session, private int $timeout, - private Closure $clock, + private Clock $clock, ) {} public function isVerified(Actor $actor, Subject $subject): bool { - $now = ($this->clock)(); + $now = $this->clock->now(); $confirmedAt = ($this->session)()?->get(self::SESSION_KEY); if (is_int($confirmedAt) || (is_string($confirmedAt) && ctype_digit($confirmedAt))) { diff --git a/src/deprecated-aliases.php b/src/deprecated-aliases.php deleted file mode 100644 index ac3a6ad..0000000 --- a/src/deprecated-aliases.php +++ /dev/null @@ -1,63 +0,0 @@ - AuditRepository::class, - Simtabi\Laranail\Settings\Database\CategoryRepository::class => CategoryRepository::class, - Simtabi\Laranail\Settings\Database\DefinitionsRepository::class => DefinitionsRepository::class, - Simtabi\Laranail\Settings\Database\SchemaInspector::class => SchemaInspector::class, - Simtabi\Laranail\Settings\Database\SchemaShapeRepository::class => SchemaShapeRepository::class, - Simtabi\Laranail\Settings\Stores\SettingWriter::class => SettingWriter::class, - Simtabi\Laranail\Settings\Stores\StoreRegistry::class => StoreRegistry::class, - Simtabi\Laranail\Settings\Resolution\Resolver::class => Resolver::class, - Simtabi\Laranail\Settings\Resolution\PreloadedRecords::class => PreloadedRecords::class, - Simtabi\Laranail\Settings\Authorization\AccessGuard::class => AccessGuard::class, - Simtabi\Laranail\Settings\Audit\Auditor::class => Auditor::class, - Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration::class => RuntimeConfiguration::class, - Simtabi\Laranail\Settings\Definitions\DefinitionRegistry::class => DefinitionRegistry::class, - Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions::class => DatabaseDefinitions::class, - Simtabi\Laranail\Settings\Tenancy\TenantDiscriminators::class => TenantDiscriminators::class, - Simtabi\Laranail\Settings\Casting\CasterRegistry::class => CasterRegistry::class, - Simtabi\Laranail\Settings\Support\ValuePipeline::class => ValuePipeline::class, - Simtabi\Laranail\Settings\Drivers\DriverFactory::class => DriverFactory::class, - Simtabi\Laranail\Settings\Caching\SettingsCache::class => SettingsCache::class, -] as $deprecated => $moved) { - if (! class_exists($deprecated, false)) { - class_alias($moved, $deprecated); - } -} diff --git a/tests/Arch/ArchitectureTest.php b/tests/Arch/ArchitectureTest.php index 879b616..4aaf4a4 100644 --- a/tests/Arch/ArchitectureTest.php +++ b/tests/Arch/ArchitectureTest.php @@ -46,8 +46,10 @@ ->not->toBeUsed(); /* - * Headless (design §16.1, D-16): no views, Blade, Livewire, Filament or published assets. An - * admin interface is a separate companion package, so nothing here may render a page. + * Headless (design §16.1, D-16): no Blade components, Livewire, Filament or published assets. An + * admin interface is a separate companion package, so nothing here may render a page. The one + * view is the alert mail's markdown body (resources/views/mail/alert.blade.php), which the + * notification names by string and the mailer renders. */ arch('the package is headless: no view, Blade, Livewire or Filament reference') ->expect('Simtabi\Laranail\Settings') @@ -60,7 +62,7 @@ 'view', ]); -it('ships no views directory and registers no views or assets', function (): void { +it('ships only the alert mail view and no assets, components or composers', function (): void { $root = dirname(__DIR__, 2); $sources = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root . '/src', FilesystemIterator::SKIP_DOTS)); $inspected = 0; @@ -73,15 +75,31 @@ $inspected++; - if (preg_match('/->\s*(hasViews|hasAssets|hasViewComponents?|hasViewComposer|sharesDataWithAllViews)\s*\(/', (string) file_get_contents($file->getPathname())) === 1) { + if (preg_match('/->\s*(hasAssets|hasViewComponents?|hasViewComposer|sharesDataWithAllViews)\s*\(/', (string) file_get_contents($file->getPathname())) === 1) { $offending[] = $file->getPathname(); } } + // Files under a directory, relative, sorted; macOS's .DS_Store is the OS's, not the package's. + $files = static function (string $directory): array { + $found = []; + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS)) as $file) { + if ($file instanceof SplFileInfo && $file->getFilename() !== '.DS_Store') { + $found[] = substr($file->getPathname(), strlen($directory) + 1); + } + } + + sort($found); + + return $found; + }; + // A scan that inspects nothing has broken, not found a clean tree. - expect($inspected)->toBeGreaterThanOrEqual(360) + expect($inspected)->toBeGreaterThanOrEqual(355) ->and($offending)->toBe([]) - ->and(is_dir($root . '/resources/views'))->toBeFalse(); + ->and($files($root . '/resources/views'))->toBe(['mail/alert.blade.php']) + ->and($files($root . '/resources/assets'))->toBe(['.gitkeep']); }); /* diff --git a/tests/Arch/LayeringTest.php b/tests/Arch/LayeringTest.php index 384197b..66bd23d 100644 --- a/tests/Arch/LayeringTest.php +++ b/tests/Arch/LayeringTest.php @@ -41,17 +41,9 @@ function classOf(string $path): string /** Actions with more than handle() public, and why. */ const ACTION_EXEMPTIONS = [ - 'Actions\\WriteGuard' => 'run(): the guard every write action runs through; not an intent of its own', - 'Actions\\Categories\\CategoryGuard' => 'run(): the guard every category action runs through', - 'Actions\\SettingActions' => 'a bundle of the write actions for entry points (using())', - 'Actions\\StoreActions' => 'a bundle of the store actions for entry points', - 'Actions\\HistoryActions' => 'a bundle of the history actions for entry points', - 'Actions\\Approvals\\ApprovalActions' => 'a bundle of the approval actions for entry points', - 'Actions\\Transfer\\TransferActions' => 'a bundle of the export, import and diff actions for entry points', - 'Actions\\Configuration\\ConfigurationActions' => 'a bundle of the persisted configuration actions for entry points', - 'Actions\\Categories\\CategoryActions' => 'a bundle of the category actions for entry points (using())', - 'Actions\\QueryAudit' => 'get(), cursor(), paginate(): one authorized read in three result shapes, part of the public API', - 'Actions\\PruneOrphans' => 'find(): deprecated in 0.1, forwards to FindOrphans, removed in 1.0', + 'Actions\\WriteGuard' => 'run(): the guard every write action runs through; not an intent of its own', + 'Actions\\Categories\\CategoryGuard' => 'run(): the guard every category action runs through', + 'Actions\\QueryAudit' => 'get(), cursor(), paginate(): one authorized read in three result shapes, part of the public API', ]; it('gives every action handle() as its only public method', function (): void { @@ -71,7 +63,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(55) + expect(count($files))->toBeGreaterThanOrEqual(50) ->and(array_keys(array_diff_key($offenders, ACTION_EXEMPTIONS)))->toBe([]) // An exemption that no longer needs to be one is stale. ->and(array_keys(array_diff_key(ACTION_EXEMPTIONS, $offenders)))->toBe([]); @@ -81,12 +73,12 @@ function classOf(string $path): string $files = sourceFiles('Actions'); $offenders = array_keys(array_filter($files, static fn (string $code): bool => preg_match('/->connection\(\)|getSchemaBuilder\(|DB::/', $code) === 1)); - expect(count($files))->toBeGreaterThanOrEqual(55) + expect(count($files))->toBeGreaterThanOrEqual(50) ->and($offenders)->toBe([]); }); it('lets only entry points depend on actions', function (): void { - $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php', 'History/HistoryQuery.php', 'Approvals/Approvals.php', 'Configuration/PersistedConfigurationEditor.php', 'Http/', 'Enums/Capability.php', 'Typed/SettingsMigrator.php']; + $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php', 'History/HistoryQuery.php', 'Approvals/Approvals.php', 'Configuration/PersistedConfigurationEditor.php', 'Http/', 'Typed/SettingsMigrator.php']; $files = sourceFiles(''); $offenders = []; @@ -100,7 +92,7 @@ function classOf(string $path): string } } - expect(count($files))->toBeGreaterThanOrEqual(360) + expect(count($files))->toBeGreaterThanOrEqual(355) ->and($offenders)->toBe([]); }); diff --git a/tests/Arch/RestApiTest.php b/tests/Arch/RestApiTest.php deleted file mode 100644 index 5ff33f7..0000000 --- a/tests/Arch/RestApiTest.php +++ /dev/null @@ -1,89 +0,0 @@ - "Controller::method" => method, for every public controller method */ -function controllerMethods(): array -{ - $methods = []; - - foreach (glob(dirname(__DIR__, 2) . '/src/Http/Controllers/*.php') ?: [] as $file) { - $class = new ReflectionClass('Simtabi\\Laranail\\Settings\\Http\\Controllers\\' . basename($file, '.php')); - - foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { - if ($method->getName() !== '__construct' && $method->getDeclaringClass()->getName() === $class->getName()) { - $methods[$class->getShortName() . '::' . $method->getName()] = $method; - } - } - } - - return $methods; -} - -/** @return list the Actions\* classes a controller method calls through its constructor properties */ -function delegatedActions(ReflectionMethod $method): array -{ - $lines = file((string) $method->getFileName()) ?: []; - $body = implode('', array_slice($lines, (int) $method->getStartLine() - 1, (int) $method->getEndLine() - (int) $method->getStartLine() + 1)); - $actions = []; - - foreach ($method->getDeclaringClass()->getConstructor()?->getParameters() ?? [] as $parameter) { - $type = $parameter->getType(); - $class = $type instanceof ReflectionNamedType ? $type->getName() : ''; - - if (str_starts_with($class, 'Simtabi\\Laranail\\Settings\\Actions\\') && preg_match('/\$this->' . $parameter->getName() . '->(handle|paginate|get|cursor)\(/', $body) === 1) { - $actions[] = $class; - } - } - - return $actions; -} - -it('makes every controller method delegate to an action', function (): void { - $methods = controllerMethods(); - $idle = array_keys(array_filter($methods, static fn (ReflectionMethod $method): bool => delegatedActions($method) === [])); - - expect(count($methods))->toBeGreaterThanOrEqual(30) - ->and($idle)->toBe([]); -}); - -it('holds the routes, the capabilities and the controllers to each other', function (): void { - $routes = ApiRoutes::definitions(); - $methods = controllerMethods(); - $routed = array_values(array_unique(array_map(static fn (array $route): string => $route['capability']->value, $routes))); - $mismatched = []; - - foreach ($routes as $route) { - $method = $methods[new ReflectionClass($route['controller'])->getShortName() . '::' . $route['action']] ?? null; - - if (! $method instanceof ReflectionMethod || array_intersect($route['capability']->actions(), delegatedActions($method)) === []) { - $mismatched[] = $route['name']; - } - } - - sort($routed); - $cases = array_map(static fn (Capability $capability): string => $capability->value, Capability::cases()); - sort($cases); - - expect(count($routes))->toBeGreaterThanOrEqual(39) - ->and($routed)->toBe($cases) - ->and($mismatched)->toBe([]) - // Every controller method is routed: nothing reachable only by accident. - ->and(array_diff(array_keys($methods), array_map(static fn (array $route): string => new ReflectionClass($route['controller'])->getShortName() . '::' . $route['action'], $routes)))->toBe([]); -}); - -it('names every route with the vendor-scoped prefix and a capability', function (): void { - foreach (ApiRoutes::definitions() as $route) { - expect($route['name'])->toStartWith('laranail-settings.api.') - ->and(Capability::tryFrom((string) preg_replace('/^laranail-settings\.api\.(owners\.)?/', '', $route['name'])))->toBe($route['capability']); - } -}); diff --git a/tests/Arch/ServicesTest.php b/tests/Arch/ServicesTest.php index e03c939..1716aaf 100644 --- a/tests/Arch/ServicesTest.php +++ b/tests/Arch/ServicesTest.php @@ -1,44 +1,30 @@ new name. */ +/** The 19 classes moved into Services\ in 0.1, whose old names were removed: old name => new name. */ const MOVED_SERVICES = [ 'Database\\AuditRepository' => 'Services\\Database\\AuditRepository', 'Database\\CategoryRepository' => 'Services\\Database\\CategoryRepository', @@ -110,49 +96,17 @@ function servicesSources(): array )); // The positive control: the scan does find the repositories and registries that exist. - expect(count($files))->toBeGreaterThanOrEqual(360) + expect(count($files))->toBeGreaterThanOrEqual(355) ->and(count($found))->toBeGreaterThanOrEqual(9) ->and($offenders)->toBe([]); }); -it('aliases exactly the moved classes, and each old name still works', function (): void { - $file = (string) file_get_contents(dirname(__DIR__, 2) . '/src/deprecated-aliases.php'); - preg_match_all('/^\s*(?:\\\\)?Simtabi\\\\Laranail\\\\Settings\\\\([A-Za-z\\\\]+)::class\s*=>/m', $file, $matches); - $aliased = $matches[1]; +it('leaves no old name for a moved class, and every new name loads', function (): void { $base = 'Simtabi\\Laranail\\Settings\\'; - $broken = []; - - foreach (MOVED_SERVICES as $old => $new) { - $reflection = new ReflectionClass($base . $old); - - if ($reflection->getName() !== $base . $new || ! is_a($base . $new, $base . $old, true)) { - $broken[] = $old; - } - } + $root = dirname(__DIR__, 2); expect(count(MOVED_SERVICES))->toBe(19) - ->and($aliased)->toHaveCount(19) - ->and(array_values(array_diff($aliased, array_keys(MOVED_SERVICES))))->toBe([]) - ->and(array_values(array_diff(array_keys(MOVED_SERVICES), $aliased)))->toBe([]) - ->and($broken)->toBe([]) - // No old file is left behind to shadow the alias. - ->and(array_filter(array_keys(MOVED_SERVICES), static fn (string $old): bool => is_file(dirname(__DIR__, 2) . '/src/' . str_replace('\\', '/', $old) . '.php')))->toBe([]); -}); - -it('keeps an old name working in a type declaration', function (): void { - $accepts = static fn (StoreRegistry $registry): string => $registry::class; - $registry = new Simtabi\Laranail\Settings\Services\Stores\StoreRegistry( - new DriverFactory( - Mockery::mock(Factory::class), - Mockery::mock(Repository::class), - new ReadOnlyValues(new ValueEncoder), - new RecordSerializer, - sys_get_temp_dir(), - ), - 'settings', - ['settings' => ['layers' => []]], - [], - ); - - expect($accepts($registry))->toBe(Simtabi\Laranail\Settings\Services\Stores\StoreRegistry::class); + ->and(is_file($root . '/src/deprecated-aliases.php'))->toBeFalse() + ->and(array_keys(array_filter(MOVED_SERVICES, static fn (string $new, string $old): bool => class_exists($base . $old), ARRAY_FILTER_USE_BOTH)))->toBe([]) + ->and(array_values(array_filter(MOVED_SERVICES, static fn (string $new): bool => ! class_exists($base . $new))))->toBe([]); }); diff --git a/tests/Feature/AlertsTest.php b/tests/Feature/AlertsTest.php index 0463f04..b5a62f7 100644 --- a/tests/Feature/AlertsTest.php +++ b/tests/Feature/AlertsTest.php @@ -2,15 +2,16 @@ declare(strict_types=1); -use Carbon\CarbonImmutable; use Psr\Log\AbstractLogger; use Illuminate\Support\Stringable; use Illuminate\Contracts\Cache\Repository; use Simtabi\Laranail\Settings\Data\Subject; use Illuminate\Support\Facades\Notification; use Simtabi\Laranail\Settings\Enums\Ability; +use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Data\AlertRule; use Simtabi\Laranail\Settings\Data\StoreName; +use Illuminate\Contracts\Translation\Translator; use Simtabi\Laranail\Settings\Data\AlertContext; use Illuminate\Notifications\AnonymousNotifiable; use Simtabi\Laranail\Settings\Events\AuditPruned; @@ -24,6 +25,7 @@ use Simtabi\Laranail\Settings\Notifications\SettingsAlert; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Providers\SettingsServiceProvider; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; @@ -103,7 +105,7 @@ function sentAlerts(): array $cache = Mockery::mock(Repository::class); $cache->shouldReceive('add')->andThrow(new RuntimeException('cache down')); $logger = alertLogger(); - $listener = new SendSettingsAlert(app(Dispatcher::class), [AlertRule::fromConfig(['events' => ['SettingSaved'], 'notify' => ['mail' => ['ops@example.test']]], 0)], static fn (): bool => false, static fn (): CarbonImmutable => now()->toImmutable(), $logger, $cache, 60); + $listener = new SendSettingsAlert(app(Dispatcher::class), [AlertRule::fromConfig(['events' => ['SettingSaved'], 'notify' => ['mail' => ['ops@example.test']]], 0)], app(Definitions::class), new Clock, $logger, app(Translator::class), $cache, 60); $listener->handle(new SettingSaved('settings', 'global', 'site.name', '', 1)); diff --git a/tests/Feature/ConvenienceApiTest.php b/tests/Feature/ConvenienceApiTest.php new file mode 100644 index 0000000..961eae8 --- /dev/null +++ b/tests/Feature/ConvenienceApiTest.php @@ -0,0 +1,146 @@ +missing('site.name'))->toBeTrue(); + + settings()->set('site.name', 'Acme'); + + expect(settings()->missing('site.name'))->toBeFalse(); +}); + +it('reads many keys at once, with per-key defaults', function (): void { + settings()->set('site.name', 'Acme'); + + expect(settings()->many(['site.name', 'site.tagline' => 'Welcome', 'site.logo']))->toBe([ + 'site.name' => 'Acme', + 'site.tagline' => 'Welcome', + 'site.logo' => null, + ]); +}); + +it('refuses a list entry that is not a key', function (): void { + settings()->many([42]); +})->throws(InvalidKey::class); + +it('writes and forgets many keys, in order', function (): void { + settings()->setMany(['site.name' => 'Acme', 'site.tagline' => 'Hi']); + + expect(settings()->get('site.name'))->toBe('Acme') + ->and(settings()->get('site.tagline'))->toBe('Hi'); + + settings()->forgetMany(['site.name', 'site.tagline']); + + expect(settings()->has('site.name'))->toBeFalse() + ->and(settings()->has('site.tagline'))->toBeFalse(); +}); + +it('remembers a computed value: written once, read back afterwards', function (): void { + $calls = 0; + $compute = static function () use (&$calls): string { + $calls++; + + return 'generated'; + }; + + expect(settings()->remember('install.id', $compute))->toBe('generated') + ->and(settings()->remember('install.id', $compute))->toBe('generated') + ->and($calls)->toBe(1) + ->and(settings()->get('install.id'))->toBe('generated'); +}); + +it('lists every visible value in key order, filtered by prefix', function (): void { + app(DefinitionRegistry::class)->define('site.locale')->withDefault('en')->register(); + settings()->setMany(['site.name' => 'Acme', 'mail.from' => 'a@acme.test', 'sitemap.enabled' => true]); + + expect(settings()->all())->toBe([ + 'mail.from' => 'a@acme.test', + 'site.locale' => 'en', + 'site.name' => 'Acme', + 'sitemap.enabled' => true, + ])->and(settings()->all('site'))->toBe(['site.locale' => 'en', 'site.name' => 'Acme']) + ->and(settings()->all('site.'))->toBe(['site.locale' => 'en', 'site.name' => 'Acme']) + ->and(settings()->all('site.name'))->toBe(['site.name' => 'Acme']); +}); + +it('lists an owner\'s own values', function (): void { + config()->set('laranail.settings.stores.settings.owners', ['user']); + settings()->set('site.name', 'Acme'); + settings()->for(new OwnerRef('user', 1))->set('ui.theme', 'dark'); + + expect(settings()->for(new OwnerRef('user', 1))->all())->toBe(['ui.theme' => 'dark']); +}); + +it('leaves out of a listing the keys an actor may not view, and sensitive values it may not read', function (): void { + app(DefinitionRegistry::class)->define('mail.api_key')->sensitive()->register(); + settings()->setMany(['site.name' => 'Acme', 'billing.plan' => 'pro', 'mail.api_key' => TestCredentials::secret()]); + Gate::define('laranail-settings.view', static fn (TestUser $user, mixed $subject): bool => ! str_starts_with((string) $subject->key?->value, 'billing.')); + Gate::define('laranail-settings.view_sensitive', static fn (TestUser $user): bool => false); + + expect(settings()->as(user())->all())->toBe(['site.name' => 'Acme']); +}); + +it('lists the store\'s definitions for a UI, gated by view', function (): void { + app(DefinitionRegistry::class)->define('site.name')->withDefault('Acme')->register(); + app(DefinitionRegistry::class)->define('mail.from')->register(); + allowGates(Ability::View); + + expect(array_map(static fn (Definition $definition): string => $definition->key->value, settings()->as(user())->definitions())) + ->toBe(['mail.from', 'site.name']); + + Gate::define('laranail-settings.view', static fn (TestUser $user): bool => false); + + expect(fn (): array => settings()->as(user())->definitions())->toThrow(AccessDenied::class); +}); + +it('lists definitions from a manager the container builds', function (): void { + app(DefinitionRegistry::class)->define('site.name')->register(); + + expect(array_map(static fn (Definition $definition): string => $definition->key->value, app(SettingsManager::class)->definitions()))->toBe(['site.name']); +}); + +it('records many writes, forgets and remembered values in the fake', function (): void { + app(DefinitionRegistry::class)->define('site.locale')->withDefault('en')->register(); + $fake = Settings::fake(); + + Settings::setMany(['site.name' => 'Acme', 'site.tagline' => 'Hi']); + Settings::forgetMany(['site.tagline']); + Settings::remember('install.id', static fn (): string => 'generated'); + Settings::remember('install.id', static fn (): string => 'other'); + + $fake->assertSaved('site.name', 'Acme'); + $fake->assertForgotten('site.tagline'); + $fake->assertSaved('install.id', 'generated'); + + expect(Settings::missing('site.tagline'))->toBeTrue() + ->and(Settings::many(['site.name']))->toBe(['site.name' => 'Acme']) + ->and(Settings::all())->toBe(['install.id' => 'generated', 'site.locale' => 'en', 'site.name' => 'Acme']) + ->and(Settings::definitions())->toHaveCount(1); +}); + +it('offers a namespaced settings() helper over the contract', function (): void { + settingsHelper()->set('site.name', 'Acme'); + + expect(settingsHelper())->toBeInstanceOf(SettingsContract::class) + ->and(settingsHelper('site.name'))->toBe('Acme') + ->and(settingsHelper('site.tagline', 'Welcome'))->toBe('Welcome') + ->and(function_exists('settings'))->toBeTrue() // the test suite's own global helper, untouched + ->and(function_exists('Simtabi\Laranail\Settings\settings'))->toBeTrue(); +}); diff --git a/tests/Feature/Database/MaintenanceTest.php b/tests/Feature/Database/MaintenanceTest.php index d73c8e2..1216d20 100644 --- a/tests/Feature/Database/MaintenanceTest.php +++ b/tests/Feature/Database/MaintenanceTest.php @@ -9,11 +9,11 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Actions\RescopeOwners; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; -use Simtabi\Laranail\Settings\Contracts\ValueEncrypter; use Simtabi\Laranail\Settings\Actions\ReencryptSettings; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; +use Simtabi\Laranail\Settings\Support\LaravelValueEncrypter; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* @@ -34,7 +34,7 @@ function rotateKey(bool $keepPrevious): void config()->set('app.key', 'base64:' . base64_encode(random_bytes(32))); config()->set('app.previous_keys', $keepPrevious ? [$old] : []); - foreach (['encrypter', ValueEncrypter::class, ValuePipeline::class] as $abstract) { + foreach (['encrypter', LaravelValueEncrypter::class, ValuePipeline::class] as $abstract) { app()->forgetInstance($abstract); } @@ -62,7 +62,7 @@ function rotateKey(bool $keepPrevious): void // The old key can go now: everything reads under the new one alone. config()->set('app.previous_keys', []); app()->forgetInstance('encrypter'); - app()->forgetInstance(ValueEncrypter::class); + app()->forgetInstance(LaravelValueEncrypter::class); app()->forgetInstance(ValuePipeline::class); app()->forgetScopedInstances(); app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); diff --git a/tests/Feature/Database/MigrationTest.php b/tests/Feature/Database/MigrationTest.php index b3f3acb..fa7d619 100644 --- a/tests/Feature/Database/MigrationTest.php +++ b/tests/Feature/Database/MigrationTest.php @@ -7,9 +7,9 @@ use Illuminate\Database\Migrations\Migration; use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; +use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; /* * The package's one migration: every table, in dependency order, for every recorded database @@ -101,7 +101,7 @@ function packageMigration(): Migration new SchemaNames, null, true, - static fn (): ReadinessProbe => app(ReadinessProbe::class), + static fn (): SchemaReadinessInterface => app(SchemaReadinessInterface::class), )); $live = new SchemaInspector(app(StoreRegistry::class)->default()->requireDatabase('')); diff --git a/tests/Feature/Database/OwnersTest.php b/tests/Feature/Database/OwnersTest.php index 17f74a2..18ae21e 100644 --- a/tests/Feature/Database/OwnersTest.php +++ b/tests/Feature/Database/OwnersTest.php @@ -149,7 +149,7 @@ Event::assertDispatched(OrphansPruned::class, static fn (OrphansPruned $event): bool => $event->owners === 1 && $event->rows === 1); }); -it('finds orphans with FindOrphans, and through the deprecated PruneOrphans::find()', function (): void { +it('finds orphans with FindOrphans', function (): void { $gone = SettingsOwner::query()->create(); $gone->settings()->set('ui.theme', 'dark'); SettingsOwner::query()->whereKey($gone->id)->delete(); @@ -157,7 +157,6 @@ $found = app(FindOrphans::class)->handle(); expect(array_map(static fn (OwnerRef $owner): string => $owner->scope()->value, $found['orphans']['settings'] ?? []))->toBe(['owner:' . $gone->id]) - ->and(app(PruneOrphans::class)->find())->toEqual($found) ->and(DB::table('settings')->count())->toBe(1); }); diff --git a/tests/Feature/Database/RestApiTest.php b/tests/Feature/Database/RestApiTest.php index d752c45..17b7ff1 100644 --- a/tests/Feature/Database/RestApiTest.php +++ b/tests/Feature/Database/RestApiTest.php @@ -7,23 +7,22 @@ use Illuminate\Support\Facades\Gate; use Illuminate\Testing\TestResponse; use Illuminate\Support\Facades\Schema; -use Illuminate\Support\Facades\Artisan; use Illuminate\Database\Schema\Blueprint; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\NewCategory; use Illuminate\Database\Eloquent\Relations\Relation; use Simtabi\Laranail\Settings\Tests\Fixtures\TestUser; +use Simtabi\Laranail\Settings\Tests\Support\ApiSchemas; use Simtabi\Laranail\Settings\Tests\Support\JsonSchema; use Simtabi\Laranail\Package\Tools\Testing\TestCredentials; -use Simtabi\Laranail\Settings\Http\OpenApi\OpenApiDocument; use Simtabi\Laranail\Settings\Tests\Fixtures\SettingsOwner; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* * §16.10: the REST API runs the actions the PHP API runs, answers problem details, ETags and * If-Match, 202 for approvals, cursor pages, idempotent retries, and every response it gives - * conforms to the OpenAPI document it generates. + * matches its shape (tests/Support/ApiSchemas.php). */ beforeEach(function (): void { @@ -37,20 +36,18 @@ $this->actingAs(user(1)); }); -/** Call the API and check the response against the OpenAPI document. */ +/** Call the API and check the response against its shape. */ function api(string $method, string $uri, array $data = [], array $headers = []): TestResponse { $response = test()->json($method, '/api/settings/v1/' . $uri, $data, $headers); $route = $response->baseRequest->route(); if (is_object($route) && $response->status() !== 204) { - $document = OpenApiDocument::build(app(Router::class)->getRoutes()->getRoutes()); - $operation = $document['paths']['/' . $route->uri()][strtolower($method)] ?? null; - $schema = $operation['responses'][(string) $response->status()]['content'] ?? null; + $schema = ApiSchemas::response((string) $route->getName(), $response->status()); - expect($schema)->not->toBeNull(sprintf('%s %s answered %d, which the document does not describe', $method, $uri, $response->status())); + expect($schema)->not->toBeNull(sprintf('%s %s answered %d, which no response shape describes', $method, $uri, $response->status())); - $errors = new JsonSchema($document)->errors(json_decode((string) $response->getContent(), true), array_values($schema)[0]['schema']); + $errors = new JsonSchema(ApiSchemas::document())->errors(json_decode((string) $response->getContent(), true), $schema); expect($errors)->toBe([], sprintf('%s %s does not match its schema', $method, $uri)); } @@ -60,8 +57,7 @@ function api(string $method, string $uri, array $data = [], array $headers = []) it('registers no route unless the API is enabled', function (): void { $this->rebootWith([]); - expect(collect(app(Router::class)->getRoutes()->getRoutes())->filter(fn ($route): bool => str_starts_with((string) $route->getName(), 'laranail-settings.api.')))->toHaveCount(0) - ->and(Artisan::call('laranail::settings.openapi'))->toBe(1); + expect(collect(app(Router::class)->getRoutes()->getRoutes())->filter(fn ($route): bool => str_starts_with((string) $route->getName(), 'laranail-settings.api.')))->toHaveCount(0); }); it('reads and writes a setting with ETags and If-Match', function (): void { @@ -204,19 +200,17 @@ function api(string $method, string $uri, array $data = [], array $headers = []) test()->json('GET', '/api/settings/v1/stores')->assertUnauthorized()->assertJsonPath('type', 'https://opensource.simtabi.com/documentation/laranail/settings/problems/actor-required'); }); -it('generates an OpenAPI 3.1 document of every registered route', function (): void { - $path = sys_get_temp_dir() . '/laranail-settings-openapi-' . bin2hex(random_bytes(4)) . '.json'; - - expect(Artisan::call('laranail::settings.openapi', ['--output' => $path]))->toBe(0); - - $document = json_decode((string) file_get_contents($path), true); - $operations = collect($document['paths'])->flatMap(static fn (array $methods): array => array_column($methods, 'operationId')); - - expect($document['openapi'])->toBe('3.1.0') - ->and($operations)->toHaveCount(39) - ->and($operations->unique())->toHaveCount(39) - ->and(Artisan::call('laranail::settings.openapi'))->toBe(0) - ->and(Artisan::output())->toContain('"openapi": "3.1.0"'); +it('has a response shape for every registered route, and none for a route that is gone', function (): void { + $names = collect(app(Router::class)->getRoutes()->getRoutes()) + ->map(static fn ($route): string => (string) $route->getName()) + ->filter(static fn (string $name): bool => str_starts_with($name, 'laranail-settings.api.')) + ->map(static fn (string $name): string => (string) preg_replace('/^laranail-settings\.api\.(owners\.)?/', '', $name)) + ->unique()->sort()->values()->all(); + $shapes = ApiSchemas::routes(); + sort($shapes); + + expect($names)->toHaveCount(30) + ->and($shapes)->toBe($names); }); it('loads a Settable owner, so its parents take part in reads, and refuses one that does not exist', function (): void { diff --git a/tests/Feature/Database/TypedSettingsTest.php b/tests/Feature/Database/TypedSettingsTest.php index 99f3fb6..1ad565d 100644 --- a/tests/Feature/Database/TypedSettingsTest.php +++ b/tests/Feature/Database/TypedSettingsTest.php @@ -154,11 +154,18 @@ public function up(): void ->and(settings()->history()->global()->key('mail.from_address')->get())->toHaveCount(1); }); -it('resolves a typed settings class from the container, loaded', function (): void { +it('resolves a class listed in typed.classes from the container, loaded', function (): void { + $this->rebootWith(['laranail.settings.typed.classes' => [MailSettings::class]]); + useDatabase(['stores.settings.owners' => ['user'], 'typed.classes' => [MailSettings::class]]); settings()->set('mail.port', 465); expect(app(MailSettings::class)->port)->toBe(465) - ->and(app(MailSettings::class))->toBeInstanceOf(TypedSettings::class); + ->and(app(MailSettings::class))->toBeInstanceOf(TypedSettings::class) + ->and(app()->bound(MailSettings::class))->toBeTrue(); +}); + +it('binds only the classes typed.classes lists when the application boots', function (): void { + expect(app()->bound(MailSettings::class))->toBeFalse(); }); it('refuses a typed.classes entry that is not a typed settings class', function (): void { diff --git a/tests/Feature/Database/WriteRetryTest.php b/tests/Feature/Database/WriteRetryTest.php index 66eaefa..8191537 100644 --- a/tests/Feature/Database/WriteRetryTest.php +++ b/tests/Feature/Database/WriteRetryTest.php @@ -8,8 +8,8 @@ use Simtabi\Laranail\Settings\Data\Locale; use Illuminate\Database\Events\QueryExecuted; use Simtabi\Laranail\Settings\Data\SettingWrite; +use Simtabi\Laranail\Settings\Actions\SetSetting; use Simtabi\Laranail\Settings\Data\SettingTarget; -use Simtabi\Laranail\Settings\Actions\SettingActions; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Exceptions\ConcurrentModification; @@ -93,7 +93,7 @@ public function log($level, string|Stringable $message, array $context = []): vo }); it('checks an explicit expected version and never retries it', function (): void { - $set = app(SettingActions::class)->set; + $set = app(SetSetting::class); expect(fn () => $set->handle(new SettingWrite(target(), 'Stale', expectedVersion: 7)))->toThrow(ConcurrentModification::class, 'not the expected 7'); diff --git a/tests/Feature/PackageLayoutTest.php b/tests/Feature/PackageLayoutTest.php new file mode 100644 index 0000000..6759b3f --- /dev/null +++ b/tests/Feature/PackageLayoutTest.php @@ -0,0 +1,175 @@ +> the `laranail-settings.*` rows `route:list --json` prints */ +function listedSettingsRoutes(): array +{ + Artisan::call('route:list', ['--name' => 'laranail-settings', '--json' => true]); + $rows = json_decode(trim(Artisan::output()), true); + + return is_array($rows) ? array_values($rows) : []; +} + +it('lists the 39 API routes from routes/api.php when the API is enabled', function (): void { + $this->rebootWith(['laranail.settings.http.enabled' => true, 'laranail.settings.http.middleware' => ['api', 'auth']]); + + $listed = listedSettingsRoutes(); + $names = array_column($listed, 'name'); + sort($names); + $settings = ['index', 'show', 'explain', 'update', 'destroy', 'lock', 'unlock', 'history', 'rollback']; + $expected = [ + 'audit.index', 'categories.destroy', 'categories.index', 'categories.store', 'categories.update', + 'changes.approve', 'changes.cancel', 'changes.index', 'changes.reject', 'changes.show', 'changes.store', + 'configuration.destroy', 'configuration.index', 'configuration.update', + 'definitions.destroy', 'definitions.index', 'definitions.update', 'stores.index', + 'transfer.diff', 'transfer.export', 'transfer.import', + ...array_map(static fn (string $action): string => 'settings.' . $action, $settings), + ...array_map(static fn (string $action): string => 'owners.settings.' . $action, $settings), + ]; + $expected = array_map(static fn (string $name): string => 'laranail-settings.api.' . $name, $expected); + sort($expected); + + expect($listed)->toHaveCount(39) + ->and($names)->toBe($expected) + ->and(array_unique(array_map(static fn (array $row): string => explode('/v1/', (string) $row['uri'])[0], $listed)))->toBe(['api/settings']) + ->and(app(Router::class)->getRoutes()->getByName('laranail-settings.api.stores.index')?->middleware())->toContain('api', 'auth', 'throttle:laranail-settings'); +}); + +it('moves every route under http.prefix, and mounts them at /v1 when it is empty', function (string $prefix, string $base): void { + $this->rebootWith(['laranail.settings.http.enabled' => true, 'laranail.settings.http.middleware' => ['api', 'auth'], 'laranail.settings.http.prefix' => $prefix]); + + $uris = array_map(static fn (array $row): string => (string) $row['uri'], listedSettingsRoutes()); + + expect($uris)->toHaveCount(39) + ->and(array_filter($uris, static fn (string $uri): bool => ! str_starts_with($uri, $base . '/')))->toBe([]) + ->and(route('laranail-settings.api.settings.show', ['store' => 'settings', 'key' => 'site.name']))->toBe(url($base . '/stores/settings/settings/site.name')) + ->and(route('laranail-settings.api.owners.settings.show', ['store' => 'settings', 'alias' => 'user', 'id' => 1, 'key' => 'theme']))->toBe(url($base . '/stores/settings/owners/user/1/settings/theme')); +})->with([ + 'the default' => ['api/settings', 'api/settings/v1'], + 'a custom prefix' => ['/internal/config/', 'internal/config/v1'], + 'no prefix at all' => ['', 'v1'], +]); + +it('lists no settings route when the API is disabled', function (): void { + $this->rebootWith(['laranail.settings.http.enabled' => false]); + + expect(listedSettingsRoutes())->toBe([]); +}); + +it('ships a web route file that registers nothing and is not loaded', function (): void { + $this->rebootWith(['laranail.settings.http.enabled' => true]); + $router = new Router(new Dispatcher); + + require dirname(__DIR__, 2) . '/routes/web.php'; + + expect(is_file(dirname(__DIR__, 2) . '/routes/web.php'))->toBeTrue() + ->and($router->getRoutes()->getRoutes())->toBe([]) + ->and(array_filter(listedSettingsRoutes(), static fn (array $row): bool => str_starts_with((string) $row['name'], 'laranail-settings.web.')))->toBe([]); +}); + +/** + * Every message key the package's source reads (quoted `problems.`, `alert.` and `console.` dot + * paths), plus the problem titles, which Problems reads by type. + * + * @return list + */ +function messageKeysUsedInSource(): array +{ + $root = dirname(__DIR__, 2) . '/src'; + $keys = []; + $files = 0; + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)) as $file) { + if (! $file instanceof SplFileInfo || $file->getExtension() !== 'php') { + continue; + } + + $files++; + $source = (string) file_get_contents($file->getPathname()); + // Crude on purpose: any quoted dot path under a top-level section of the file counts as + // read, which errs toward "used" (a ternary picking one of two keys is covered). + preg_match_all("/'(?:laranail\\/settings::settings\\.)?((?:problems|alert|console)\\.[a-z0-9_.-]*[a-z0-9])'/", $source, $matches); + $keys = [...$keys, ...$matches[1]]; + } + + expect($files)->toBeGreaterThanOrEqual(355); + + $problems = (string) file_get_contents($root . '/Http/Support/Problems.php'); + preg_match_all("/this->make\\(\\d+, '([a-z-]+)'/", $problems, $fixed); + $types = [...problemTypes(), SettingsException::TYPE, ...$fixed[1]]; + + foreach ($types as $type) { + $keys[] = 'problems.titles.' . $type; + } + + $keys = array_values(array_unique($keys)); + sort($keys); + + return $keys; +} + +/** + * Every leaf key of the packaged English file, as a dot path. + * + * @param array $lines + * + * @return list + */ +function messageKeysInFile(array $lines, string $prefix = ''): array +{ + $keys = []; + + foreach ($lines as $name => $line) { + $keys = is_array($line) + ? [...$keys, ...messageKeysInFile($line, $prefix . $name . '.')] + : [...$keys, $prefix . $name]; + } + + sort($keys); + + return $keys; +} + +it('has every message key the source reads in the lang file, and no other', function (): void { + $used = messageKeysUsedInSource(); + $shipped = messageKeysInFile(require dirname(__DIR__, 2) . '/resources/lang/en/settings.php'); + + // Floor: 85 keys read today (28 problem titles, 5 problem details, 11 alert lines, 41 console + // lines; counted 2026-11-10). A scan that suddenly finds fewer has broken. + expect(count($used))->toBeGreaterThanOrEqual(85) + ->and(array_values(array_diff($used, $shipped)))->toBe([], 'read in src/ but missing from resources/lang/en/settings.php') + ->and(array_values(array_diff($shipped, $used)))->toBe([], 'in resources/lang/en/settings.php but read nowhere in src/'); +}); + +it('registers the translations and the mail view under laranail/settings, publishably', function (): void { + $groups = ServiceProvider::publishableGroups(); + + expect(app('translator')->get('laranail/settings::settings.problems.validation'))->toBe('The request is invalid.') + ->and(view()->exists('laranail/settings::mail.alert'))->toBeTrue() + ->and($groups)->toContain('laranail::settings-translations', 'laranail::settings-views') + ->and(array_keys(ServiceProvider::pathsToPublish(SettingsServiceProvider::class, 'laranail::settings-translations')))->not->toBeEmpty() + ->and(array_keys(ServiceProvider::pathsToPublish(SettingsServiceProvider::class, 'laranail::settings-views')))->not->toBeEmpty(); +}); + +it('reads a published translation in place of the packaged English', function (): void { + app('translator')->addLines(['settings.problems.validation' => 'Die Anfrage ist ungültig.'], 'de', 'laranail/settings'); + app()->setLocale('de'); + + expect(__('laranail/settings::settings.problems.validation'))->toBe('Die Anfrage ist ungültig.') + ->and(__('laranail/settings::settings.problems.validation', locale: 'en'))->toBe('The request is invalid.') + ->and(trans_choice('laranail/settings::settings.console.history_pruned', 1, locale: 'en'))->toBe('Removed 1 history entry.') + ->and(trans_choice('laranail/settings::settings.console.history_pruned', 0, locale: 'en'))->toBe('Removed 0 history entries.'); +}); diff --git a/tests/Feature/ReadinessFlushTest.php b/tests/Feature/ReadinessFlushTest.php index 532b4d4..a1532a7 100644 --- a/tests/Feature/ReadinessFlushTest.php +++ b/tests/Feature/ReadinessFlushTest.php @@ -3,26 +3,40 @@ declare(strict_types=1); use Illuminate\Support\Facades\Event; -use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; +use Simtabi\Laranail\DbTools\Schema\SchemaReadinessReport; +use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; /** A probe that counts flushes. */ -function countingProbe(): ReadinessProbe +function countingProbe(): object { - $probe = new class implements ReadinessProbe + $real = app(SchemaReadinessInterface::class); + $probe = new class($real) implements SchemaReadinessInterface { public int $flushes = 0; - public function isReady(?string $connection, array $tables): bool + public function __construct(private readonly SchemaReadinessInterface $real) {} + + public function report(array $requiredTables = [], ?string $connection = null): SchemaReadinessReport + { + return $this->real->report($requiredTables, $connection); + } + + public function isReady(array $requiredTables = [], ?string $connection = null): bool { return true; } - public function flush(): void + public function whenReady(callable $callback, mixed $default = null, array $requiredTables = [], ?string $connection = null): mixed + { + return $callback(); + } + + public function flush(?string $connection = null): void { $this->flushes++; } }; - app()->instance(ReadinessProbe::class, $probe); + app()->instance(SchemaReadinessInterface::class, $probe); return $probe; } diff --git a/tests/Feature/ReferenceDocsTest.php b/tests/Feature/ReferenceDocsTest.php new file mode 100644 index 0000000..df066a2 --- /dev/null +++ b/tests/Feature/ReferenceDocsTest.php @@ -0,0 +1,158 @@ + class basenames in a src directory */ +function classesIn(string $directory): array +{ + $names = array_map(static fn (string $file): string => basename($file, '.php'), glob(dirname(__DIR__, 2) . '/src/' . $directory . '/*.php') ?: []); + sort($names); + + return $names; +} + +/** + * The shipped config's keys as configuration.md names them: a store or layer name becomes + * ``, an `http.routes` entry ``, and a list or an open map is one key. + * + * @param array $config + * + * @return array key => default + */ +function documentedConfigKeys(array $config, string $prefix = ''): array +{ + $keys = []; + $leaves = ['seed.categories', 'authorization.permissions', 'readiness.flush_on', 'importers', 'alerts.rules', 'definitions.sources', 'definitions.allowed_rules']; + + foreach ($config as $key => $value) { + $path = $prefix === '' ? (string) $key : $prefix . '.' . $key; + $path = (string) preg_replace(['/^stores\.[a-z_]+/', '/^layers\.[a-z_]+/', '/^http\.routes\.[a-z_]+/'], ['stores.', 'layers.', 'http.routes.'], $path); + + if (is_array($value) && ! array_is_list($value) && $value !== [] && ! in_array($path, $leaves, true)) { + $keys += documentedConfigKeys($value, $path); + + continue; + } + + $keys[$path] = $value; + } + + return $keys; +} + +it('documents every method of the Settings contract, and the facade proxies each one', function (): void { + $methods = array_map(static fn (ReflectionMethod $method): string => $method->getName(), new ReflectionClass(Settings::class)->getMethods()); + $page = referencePage('tools/settings-api.md'); + $facade = (string) new ReflectionClass(SettingsFacade::class)->getDocComment(); + + expect(count($methods))->toBeGreaterThanOrEqual(47); + + foreach ($methods as $method) { + expect(str_contains($page, '`' . $method . '()`'))->toBeTrue(sprintf('settings-api.md does not document %s()', $method)) + ->and(preg_match('/@method static [^\n]+ ' . $method . '\(/', $facade))->toBe(1, sprintf('the facade docblock does not list %s()', $method)); + } +}); + +it('documents every REST route and every problem type', function (): void { + $this->rebootWith(['laranail.settings.http.enabled' => true]); + $routes = array_filter(Route::getRoutes()->getRoutes(), static fn (RoutingRoute $route): bool => str_starts_with((string) $route->getName(), 'laranail-settings.api.')); + $page = referencePage('tools/rest-api-reference.md'); + $types = problemTypes(); + + expect(count($routes))->toBeGreaterThanOrEqual(39) + ->and(count($types))->toBeGreaterThanOrEqual(24); + + foreach ($routes as $route) { + $method = array_values(array_diff($route->methods(), ['HEAD']))[0]; + $uri = (string) preg_replace('#^api/settings/v1/#', '', $route->uri()); + $name = (string) preg_replace('/^laranail-settings\.api\.(owners\.)?/', '', (string) $route->getName()); + + expect(str_contains($page, sprintf('`%s /%s`', $method, $uri)))->toBeTrue(sprintf('rest-api-reference.md does not document %s /%s', $method, $uri)) + ->and(str_contains($page, '`' . $name . '`'))->toBeTrue(sprintf('rest-api-reference.md does not name route %s', $name)); + } + + foreach ($types as $type) { + expect(str_contains($page, '| `' . $type . '` |'))->toBeTrue(sprintf('rest-api-reference.md does not list problem type %s', $type)); + } +}); + +it('documents every event', function (): void { + $events = classesIn('Events'); + $page = referencePage('tools/events.md'); + + expect(count($events))->toBeGreaterThanOrEqual(30); + + foreach ($events as $event) { + expect(str_contains($page, '`' . $event . '`'))->toBeTrue(sprintf('events.md does not document %s', $event)); + } +}); + +it('documents every exception', function (): void { + $exceptions = classesIn('Exceptions'); + $page = referencePage('tools/exceptions.md'); + + expect(count($exceptions))->toBeGreaterThanOrEqual(30); + + foreach ($exceptions as $exception) { + expect(str_contains($page, '| `' . $exception . '` |'))->toBeTrue(sprintf('exceptions.md does not document %s', $exception)); + } +}); + +it('documents every console command', function (): void { + $commands = array_values(array_filter(array_keys(Artisan::all()), static fn (string $name): bool => str_starts_with($name, 'laranail::settings.'))); + $page = referencePage('tools/commands.md'); + + expect(count($commands))->toBeGreaterThanOrEqual(17); + + foreach ($commands as $command) { + expect(preg_match('/`' . preg_quote($command, '/') . '[ `]/', $page))->toBe(1, sprintf('commands.md does not document %s', $command)); + } +}); + +it('documents every shipped config key with its default', function (): void { + /** @var array $config */ + $config = require dirname(__DIR__, 2) . '/config/settings.php'; + $keys = documentedConfigKeys($config); + $rows = array_filter(explode("\n", referencePage('configuration.md')), static fn (string $line): bool => str_starts_with($line, '| `')); + // A default that is resolved later, or that differs by store or layer, is documented in words. + $describedDefaults = ['schema.path', 'stores..layers', 'seed.categories', 'definitions.allowed_rules', 'readiness.flush_on', 'importers', 'authorization.permissions', 'definitions.sources', 'configuration.sources', 'audit.sinks', 'verification.abilities']; + + expect(count($keys))->toBeGreaterThanOrEqual(80); + + foreach ($keys as $key => $default) { + $row = array_values(array_filter($rows, static fn (string $line): bool => str_contains(explode('|', $line)[1] ?? '', '`' . $key . '`')))[0] ?? null; + + expect($row)->not->toBeNull(sprintf('configuration.md does not document %s', $key)); + + if (str_contains($key, '<') || in_array($key, $describedDefaults, true) || is_array($default)) { + continue; + } + + $shown = match (true) { + $default === null => '`null`', + is_bool($default) => $default ? '`true`' : '`false`', + $default === '' => "`''`", + default => '`' . $default . '`', + }; + + expect(str_contains((string) $row, $shown))->toBeTrue(sprintf('configuration.md gives %s a default other than %s', $key, $shown)); + } +}); diff --git a/tests/Feature/RestApiRoutesTest.php b/tests/Feature/RestApiRoutesTest.php new file mode 100644 index 0000000..ffdf52f --- /dev/null +++ b/tests/Feature/RestApiRoutesTest.php @@ -0,0 +1,92 @@ + "Controller::method" => method, for every public controller method */ +function controllerMethods(): array +{ + $methods = []; + + foreach (glob(dirname(__DIR__, 2) . '/src/Http/Controllers/*.php') ?: [] as $file) { + $class = new ReflectionClass('Simtabi\\Laranail\\Settings\\Http\\Controllers\\' . basename($file, '.php')); + + foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { + if ($method->getName() !== '__construct' && $method->getDeclaringClass()->getName() === $class->getName()) { + $methods[$class->getShortName() . '::' . $method->getName()] = $method; + } + } + } + + return $methods; +} + +/** @return list the Actions\* classes a controller method is handed and calls */ +function delegatedActions(ReflectionMethod $method): array +{ + $lines = file((string) $method->getFileName()) ?: []; + $body = implode('', array_slice($lines, (int) $method->getStartLine() - 1, (int) $method->getEndLine() - (int) $method->getStartLine() + 1)); + $actions = []; + + foreach ($method->getParameters() as $parameter) { + $type = $parameter->getType(); + $class = $type instanceof ReflectionNamedType ? $type->getName() : ''; + + if (str_starts_with($class, 'Simtabi\\Laranail\\Settings\\Actions\\') && preg_match('/\$' . $parameter->getName() . '->(handle|paginate|get|cursor)\(/', $body) === 1) { + $actions[] = $class; + } + } + + return $actions; +} + +/** @return list the API's routes, as the application registered them */ +function apiRoutes(): array +{ + return array_values(array_filter(app(Router::class)->getRoutes()->getRoutes(), static fn (Route $route): bool => str_starts_with((string) $route->getName(), 'laranail-settings.api.'))); +} + +beforeEach(function (): void { + $this->rebootWith(['laranail.settings.http.enabled' => true, 'laranail.settings.http.middleware' => ['api', 'auth']]); +}); + +it('makes every controller method delegate to an action it is handed', function (): void { + $methods = controllerMethods(); + $idle = array_keys(array_filter($methods, static fn (ReflectionMethod $method): bool => delegatedActions($method) === [])); + + expect(count($methods))->toBeGreaterThanOrEqual(30) + ->and($idle)->toBe([]); +}); + +it('routes every controller method, and every route to a controller method that delegates', function (): void { + $routes = apiRoutes(); + $methods = controllerMethods(); + $routed = []; + + foreach ($routes as $route) { + [$controller, $action] = explode('@', $route->getActionName()); + $key = new ReflectionClass($controller)->getShortName() . '::' . $action; + $routed[] = $key; + + expect($methods[$key] ?? null)->toBeInstanceOf(ReflectionMethod::class, sprintf('%s names no controller method', $route->getName())); + } + + expect(count($routes))->toBeGreaterThanOrEqual(39) + ->and(array_values(array_diff(array_keys($methods), $routed)))->toBe([]); +}); + +it('names every route with the vendor-scoped prefix, once', function (): void { + $names = array_map(static fn (Route $route): string => (string) $route->getName(), apiRoutes()); + + expect(count($names))->toBeGreaterThanOrEqual(39) + ->and(array_unique($names))->toHaveCount(count($names)) + ->and(array_filter($names, static fn (string $name): bool => preg_match('/^laranail-settings\.api\.(owners\.)?[a-z]+\.[a-z]+$/', $name) !== 1))->toBe([]); +}); diff --git a/tests/Feature/RuntimeConfigurationTest.php b/tests/Feature/RuntimeConfigurationTest.php index 8a197a6..8cb8c06 100644 --- a/tests/Feature/RuntimeConfigurationTest.php +++ b/tests/Feature/RuntimeConfigurationTest.php @@ -18,14 +18,10 @@ use Simtabi\Laranail\Settings\Exceptions\UnknownStore; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; use Simtabi\Laranail\Settings\Verification\NullVerifier; -use Simtabi\Laranail\Settings\Services\Resolution\Resolver; -use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; -use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Authorization\ClosureAuthorizer; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; use Simtabi\Laranail\Settings\Authentication\ClosureActorResolver; -use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** A logger that keeps messages, for runtime logTo() tests. */ @@ -199,18 +195,13 @@ public function log($level, string|Stringable $message, array $context = []): vo expect($configuration->generation())->toBe($start + 2); }); -it('refuses configuration() on a hand-built manager without runtime configuration', function (): void { - $manager = new SettingsManager( - app(StoreRegistry::class), - app(DefinitionRegistry::class), - app(Resolver::class), - app(SettingWriter::class), - ); +it('gives every manager the container builds the runtime configuration of the request', function (): void { + $manager = app(SettingsManager::class); $manager->set('site.name', 'Acme'); expect($manager->get('site.name'))->toBe('Acme') - ->and(fn (): RuntimeConfiguration => $manager->configuration())->toThrow(LogicException::class, 'without runtime configuration') - ->and(fn (): mixed => $manager->as(user())->get('site.name'))->toThrow(AccessDenied::class) + ->and($manager->configuration())->toBe(app(RuntimeConfiguration::class)) + ->and($manager->store('settings')->configuration())->toBe(app(RuntimeConfiguration::class)) ->and(fn (): SettingsManager => $manager->asCurrentActor())->toThrow(ActorRequired::class); }); diff --git a/tests/Feature/SettingsCacheTest.php b/tests/Feature/SettingsCacheTest.php index 8f81eee..0d96543 100644 --- a/tests/Feature/SettingsCacheTest.php +++ b/tests/Feature/SettingsCacheTest.php @@ -15,9 +15,11 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\CacheTarget; use Illuminate\Contracts\Cache\Factory as CacheFactory; +use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Illuminate\Contracts\Cache\Repository as CacheContract; use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; +use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; /* * The cache service on its own (design §7.5), over an in-memory cache store: the database side is @@ -142,13 +144,27 @@ public function forever($key, $value): bool ->and($cache->bagKey(cacheTarget('mysql', 'app'), Scope::global()))->toBe($keys[3]); }); +/** An operational log that hands each warning's context and message to `$record`. */ +function failureLog(Closure $record): OperationalLogger +{ + return new OperationalLogger(new class($record) extends AbstractLogger + { + public function __construct(private readonly Closure $record) {} + + public function log($level, string|Stringable $message, array $context = []): void + { + ($this->record)($context, (string) $message); + } + }); +} + it('keys the tenant into every bag', function (): void { $tenant = new class { public ?string $id = 'a'; }; $calls = []; - $cache = new SettingsCache(new Repository(new ArrayStore), tenant: static fn (): ?string => $tenant->id); + $cache = new SettingsCache(new Repository(new ArrayStore), tenant: new ClosureTenantDiscriminator(static fn (): ?string => $tenant->id)); $a = $cache->bagKey(cacheTarget(), Scope::global()); $cache->load(cacheTarget(), [Scope::global()], countingLoader($calls)); @@ -180,9 +196,9 @@ public function forever($key, $value): bool it('reads from the database and reports it when the cache fails', function (): void { $calls = []; $failures = []; - $cache = new SettingsCache(brokenCache(), onFailure: static function (string $operation, Throwable $exception) use (&$failures): void { - $failures[] = $operation . ': ' . $exception->getMessage(); - }); + $cache = new SettingsCache(brokenCache(), log: failureLog(static function (array $context, string $message) use (&$failures): void { + $failures[] = $context['operation'] . ': ' . (str_contains($message, 'cache down') ? 'cache down' : $message); + })); $records = $cache->load(cacheTarget(), [Scope::global()], countingLoader($calls)); $cache->forgetScope(cacheTarget(), Scope::global()); @@ -203,9 +219,9 @@ public function putMany(array $values, $seconds): bool throw new RuntimeException('full'); } }); - $cache = new SettingsCache($store, onFailure: static function (string $operation) use (&$failures): void { - $failures[] = $operation; - }); + $cache = new SettingsCache($store, log: failureLog(static function (array $context) use (&$failures): void { + $failures[] = $context['operation']; + })); expect($cache->load(cacheTarget(), [Scope::global()], countingLoader($calls))->count())->toBe(1) ->and($failures)->toBe(['write']); diff --git a/tests/Pest.php b/tests/Pest.php index d295c24..b8db9d8 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -10,8 +10,9 @@ use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Audit\InMemoryAuditSink; use Simtabi\Laranail\Settings\Tests\Fixtures\TestUser; -use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; +use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Services\Drivers\DriverFactory; +use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; // Feature tests boot the application; Unit and Arch tests deliberately do not, so a unit // that quietly relies on the container fails instead of passing. @@ -90,7 +91,7 @@ function useDatabase(array $config = [], array $stores = [], array $ownerTables if (is_dir($directory)) { Artisan::call('migrate:fresh', ['--path' => $directory, '--realpath' => true]); - app(ReadinessProbe::class)->flush(); + app(SchemaReadinessInterface::class)->flush(); return; } @@ -126,5 +127,26 @@ public function up(): void } Artisan::call('migrate:fresh', ['--path' => $directory, '--realpath' => true]); - app(ReadinessProbe::class)->flush(); + app(SchemaReadinessInterface::class)->flush(); +} + +/** + * The problem type of every exception that names one (the base's `settings-error` aside), read + * from the exception classes themselves. + * + * @return list + */ +function problemTypes(): array +{ + $types = []; + + foreach (glob(__DIR__ . '/../src/Exceptions/*.php') ?: [] as $file) { + $class = 'Simtabi\\Laranail\\Settings\\Exceptions\\' . basename($file, '.php'); + + if (is_subclass_of($class, SettingsException::class) && $class::TYPE !== SettingsException::TYPE) { + $types[] = $class::TYPE; + } + } + + return array_values(array_unique($types)); } diff --git a/src/Http/OpenApi/OpenApiDocument.php b/tests/Support/ApiSchemas.php similarity index 55% rename from src/Http/OpenApi/OpenApiDocument.php rename to tests/Support/ApiSchemas.php index 8517029..336530b 100644 --- a/src/Http/OpenApi/OpenApiDocument.php +++ b/tests/Support/ApiSchemas.php @@ -2,156 +2,86 @@ declare(strict_types=1); -namespace Simtabi\Laranail\Settings\Http\OpenApi; - -use Illuminate\Routing\Route; -use Simtabi\Laranail\Settings\Http\ApiRoutes; -use Simtabi\Laranail\Settings\Enums\Capability; +namespace Simtabi\Laranail\Settings\Tests\Support; /** - * An OpenAPI 3.1 document for the REST API (§16.12), built from the routes actually registered - * (so a group switched off in `http.routes` is absent), with one schema per resource. A test - * validates real responses against it, so the document cannot drift from what the API returns. + * The response shapes of the REST API, as JSON Schema: what each route answers on success, by + * route name, and one schema per resource. The REST tests validate every response against them, + * so a resource cannot change its shape without a test noticing. */ -final readonly class OpenApiDocument +final class ApiSchemas { - /** - * @param iterable $routes the application's routes; only the API's are read - * - * @return array - */ - public static function build(iterable $routes, string $version = '0.1.0'): array - { - $paths = []; - - foreach ($routes as $route) { - $name = (string) $route->getName(); - - if (! str_starts_with($name, ApiRoutes::NAME_PREFIX)) { - continue; - } - - $capability = Capability::from(preg_replace('/^owners\./', '', substr($name, strlen(ApiRoutes::NAME_PREFIX))) ?? ''); + /** route name (without `laranail-settings.api.` and `owners.`) => [schema, list?, status] */ + private const array RESPONSES = [ + 'stores.index' => ['Store', true, 200], + 'definitions.index' => ['Definition', true, 200], + 'settings.index' => ['Setting', true, 200], + 'settings.show' => ['Setting', false, 200], + 'settings.update' => ['Setting', false, 200], + 'settings.lock' => ['Setting', false, 200], + 'settings.unlock' => ['Setting', false, 200], + 'settings.rollback' => ['Setting', false, 200], + 'settings.destroy' => [null, false, 204], + 'categories.destroy' => [null, false, 204], + 'configuration.destroy' => [null, false, 204], + 'definitions.destroy' => [null, false, 204], + 'settings.explain' => ['Explanation', false, 200], + 'settings.history' => ['HistoryEntry', true, 200], + 'audit.index' => ['AuditEntry', true, 200], + 'changes.index' => ['ChangeRequest', true, 200], + 'changes.store' => ['ChangeRequest', false, 202], + 'changes.show' => ['ChangeRequest', false, 200], + 'changes.approve' => ['ChangeRequest', false, 200], + 'changes.reject' => ['ChangeRequest', false, 200], + 'changes.cancel' => ['ChangeRequest', false, 200], + 'categories.index' => ['Category', true, 200], + 'categories.store' => ['Category', false, 201], + 'categories.update' => ['Category', false, 200], + 'configuration.index' => ['ConfigurationEntry', true, 200], + 'configuration.update' => ['ConfigurationEntry', false, 200], + 'definitions.update' => ['Definition', false, 200], + 'transfer.export' => ['ExportDocument', false, 200], + 'transfer.import' => ['ImportReport', false, 200], + 'transfer.diff' => ['StoreDiff', false, 200], + ]; - foreach (array_diff($route->methods(), ['HEAD']) as $method) { - $paths['/' . $route->uri()][strtolower($method)] = self::operation($name, $capability, $route); - } - } + /** The routes whose write may open a change request instead (202). */ + private const array MAY_PROPOSE = ['settings.update', 'settings.destroy', 'settings.lock', 'settings.unlock', 'settings.rollback']; - ksort($paths); - - return [ - 'openapi' => '3.1.0', - 'info' => [ - 'title' => 'laranail/settings', - 'version' => $version, - 'description' => 'The settings REST API. Values the caller may not view are left out; errors are RFC 9457 problem details.', - ], - 'paths' => $paths, - 'components' => [ - 'schemas' => self::schemas(), - 'securitySchemes' => ['bearer' => ['type' => 'http', 'scheme' => 'bearer']], - ], - 'security' => [['bearer' => []]], - ]; + /** @return list every route name the shapes cover */ + public static function routes(): array + { + return array_keys(self::RESPONSES); } /** - * The schema name a capability's success response holds, and whether it is a list. + * The schema a route's response with this status must match: its success shape, a change + * request (202 from a write that may propose), or a problem (any 4xx and 5xx); null when the + * route does not answer this status with a body. * - * @return array{?string, bool, int} + * @return array|null */ - public static function response(Capability $capability): array + public static function response(string $route, int $status): ?array { - return match ($capability) { - Capability::StoresIndex => ['Store', true, 200], - Capability::DefinitionsIndex => ['Definition', true, 200], - Capability::SettingsIndex => ['Setting', true, 200], - Capability::SettingsShow, Capability::SettingsUpdate, Capability::SettingsLock, - Capability::SettingsUnlock, Capability::SettingsRollback => ['Setting', false, 200], - Capability::SettingsDestroy, Capability::CategoriesDestroy, Capability::ConfigurationDestroy, - Capability::DefinitionsDestroy => [null, false, 204], - Capability::SettingsExplain => ['Explanation', false, 200], - Capability::SettingsHistory => ['HistoryEntry', true, 200], - Capability::AuditIndex => ['AuditEntry', true, 200], - Capability::ChangesIndex => ['ChangeRequest', true, 200], - Capability::ChangesStore => ['ChangeRequest', false, 202], - Capability::ChangesShow, Capability::ChangesApprove, Capability::ChangesReject, Capability::ChangesCancel => ['ChangeRequest', false, 200], - Capability::CategoriesIndex => ['Category', true, 200], - Capability::CategoriesStore => ['Category', false, 201], - Capability::CategoriesUpdate => ['Category', false, 200], - Capability::ConfigurationIndex => ['ConfigurationEntry', true, 200], - Capability::ConfigurationUpdate => ['ConfigurationEntry', false, 200], - Capability::DefinitionsUpdate => ['Definition', false, 200], - Capability::TransferExport => ['ExportDocument', false, 200], - Capability::TransferImport => ['ImportReport', false, 200], - Capability::TransferDiff => ['StoreDiff', false, 200], - }; - } + $name = (string) preg_replace('/^laranail-settings\.api\.(owners\.)?/', '', $route); + [$schema, $list, $success] = self::RESPONSES[$name] ?? [null, false, 0]; - /** @return array */ - private static function operation(string $name, Capability $capability, Route $route): array - { - [$schema, $list, $status] = self::response($capability); - $parameters = []; - - foreach ($route->parameterNames() as $parameter) { - $parameters[] = ['name' => $parameter, 'in' => 'path', 'required' => true, 'schema' => ['type' => 'string']]; - } - - if (in_array($capability, [Capability::SettingsShow, Capability::SettingsIndex, Capability::SettingsExplain, Capability::SettingsHistory, Capability::SettingsUpdate], true)) { - $parameters[] = ['name' => 'locale', 'in' => 'query', 'required' => false, 'schema' => ['type' => 'string']]; - } - - if ($list) { - $parameters[] = ['name' => 'limit', 'in' => 'query', 'required' => false, 'schema' => ['type' => 'integer', 'minimum' => 1, 'maximum' => 200]]; - $parameters[] = ['name' => 'cursor', 'in' => 'query', 'required' => false, 'schema' => ['type' => 'string']]; - } - - $problem = ['description' => 'A problem (RFC 9457).', 'content' => ['application/problem+json' => ['schema' => ['$ref' => '#/components/schemas/Problem']]]]; - $responses = [(string) $status => $schema === null - ? ['description' => 'Done.'] - : ['description' => 'OK.', 'content' => ['application/json' => ['schema' => $list ? self::listOf($schema) : self::dataOf($schema)]]]]; - - if (in_array($capability, [Capability::SettingsUpdate, Capability::SettingsDestroy, Capability::SettingsLock, Capability::SettingsUnlock, Capability::SettingsRollback], true)) { - $responses['202'] = ['description' => 'The change needs approval: a change request was opened.', 'content' => ['application/json' => ['schema' => self::dataOf('ChangeRequest')]]]; - } - - foreach (['401', '403', '404', '409', '412', '422', '423', '428', '429'] as $code) { - $responses[$code] = $problem; - } - - return array_filter([ - 'operationId' => $name, - 'summary' => $capability->label(), - 'tags' => [$capability->group()], - 'parameters' => $parameters, - 'requestBody' => in_array('GET', $route->methods(), true) ? null : ['required' => false, 'content' => ['application/json' => ['schema' => ['type' => 'object']]]], - 'responses' => $responses, - ], static fn (mixed $value): bool => $value !== null); - } - - /** @return array */ - private static function dataOf(string $schema): array - { - return ['type' => 'object', 'required' => ['data'], 'properties' => ['data' => ['$ref' => '#/components/schemas/' . $schema]]]; + return match (true) { + $status >= 400 => ['$ref' => '#/components/schemas/Problem'], + $status === 202 && in_array($name, self::MAY_PROPOSE, true) => self::dataOf('ChangeRequest'), + $status === $success && $schema !== null => $list ? self::listOf($schema) : self::dataOf($schema), + default => null, + }; } - /** @return array */ - private static function listOf(string $schema): array + /** @return array the document the schemas' `$ref`s resolve in */ + public static function document(): array { - return [ - 'type' => 'object', - 'required' => ['data', 'meta'], - 'properties' => [ - 'data' => ['type' => 'array', 'items' => ['$ref' => '#/components/schemas/' . $schema]], - 'meta' => ['type' => 'object', 'required' => ['next_cursor'], 'properties' => ['next_cursor' => ['type' => ['string', 'null']]]], - ], - ]; + return ['components' => ['schemas' => self::schemas()]]; } /** @return array */ - private static function schemas(): array + public static function schemas(): array { $string = ['type' => 'string']; $nullableString = ['type' => ['string', 'null']]; @@ -319,4 +249,23 @@ private static function schemas(): array ], ['added', 'removed', 'changed', 'unchanged', 'unknown']), ]; } + + /** @return array */ + private static function dataOf(string $schema): array + { + return ['type' => 'object', 'required' => ['data'], 'properties' => ['data' => ['$ref' => '#/components/schemas/' . $schema]]]; + } + + /** @return array */ + private static function listOf(string $schema): array + { + return [ + 'type' => 'object', + 'required' => ['data', 'meta'], + 'properties' => [ + 'data' => ['type' => 'array', 'items' => ['$ref' => '#/components/schemas/' . $schema]], + 'meta' => ['type' => 'object', 'required' => ['next_cursor'], 'properties' => ['next_cursor' => ['type' => ['string', 'null']]]], + ], + ]; + } } diff --git a/tests/Unit/DocsConformanceTest.php b/tests/Unit/DocsConformanceTest.php index 886cb9e..ad94ecc 100644 --- a/tests/Unit/DocsConformanceTest.php +++ b/tests/Unit/DocsConformanceTest.php @@ -6,10 +6,10 @@ uses(AssertsDocsConformance::class); -// Floor = the 41 pages shipped today (5 guides, 25 reference, 11 recipes; counted 2026-11-10). Raise it as pages +// Floor = the 50 pages shipped today (5 guides, 27 reference, 18 recipes; counted 2026-11-10). Raise it as pages // are added; a glob that suddenly matches fewer has broken rather than found a clean tree. it('conforms to the org docs standard', function (): void { - $this->assertDocsConformToStandard(dirname(__DIR__, 2), 41); + $this->assertDocsConformToStandard(dirname(__DIR__, 2), 50); expect(true)->toBeTrue(); }); diff --git a/tests/Unit/SupportTest.php b/tests/Unit/SupportTest.php index ec87f22..8b07fd5 100644 --- a/tests/Unit/SupportTest.php +++ b/tests/Unit/SupportTest.php @@ -2,18 +2,14 @@ declare(strict_types=1); -use Illuminate\Config\Repository; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\OwnerRef; -use Simtabi\Laranail\Settings\Support\ConfigValues; use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Enums\TranslationsMode; use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; it('stores and reads titles in both translation modes', function (): void { $lang = new Translations(TranslationsMode::Lang); @@ -30,10 +26,7 @@ ->and($json->text('{"fr":3}'))->toBe('{"fr":3}') ->and($json->storeNullable(null))->toBeNull() ->and($json->nullableText(null))->toBeNull() - ->and($json->nullableText('{"":"Mail"}'))->toBe('Mail') - // The deprecated helper forwards. - ->and(DatabaseDefinitions::localised('{"":"Mail"}', true))->toBe('Mail') - ->and(DatabaseDefinitions::localised('{"":"Mail"}', false))->toBe('{"":"Mail"}'); + ->and($json->nullableText('{"":"Mail"}'))->toBe('Mail'); }); it('encodes JSON with one set of flags and names what failed', function (): void { @@ -61,21 +54,3 @@ ->and(Scope::global()->owner())->toBeNull() ->and(fn (): ?Scope => Scope::fromString('App\\Models\\User:1'))->toThrow(InvalidIdentifier::class); }); - -it('reads configuration leniently, and lists strictly', function (): void { - $config = new ConfigValues(new Repository([ - 'a' => ['name' => 'x', 'n' => '12', 'bad' => 1.5, 'list' => ['x', 2, 'y'], 'scalar' => 'no'], - ])); - - expect($config->string('a.name', 'd'))->toBe('x') - ->and($config->string('a.n', 'd'))->toBe('12') - ->and($config->string('a.bad', 'd'))->toBe('d') - ->and($config->integer('a.n', 0))->toBe(12) - ->and($config->integer('a.bad', 7))->toBe(7) - ->and($config->integer('a.missing', 7))->toBe(7) - ->and($config->array('a.scalar'))->toBe([]) - ->and($config->strings('a.list'))->toBe(['x', 'y']) - ->and(ConfigValues::listOfStrings(['x', 'y'], 'p'))->toBe(['x', 'y']) - ->and(fn (): array => ConfigValues::listOfStrings(['x', 2], 'p.q'))->toThrow(InvalidConfiguration::class, 'p.q: a list of strings is required.') - ->and(fn (): array => ConfigValues::listOfStrings('x', 'p.q'))->toThrow(InvalidConfiguration::class, 'p.q'); -});