diff --git a/.gitattributes b/.gitattributes index 1bb2920..e5d9214 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,8 +2,9 @@ * text=auto eol=lf # Keep the Composer dist lean: exclude dev-only paths from package archives. -# Source, config, database (migration, factories, seeders), README, LICENSE, CHANGELOG and composer.json ship. +# src, config, database, routes, resources, helpers, README, LICENSE, CHANGELOG and composer.json ship. /.github export-ignore +/.claude export-ignore /benchmarks export-ignore /docs export-ignore /tests export-ignore diff --git a/CHANGELOG.md b/CHANGELOG.md index 076ea71..f5cd9ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `laranail::settings.show {key} [--store=] [--owner=] [--locale=] [--reveal]`: prints how one + setting resolves (value, layer, scope, type, version, locked, encrypted and sensitive flags, and + the latest audit entry), through the same `ExplainSetting` action as `explain()`. Sensitive and + encrypted values print as `[protected]` unless `--reveal` is given. +- `doctor` warns, without failing, about a stored value or a code or config definition whose key's + first segment is not its category's slug (`: category keys`, `definitions: category keys`). +- `Logging\LogContext`: every operational log entry's context now starts with `store`, `key`, + `scope`, `actor` and `channel`, in that order and `null` where the entry has none. Refusals, + write retries, cache failures, alert failures, skipped persisted entries, runtime configuration + changes and log-sink audit entries all use it, so one log query finds every entry about a setting. + - 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 @@ -198,6 +209,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- Prepared for the public release. Source, config, migration, route, helper and test comments are + rewritten as short plain docblocks, with no references to internal planning documents; the + design rationale they carried is now in `docs/architecture.md`. Comment lines in `src/` went + from 3,784 to 2,743. No behaviour changed. +- The migration builds each table in one method with a flat column list; the values table's + indexes moved to `indexValues()`. Every column, type, index name and foreign key is unchanged, + verified by diffing the SQLite schema of the default and the full shape before and after. +- The service provider is split into one private method per concern (`registerDrivers()`, + `registerStores()`, `registerCache()`, `registerLogging()`, `registerAudit()`, + `registerAccess()`, `registerAlerts()`, `bootReadinessFlush()`, `bootListeners()`, …), so + `register()` and `boot()` read as a table of contents. No binding changed. +- README: the Tests, Static analysis and MIT badges, with a note that the package is not on + Packagist; `.gitattributes` also export-ignores `.claude`. - 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 diff --git a/README.md b/README.md index b528399..a430354 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,10 @@ # laranail/settings -No badges yet: the package is not on a registry and its CI history is only days old. -They are added once each claim is true. +[![Tests](https://github.com/laranail/settings/actions/workflows/tests.yml/badge.svg)](https://github.com/laranail/settings/actions/workflows/tests.yml) +[![Static analysis](https://github.com/laranail/settings/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/laranail/settings/actions/workflows/static-analysis.yml) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) + +`laranail/settings` is not published to Packagist, so there is no registry-version badge to show: see [Install](#install). > Key-value settings for any Laravel owner (the application, a user, a tenant, a product), stored in layered stores that work before the database exists. diff --git a/config/settings.php b/config/settings.php index 9931e3d..dc2b16c 100644 --- a/config/settings.php +++ b/config/settings.php @@ -11,16 +11,9 @@ | laranail/settings |-------------------------------------------------------------------------- | -| Read at `config('laranail.settings.*')` and published to -| `config/laranail/settings.php` with: -| -| php artisan laranail::settings.install -| -| The default store keeps its values in the database (the install command -| above publishes the package's one migration; then run `php artisan -| migrate`), above a JSON runtime file and the shipped PHP defaults. An -| application without a database drops `database` from the store's -| `layers`. +| Read from `config('laranail.settings.*')`. Publish it to +| `config/laranail/settings.php` with `php artisan laranail::settings.install`, +| which also publishes the migration. | */ @@ -32,31 +25,26 @@ 'default' => env('LARANAIL_SETTINGS_STORE', 'settings'), /* - | Stores. `layers` are read in order; writes go to the first writable one. - | `owners` lists the morph aliases this store holds values for (each alias - | belongs to one store). `strict` makes keys without a definition an error. - | `inherits` lets owners fall back to their parents and to the global value - | when a definition does not say otherwise. `locks.overridable` lets an - | actor holding `override_lock` write a locked setting; off, a lock binds - | everyone. `table` names the store's database table (default: the store - | name). `bootstrap` lets the database layer be skipped while, and only - | while, the application is being installed (see `bootstrap` below); - | otherwise an unreachable database raises DriverUnavailable. + | Stores, by name. | - | Schema switches per store (migration-time, recorded in the schema file): - | `mode` is `polymorphic` (settable_type/settable_id, any listed alias, plus - | global rows) or `dedicated` (one owner alias, a non-null `owner_id` foreign - | key to `owner.table`, owner rows only; its global values come from - | `fallback`, default the default store). `soft_deletes` keeps forgotten rows - | as trashed and restores them on the next write. `approvals.keys` lists key - | globs (`mail.*`) whose writes become change requests (see `approvals`). + | layers: the layers read in order; writes go to the first writable one. + | owners: the morph aliases this store holds values for. + | strict: reject keys that have no definition. + | inherits: let owners fall back to their parents and the global value. + | locks: `overridable` lets an actor with `override_lock` write a + | locked setting. + | approvals: key globs (`mail.*`) whose writes become change requests. + | bootstrap: skip the database layer while the application installs. + | table: the values table name (default: the store name). + | mode: `polymorphic` or `dedicated` (one owner alias, with a + | foreign key to `owner.table`). Recorded at migration time. + | soft_deletes: keep forgotten rows trashed and restore them on write. | | 'user_settings' => [ | 'layers' => ['database'], | 'owners' => ['user'], | 'mode' => 'dedicated', | 'owner' => ['table' => 'users', 'key' => 'id', 'type' => null], - | 'soft_deletes' => false, | ], */ 'stores' => [ @@ -74,17 +62,15 @@ ], /* - | Positive evidence that the application is being installed, for stores in - | bootstrap mode: set it for the install window only. laranail/installer- - | headless reporting an install in progress counts too. The absence of - | evidence never does. + | Set while the application is being installed, so stores in bootstrap + | mode skip their database layer. laranail/installer-headless reporting an + | install in progress counts too. */ 'bootstrap' => env('LARANAIL_SETTINGS_BOOTSTRAP', false), /* - | Table names (D-4). `prefix` goes in front of every table, including each - | store's values table. Install refuses to run over a table of the same - | name that is not this package's. + | Table names. `prefix` is prepended to every table, including each store's + | values table. */ 'tables' => [ 'prefix' => env('LARANAIL_SETTINGS_TABLE_PREFIX', ''), @@ -98,25 +84,21 @@ /* |-------------------------------------------------------------------------- - | Schema switches (migration-time) + | Schema switches |-------------------------------------------------------------------------- | - | Read by `install` and `make-store`, which record the shape the package - | migration produces in the schema file (`schema.path`, default - | database/settings-schema.php); the migration reads that file. - | The package then reads that file, not these keys, so changing a switch - | after migrating changes nothing until a migration says so; `doctor` - | reports the drift. The defaults are the recommended shape. + | Read by `install` and `make-store`, which record the resulting shape in + | the schema file (`schema.path`, default database/settings-schema.php). + | The package reads that file at runtime, so changing a switch after + | migrating has no effect until a migration applies it; `doctor` reports + | the drift. | - | identity.mode: `slug_uid` (a slug shared by a key's rows and a ULID per - | row), `slug_per_row` (a unique sha1 slug per row, no uid) or `uid_only`. - | ids.type: `bigint`, `uuid` or `ulid`; null follows laranail.db-tools.id_type. - | ids.owner_key: `string` (settable_id as string(36)) or `typed` (typed like - | laranail.db-tools.id_type, for owners that share one key type). - | translations.mode: `lang` (titles, labels and descriptions as text) or - | `json` (per-locale JSON maps). - | categories.soft_deletes: categories are trashed, and restored when the slug - | is created again. + | identity.mode: `slug_uid`, `slug_per_row` or `uid_only`. + | ids.type: `bigint`, `uuid`, `ulid`, or null to follow + | laranail.db-tools.id_type. + | ids.owner_key: `string` (settable_id as string(36)) or `typed`. + | translations.mode: `lang` (plain text) or `json` (per-locale maps). + | categories.soft_deletes: trash categories and restore them on re-create. */ 'schema' => [ 'path' => env('LARANAIL_SETTINGS_SCHEMA_PATH'), @@ -144,20 +126,16 @@ | Tenancy |-------------------------------------------------------------------------- | - | mode (migration-time, recorded in the schema file): - | `none` one set of settings for the application (the default); - | `column` one database: the values, categories and audit tables get a - | `tenant` column, every row is stamped with the current tenant - | and every query is limited to it ('' is the central rows); - | `database` a database per tenant, switched by the tenancy package: no - | tenant column; publish the migration into the tenant - | migrations folder. - | discriminator: who the current tenant is. `auto` uses stancl/tenancy or - | spatie/laravel-multitenancy when installed (neither is required), else - | none; or `null`, `stancl`, `spatie`, or a class implementing - | Simtabi\Laranail\Settings\Contracts\TenantDiscriminator. In every mode - | the tenant also keys what is held in memory during a request or job. - | Definitions are shared by every tenant. + | mode (recorded at migration time): + | `none` one set of settings for the application. + | `column` a `tenant` column on every table, filled and filtered with + | the current tenant ('' is the central partition). + | `database` a database per tenant; publish the migration into the + | tenant migrations folder. + | + | discriminator: `auto` (stancl/tenancy or spatie/laravel-multitenancy when + | installed), `null`, `stancl`, `spatie`, or a class implementing + | Simtabi\Laranail\Settings\Contracts\TenantDiscriminator. */ 'tenancy' => [ 'mode' => env('LARANAIL_SETTINGS_TENANCY', 'none'), @@ -165,14 +143,10 @@ ], /* - | Default data, seeded with the application's `php artisan db:seed` (or - | `db:seed --class="Simtabi\Laranail\Settings\Database\Seeders\DefaultCategoriesSeeder"`). - | `categories` are created as system categories in each of `stores` (empty: - | the default store), as the system actor, so they are validated and - | audited; one that already exists is left as it is, so seeding twice - | changes nothing. A category is `slug => title` or `slug => [title, - | description, icon, parent, sort_order, translations]`. No setting values - | and never any credentials are seeded. `enabled` false switches it off. + | Categories seeded by `php artisan db:seed` as system categories in each of + | `stores` (empty: the default store). Existing categories are left as they + | are. A category is `slug => title` or `slug => [title, description, icon, + | parent, sort_order, translations]`. */ 'seed' => [ 'enabled' => env('LARANAIL_SETTINGS_SEED', true), @@ -188,26 +162,22 @@ ], /* - | Writes. `retry_on_conflict` retries a plain set() once when another writer - | changed the row between the read and the write (re-reading it under a row - | lock where the database supports one). A write that names the version it - | expects is never retried. + | retry_on_conflict: retry a plain set() once when another writer changed + | the row first. Writes that name an expected version are never retried. */ 'writes' => [ 'retry_on_conflict' => true, ], /* - | The settings cache (database layers only; file layers are read directly). - | It holds each scope's raw rows (a "bag"), keyed by connection, database, - | tenant, store and scope, and is invalidated on every write by replacing a - | generation token, so a write is visible on the next read everywhere. - | `store` is a cache store from config/cache.php (null: the default one; - | it must exist, and a node-local store such as `array` or `file` is only - | right for a single server). `ttl` is how long a bag is fresh; for `stale` - | seconds after that it is still answered while it is refreshed in the - | background (Cache::flexible()); 0 turns that off. `prefix` starts every - | key, so two applications can share a cache store. + | The cache in front of database layers. + | + | store: a cache store from config/cache.php, or null for the default. + | Use a shared store when running more than one server. + | prefix: prepended to every cache key. + | ttl: seconds a cached scope stays fresh. + | stale: seconds a stale scope is still served while it refreshes; + | 0 turns this off. */ 'cache' => [ 'enabled' => env('LARANAIL_SETTINGS_CACHE', true), @@ -218,10 +188,9 @@ ], /* - | Events after which the schema readiness memo is forgotten, besides - | migrations, queued jobs and Octane requests: tenant switches. db-tools has - | no tenant hook of its own, so the tenancy packages' events are listened to - | by name (no dependency is added; an event that never fires costs nothing). + | Events that reset the schema readiness check, in addition to migrations, + | queued jobs and Octane requests. Listed by name, so no tenancy package is + | required. */ 'readiness' => [ 'flush_on' => [ @@ -233,9 +202,9 @@ ], /* - | Layers, by name. Drivers: database, json, php, config, array, or a custom - | one registered with DriverFactory::extend(). A JSON path must contain - | {store}. A database layer's `connection` is null for the default one. + | Layers, by name. Drivers: database, json, php, config, array, or one + | registered with DriverFactory::extend(). A JSON path must contain {store}; + | a null database `connection` uses the default connection. */ 'layers' => [ 'database' => [ @@ -255,16 +224,12 @@ ], /* - | Definitions, `key => attributes`: type, default, rules, encrypted, - | public, locked, localised, inherits, overridable_by, precedence, - | label, description, category, group, store. Definitions can also be - | registered in code through DefinitionRegistry::define(). + | Setting definitions are registered in code with DefinitionRegistry::define() + | or kept in the definitions table. | - | Three names are options, not keys (D-6): `table` creates the optional - | settings_definitions table (migration-time), `sources` lists where - | definitions come from, merged in order, later wins per field (`code`, - | `config`, `database`; `database` is read only when the table exists), - | and `allowed_rules` filters the rules of database definitions. + | table: create the settings_definitions table (migration time). + | sources: where definitions come from, merged in order, later wins. + | allowed_rules: the validation rules a database definition may use. */ 'definitions' => [ 'table' => false, @@ -274,19 +239,15 @@ /* |-------------------------------------------------------------------------- - | Access: actors, authorization, verification, audit, logging + | Access |-------------------------------------------------------------------------- | | A call made with an actor (`Settings::as($user)`) is authorized; a call | without one runs as trusted code and is audited as `system`. | - */ - - /* - | How `asCurrentActor()` finds the actor: `guard` (the first of `guards` - | with a user; empty means the default guard), `sanctum` (also reads the - | token's abilities; needs laravel/sanctum), or a class implementing - | ActorResolver. + | resolver: how asCurrentActor() finds the actor: `guard` (the first of + | `guards` with a user), `sanctum` (also reads token abilities), or a class + | implementing ActorResolver. */ 'authentication' => [ 'resolver' => env('LARANAIL_SETTINGS_ACTOR_RESOLVER', 'guard'), @@ -294,12 +255,12 @@ ], /* - | `driver`: `gate` (asks `laranail-settings.`), `permissions` - | (asks `$user->can()` with the names below), a class implementing - | Authorizer, or a list of these tried in order. `undefined` decides an - | ability nobody defined: `deny` (fails closed) or `allow`. - | `require_actor` refuses calls without an actor; `asSystem()` still works. - | Permission names may use {ability}, {store} and {key}. + | driver: `gate` (asks `laranail-settings.`), `permissions` + | (asks `$user->can()` with the names below), a class + | implementing Authorizer, or a list tried in order. + | undefined: `deny` or `allow` an ability nobody defined. + | require_actor: refuse calls without an actor; asSystem() still works. + | permissions: permission names; may use {ability}, {store} and {key}. */ 'authorization' => [ 'driver' => env('LARANAIL_SETTINGS_AUTHORIZER', 'gate'), @@ -328,11 +289,11 @@ ], /* - | Step-up verification for the abilities listed here and for definitions - | marked requiresVerification(). `driver`: `password_confirmation` (the - | session's password confirmation within auth.password_timeout, else the - | actor's verifiedAt), `actor` (the actor's verifiedAt within `ttl` - | seconds), `none`, or a class implementing Verifier. + | Step-up verification for these abilities and for definitions marked + | requiresVerification(). + | + | driver: `password_confirmation`, `actor` (the actor's verifiedAt within + | `ttl` seconds), `none`, or a class implementing Verifier. */ 'verification' => [ 'driver' => env('LARANAIL_SETTINGS_VERIFIER', 'password_confirmation'), @@ -341,12 +302,10 @@ ], /* - | Audit sinks, all of which receive every entry: `auto` (the `database` - | sink for a store with an active database layer, `log` otherwise), - | `database` (the settings_audit table), `log` (the logging channel - | below), `null`, or a class implementing AuditSink. Entries record actions - | and denials, never values. An allowed write and its database audit row - | commit together. `keep_days` is the retention prune-audit applies. + | sinks: every sink receives every entry: `auto` (database when the + | store has a database layer, else log), `database`, `log`, + | `null`, or a class implementing AuditSink. + | keep_days: retention applied by prune-audit. */ 'audit' => [ 'sinks' => ['auto'], @@ -354,9 +313,9 @@ ], /* - | The operational log (denials, verification failures, configuration - | changes, log-sink audit entries). `channel`: null for the application's - | default channel, a channel name, or false to switch it off. + | The operational log: denials, verification failures and configuration + | changes. `channel` is null for the default channel, a channel name, or + | false to turn it off. */ 'logging' => [ 'channel' => null, @@ -365,16 +324,13 @@ /* |-------------------------------------------------------------------------- - | History (§4.3) + | History |-------------------------------------------------------------------------- | - | `enabled` is a schema switch: it decides whether the migration creates - | the settings_history table (one per connection, like the audit table), - | and is recorded in the schema file with the others. With it, every set, - | forget, lock, unlock and rollback appends the value before and after, as - | stored (encrypted values stay encrypted), in the same transaction as the - | change. `keep_days` / `keep_versions` are the retention prune-history - | applies; null switches that rule off. + | enabled: create the settings_history table (migration time) and + | record every value change in it. + | keep_days: retention applied by prune-history; null to disable. + | keep_versions: versions kept per setting; null to disable. */ 'history' => [ 'enabled' => env('LARANAIL_SETTINGS_HISTORY', true), @@ -387,9 +343,8 @@ | Built-in listeners |-------------------------------------------------------------------------- | - | `alerts`: send the alerts below (they still need alerts.enabled). - | `log`: write every settings event to the logging channel above. Off by - | default, because the audit trail already records the actions. + | alerts: send the alerts configured below (they also need alerts.enabled). + | log: write every settings event to the operational log. */ 'listeners' => [ 'alerts' => true, @@ -398,11 +353,11 @@ /* |-------------------------------------------------------------------------- - | Alerts: notifications on changes + | Alerts |-------------------------------------------------------------------------- | - | Laravel notifications sent when an event matches a rule. Alerts carry - | the store, key, scope, actor, outcome and time, never a value. Each rule: + | Notifications sent when an event matches a rule. Alerts never carry a + | value. Each rule: | | 'events' => ['SettingSaved', 'AccessWasDenied'], // short names or classes | 'keys' => ['mail.*'], // globs; null for any @@ -416,8 +371,8 @@ | ], | 'queue' => null, // a queue name, or null to send at once | - | `throttle`: seconds a rule stays quiet about one key after alerting - | about it (0 for never), kept in `cache` (null for the default store). + | throttle: seconds a rule stays quiet about a key after alerting (0: never), + | tracked in `cache` (null: the default store). */ 'alerts' => [ 'enabled' => env('LARANAIL_SETTINGS_ALERTS', false), @@ -428,17 +383,17 @@ /* |-------------------------------------------------------------------------- - | Approvals: four eyes (§16.7) + | Approvals |-------------------------------------------------------------------------- | - | A write to a definition marked requiresApproval(), or to a key matched by - | `stores..approvals.keys`, becomes a change request instead of a - | change. `table` is a schema switch (recorded in the schema file): it - | creates settings_change_requests on every connection a store uses. - | `min_approvals` approvals apply the change; the requester may approve - | their own request only with `allow_self`. A request expires after - | `expire_after` days; prune-changes marks expired requests and deletes - | decided ones older than `keep_days`. + | Writes to definitions marked requiresApproval(), or to keys matched by + | `stores..approvals.keys`, become change requests. + | + | table: create settings_change_requests (migration time). + | min_approvals: approvals needed to apply a change. + | allow_self: let the requester approve their own request. + | expire_after: days before an open request expires. + | keep_days: days decided requests are kept by prune-changes. */ 'approvals' => [ 'table' => true, @@ -450,15 +405,12 @@ /* |-------------------------------------------------------------------------- - | Persisted configuration (§16.11) + | Persisted configuration |-------------------------------------------------------------------------- | - | `persisted` (a schema switch) creates settings_stores, where stores and - | layers saved through the API are kept; definitions saved through the API - | go to the definitions table (definitions.table). `sources` is the merge - | order, later wins: `config` (this file), `database` (persisted entries, - | read on first use, never at boot; an invalid entry is logged and skipped) - | and `runtime` (changes made in code for one request). + | persisted: create settings_stores (migration time) to hold stores and + | layers saved through the API. + | sources: merge order, later wins: `config`, `database`, `runtime`. */ 'configuration' => [ 'persisted' => env('LARANAIL_SETTINGS_PERSISTED_CONFIGURATION', false), @@ -467,12 +419,12 @@ /* |-------------------------------------------------------------------------- - | Import and export (G-42, G-43) + | Importers |-------------------------------------------------------------------------- | - | Importers that `laranail::settings.import --from=` can read, by - | name: a class implementing Simtabi\Laranail\Settings\Contracts\Importer. - | The three shipped ones need none of the packages they read. + | Sources for `laranail::settings.import --from=`: classes implementing + | Simtabi\Laranail\Settings\Contracts\Importer. None needs the package it + | reads. */ 'importers' => [ 'spatie' => SpatieSettingsImporter::class, @@ -482,33 +434,34 @@ /* |-------------------------------------------------------------------------- - | REST API (§16.10) - |-------------------------------------------------------------------------- - | - | Off by default; no route is registered until `enabled` is true. Routes - | live under `prefix`/v1, are named `laranail-settings.api.*`, and run - | through `middleware` (null: ['api', 'auth:sanctum'] when Sanctum is - | installed, else ['api', 'auth']) and the `laranail-settings` rate - | limiter (`rate_limit` requests per minute per actor, 0 for none). - | `routes` switches groups off. `idempotency` keeps the response to a - | write sent with an Idempotency-Key header for `ttl` seconds in `cache` - | (null: the default cache store), so a retried request is answered from - | there instead of applying twice. `owners` maps owner aliases the URL may - | name; null uses the morph map. - */ - /* - |-------------------------------------------------------------------------- - | Typed settings classes (Phase 5) + | Typed settings |-------------------------------------------------------------------------- | | Classes extending Simtabi\Laranail\Settings\Typed\TypedSettings whose - | properties are registered as definitions (type, default, encryption) - | when definitions are first read, so the key-value API casts them alike. + | properties are registered as definitions. */ 'typed' => [ 'classes' => [], ], + /* + |-------------------------------------------------------------------------- + | REST API + |-------------------------------------------------------------------------- + | + | enabled: register the routes (off by default). + | prefix: routes live under `prefix`/v1, named laranail-settings.api.*. + | middleware: null for ['api', 'auth:sanctum'] when Sanctum is installed, + | else ['api', 'auth']. + | rate_limit: requests per minute per actor; 0 for none. + | routes: switch route groups off. + | idempotency: how long (`ttl`) and where (`cache`) responses to writes + | sent with an Idempotency-Key header are kept. + | page_size: items per page in listings. + | + | An optional `owners` key maps owner aliases a URL may name to model + | classes; unset, the morph map is used. + */ 'http' => [ 'enabled' => env('LARANAIL_SETTINGS_HTTP', false), 'prefix' => env('LARANAIL_SETTINGS_HTTP_PREFIX', 'api/settings'), diff --git a/database/migrations/create_laranail_settings_tables.php b/database/migrations/create_laranail_settings_tables.php index fbe6242..2b7493b 100644 --- a/database/migrations/create_laranail_settings_tables.php +++ b/database/migrations/create_laranail_settings_tables.php @@ -18,30 +18,26 @@ use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /* - * laranail/settings: every table the package uses, in dependency order. + * Every table laranail/settings uses, in dependency order: * - * 1. categories shared by the stores on a connection; nested by parent_id - * 2. definitions optional (definitions.table), on the default store's connection - * 3. values one table per database store - * 4. audit actions and denials, never values - * 5. history every value by version (history.enabled), encrypted values still encrypted - * 6. change requests four-eyes approvals (approvals.table); proposed values encrypted as stored - * 7. stores persisted store and layer configuration (configuration.persisted), on the - * default store's connection + * categories shared by the stores on a connection, nested by parent_id + * definitions optional (definitions.table), on the default store's connection + * one values table per database store + * audit actions and denials, never values + * history every value by version (history.enabled) + * change requests pending approvals (approvals.table) + * stores persisted store and layer configuration (configuration.persisted) * - * The shape (key type, identity mode, owner keys, dedicated stores, soft deletes, translations, - * tenancy, table names, connections) comes from the recorded schema file - * (database/settings-schema.php, written by `install` and `make-store`), or from configuration - * when nothing is recorded. Column types are explicit, so db-tools' blueprint macros cannot retype - * them. `down()` drops the same tables in reverse order. + * The shape (key types, identity mode, owner keys, soft deletes, translations, tenancy, table + * names and connections) comes from the recorded schema file, database/settings-schema.php, or + * from configuration when nothing is recorded. * - * `laranail::settings.make-store` copies this file for one new store by rewriting the $only line - * (and, with --connection, the $pinnedConnection line): the copy creates that store's values table - * and, on a connection of its own, that connection's categories, audit and history tables. + * `laranail::settings.make-store` copies this file for one store by rewriting the $only line + * (and, with --connection, the $pinnedConnection line). Keep both lines exactly as they are. */ return new class extends Migration { - /** null: every recorded database store plus the shared tables; a store name: that store only. */ + /** null: every recorded store plus the shared tables; a store name: that store only. */ private ?string $only = null; private ?string $pinnedConnection = null; @@ -53,10 +49,11 @@ public function getConnection(): ?string public function up(): void { - foreach ($this->plan() as $connection => $tables) { - $shape = $this->shape(); + $shape = $this->shape(); + $names = $shape->names; - if ($tables['shared'] && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->categories()))) { + foreach ($this->plan() as $connection => $tables) { + if ($tables['shared'] && $this->missing($connection, $names->categories())) { $this->createCategories($connection, $shape); } @@ -65,22 +62,20 @@ public function up(): void } foreach ($tables['stores'] as $store) { - // A store's own copy skips a table the full migration already created (a - // `migrate:fresh` replays both: the full one creates every recorded store). - if ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->store($store->name, $store->table))) { + if ($this->missing($connection, $names->store($store->name, $store->table))) { $this->createValues($connection, $shape, $store); } } - if ($tables['shared'] && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->audit()))) { + if ($tables['shared'] && $this->missing($connection, $names->audit())) { $this->createAudit($connection, $shape); } - if ($tables['shared'] && $shape->historyTable && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->history()))) { + if ($tables['shared'] && $shape->historyTable && $this->missing($connection, $names->history())) { $this->createHistory($connection, $shape); } - if ($tables['shared'] && $shape->changeRequestsTable && ($this->only === null || ! Schema::connection($connection)->hasTable($shape->names->changeRequests()))) { + if ($tables['shared'] && $shape->changeRequestsTable && $this->missing($connection, $names->changeRequests())) { $this->createChangeRequests($connection, $shape); } @@ -93,68 +88,41 @@ public function up(): void public function down(): void { $shape = $this->shape(); + $names = $shape->names; foreach (array_reverse($this->plan(), true) as $connection => $tables) { $schema = Schema::connection($connection); if ($tables['definitions'] && $shape->storesTable) { - $schema->dropIfExists($shape->names->stores()); + $schema->dropIfExists($names->stores()); } if ($tables['shared'] && $shape->changeRequestsTable) { - $schema->dropIfExists($shape->names->changeRequests()); + $schema->dropIfExists($names->changeRequests()); } if ($tables['shared'] && $shape->historyTable) { - $schema->dropIfExists($shape->names->history()); + $schema->dropIfExists($names->history()); } if ($tables['shared']) { - $schema->dropIfExists($shape->names->audit()); + $schema->dropIfExists($names->audit()); } foreach (array_reverse($tables['stores']) as $store) { - $schema->dropIfExists($shape->names->store($store->name, $store->table)); + $schema->dropIfExists($names->store($store->name, $store->table)); } if ($tables['definitions']) { - $schema->dropIfExists($shape->names->definitions()); + $schema->dropIfExists($names->definitions()); } if ($tables['shared']) { - $schema->dropIfExists($shape->names->categories()); + $schema->dropIfExists($names->categories()); } } } - /** - * What to create on each connection, the default store's connection first. - * - * @return array}> - */ - private function plan(): array - { - $shape = $this->shape(); - $main = $this->connectionOf($shape->store($this->primaryStore())); - - if ($this->only !== null) { - $store = $shape->store(new StoreName($this->only)); - $connection = $this->pinnedConnection ?? $this->connectionOf($store); - - return [$connection => ['shared' => $this->pinnedConnection !== null, 'definitions' => false, 'stores' => [$store]]]; - } - - $plan = [$main => ['shared' => true, 'definitions' => $shape->definitionsTable, 'stores' => []]]; - - foreach ($shape->stores as $store) { - $connection = $this->connectionOf($store); - $plan[$connection] ??= ['shared' => true, 'definitions' => false, 'stores' => []]; - $plan[$connection]['stores'][] = $store; - } - - return $plan; - } - private function createCategories(string $connection, SchemaShape $shape): void { $name = $shape->names->categories(); @@ -219,24 +187,20 @@ private function createDefinitions(string $connection, SchemaShape $shape): void } /** - * One store's values. Identity is (tenant, scope, key, locale); those columns are - * binary-collated so `Theme` and `theme`, or `pt_BR` and `pt_br`, cannot become one row on - * MySQL only (G-38). + * One store's values. The identity columns are binary-collated, so `Theme` and `theme` stay + * two rows on MySQL as they do elsewhere. */ private function createValues(string $connection, SchemaShape $shape, StoreSchema $store): void { $name = $shape->names->store($store->name, $store->table); - $categories = $shape->names->categories(); $index = substr($name, 0, 40); $binary = $this->binaryCollation($connection); - Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $categories, $index, $shape, $store): void { - $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); - + Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $index, $shape, $store): void { $this->key($table, 'id', $shape->ids, primary: true); if ($shape->tenancy === TenancyMode::Column) { - $collate($table->string('tenant', 64)->default('')); + $this->collate($table->string('tenant', 64)->default(''), $binary); } if ($store->isDedicated()) { @@ -248,21 +212,21 @@ private function createValues(string $connection, SchemaShape $shape, StoreSchem : $table->string('settable_id', 36)->nullable(); } - $collate($table->string('scope', 128)); + $this->collate($table->string('scope', 128), $binary); $this->key($table, 'category_id', $shape->ids)->nullable(); $table->string('category_store', 64)->nullable(); $table->string('group', 64); - $collate($table->string('key', 191)); + $this->collate($table->string('key', 191), $binary); if ($shape->identity->hasSlug()) { - $collate($table->string('slug', $shape->identity === IdentityMode::SlugPerRow ? 40 : 191)->nullable()); + $this->collate($table->string('slug', $shape->identity === IdentityMode::SlugPerRow ? 40 : 191)->nullable(), $binary); } if ($shape->identity->hasUid()) { $table->char('uid', 26)->nullable(); } - $collate($table->string('locale', 16)->default('')); + $this->collate($table->string('locale', 16)->default(''), $binary); $table->longText('value')->nullable(); $table->string('type', 64)->nullable(); $this->translatable($table, 'label', $shape); @@ -280,35 +244,41 @@ private function createValues(string $connection, SchemaShape $shape, StoreSchem $table->timestamp('deleted_at')->nullable(); } - $tenant = $this->tenantColumns($shape); - $table->unique([...$tenant, 'scope', 'key', 'locale'], $index . '_identity_unique'); + $this->indexValues($table, $index, $shape, $store); + }); + } - if ($shape->identity->hasUid()) { - $table->unique('uid', $index . '_uid_unique'); - } + private function indexValues(Blueprint $table, string $index, SchemaShape $shape, StoreSchema $store): void + { + $tenant = $this->tenantColumns($shape); - match ($shape->identity) { - IdentityMode::SlugPerRow => $table->unique([...$tenant, 'slug'], $index . '_slug_unique'), - IdentityMode::SlugUid => $table->index('slug', $index . '_slug_index'), - IdentityMode::UidOnly => null, - }; + $table->unique([...$tenant, 'scope', 'key', 'locale'], $index . '_identity_unique'); - if ($store->isDedicated()) { - $table->index('owner_id', $index . '_owner_index'); - $table->foreign('owner_id', $index . '_owner_foreign') - ->references($store->ownerKey)->on((string) $store->ownerTable)->cascadeOnDelete(); - } else { - $table->index(['settable_type', 'settable_id'], $index . '_settable_index'); - } + if ($shape->identity->hasUid()) { + $table->unique('uid', $index . '_uid_unique'); + } - $table->index('category_id', $index . '_category_index'); - $table->index(['autoload', 'scope'], $index . '_autoload_index'); - $table->foreign(['category_id', 'category_store'], $index . '_category_foreign') - ->references(['id', 'store'])->on($categories)->nullOnDelete(); - }); + match ($shape->identity) { + IdentityMode::SlugPerRow => $table->unique([...$tenant, 'slug'], $index . '_slug_unique'), + IdentityMode::SlugUid => $table->index('slug', $index . '_slug_index'), + IdentityMode::UidOnly => null, + }; + + if ($store->isDedicated()) { + $table->index('owner_id', $index . '_owner_index'); + $table->foreign('owner_id', $index . '_owner_foreign') + ->references($store->ownerKey)->on((string) $store->ownerTable)->cascadeOnDelete(); + } else { + $table->index(['settable_type', 'settable_id'], $index . '_settable_index'); + } + + $table->index('category_id', $index . '_category_index'); + $table->index(['autoload', 'scope'], $index . '_autoload_index'); + $table->foreign(['category_id', 'category_store'], $index . '_category_foreign') + ->references(['id', 'store'])->on($shape->names->categories())->nullOnDelete(); } - /** The audit trail (§16.8): who did what, when and through which channel. No value column. */ + /** Who did what, when and through which channel. There is no value column. */ private function createAudit(string $connection, SchemaShape $shape): void { $name = $shape->names->audit(); @@ -343,11 +313,8 @@ private function createAudit(string $connection, SchemaShape $shape): void } /** - * The value history (§4.3): one row per version of a setting, with the payload before and - * after exactly as the values table stores it (an encrypted value stays encrypted). Queried - * by (store, scope, key, locale), so a forget followed by a set keeps one trail; `setting_ref` - * is the row's uid (or id), kept as a string so the table never depends on `ids.type`. - * Identity columns are binary-collated like the values table's. + * One row per version of a setting, with the payload before and after exactly as the values + * table stores it. `setting_ref` is a string so the table never depends on `ids.type`. */ private function createHistory(string $connection, SchemaShape $shape): void { @@ -355,19 +322,17 @@ private function createHistory(string $connection, SchemaShape $shape): void $binary = $this->binaryCollation($connection); Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $name, $shape): void { - $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); - $table->char('id', 26)->primary(); if ($shape->tenancy === TenancyMode::Column) { - $collate($table->string('tenant', 64)->default('')); + $this->collate($table->string('tenant', 64)->default(''), $binary); } $table->string('store', 64); $table->string('setting_ref', 36)->nullable(); - $collate($table->string('scope', 128)); - $collate($table->string('key', 191)); - $collate($table->string('locale', 16)->default('')); + $this->collate($table->string('scope', 128), $binary); + $this->collate($table->string('key', 191), $binary); + $this->collate($table->string('locale', 16)->default(''), $binary); $table->string('operation', 16); $table->longText('old_value')->nullable(); $table->longText('new_value')->nullable(); @@ -388,12 +353,8 @@ private function createHistory(string $connection, SchemaShape $shape): void } /** - * Change requests (§16.7): a write that needs approval waits here until enough approvers - * decide it. `payload` is the proposed value exactly as the values table would store it, so - * the value of an encrypted definition is encrypted at rest; `base_version` is the version the - * setting was at when the request was opened, and applying checks it, so a request whose - * setting changed since becomes `stale` instead of overwriting. Keyed by ULID, so the table - * never depends on `ids.type`. + * Writes waiting for approval. `payload` is stored as the values table would store it, and + * `base_version` lets a request whose setting has since changed become `stale`. */ private function createChangeRequests(string $connection, SchemaShape $shape): void { @@ -401,18 +362,16 @@ private function createChangeRequests(string $connection, SchemaShape $shape): v $binary = $this->binaryCollation($connection); Schema::connection($connection)->create($name, function (Blueprint $table) use ($binary, $name, $shape): void { - $collate = static fn (ColumnDefinition $column): ColumnDefinition => $binary === null ? $column : $column->collation($binary); - $table->char('id', 26)->primary(); if ($shape->tenancy === TenancyMode::Column) { - $collate($table->string('tenant', 64)->default('')); + $this->collate($table->string('tenant', 64)->default(''), $binary); } $table->string('store', 64); - $collate($table->string('scope', 128)); - $collate($table->string('key', 191)); - $collate($table->string('locale', 16)->default('')); + $this->collate($table->string('scope', 128), $binary); + $this->collate($table->string('key', 191), $binary); + $this->collate($table->string('locale', 16)->default(''), $binary); $table->string('operation', 16); $table->longText('payload')->nullable(); $table->string('type', 64)->nullable(); @@ -438,11 +397,7 @@ private function createChangeRequests(string $connection, SchemaShape $shape): v }); } - /** - * Persisted configuration (§16.11): store and layer entries edited through the API, merged - * with the configuration file in `configuration.sources` order. `config` holds the entry as - * the configuration file would (JSON, so its key order is never relied on). - */ + /** Store and layer entries edited through the API; `config` holds the entry as JSON. */ private function createStores(string $connection, SchemaShape $shape): void { $name = $shape->names->stores(); @@ -459,9 +414,45 @@ private function createStores(string $connection, SchemaShape $shape): void } /** - * A key column typed per `ids.type`. The primary key is an explicit command, not the fluent - * ->primary(): Laravel appends fluent indexes after every other command, so PostgreSQL would - * see a self-referencing foreign key before the key it references (SQLSTATE 42830). + * What to create on each connection, the default store's connection first. + * + * @return array}> + */ + private function plan(): array + { + $shape = $this->shape(); + $main = $this->connectionOf($shape->store($this->primaryStore())); + + if ($this->only !== null) { + $store = $shape->store(new StoreName($this->only)); + $connection = $this->pinnedConnection ?? $this->connectionOf($store); + + return [$connection => ['shared' => $this->pinnedConnection !== null, 'definitions' => false, 'stores' => [$store]]]; + } + + $plan = [$main => ['shared' => true, 'definitions' => $shape->definitionsTable, 'stores' => []]]; + + foreach ($shape->stores as $store) { + $connection = $this->connectionOf($store); + $plan[$connection] ??= ['shared' => true, 'definitions' => false, 'stores' => []]; + $plan[$connection]['stores'][] = $store; + } + + return $plan; + } + + /** + * Whether to create this table. A single store's copy skips a table that already exists, + * because `migrate:fresh` replays both it and the full migration. + */ + private function missing(string $connection, string $table): bool + { + return $this->only === null || ! Schema::connection($connection)->hasTable($table); + } + + /** + * A key column typed per `ids.type`. The primary key is an explicit command rather than the + * fluent ->primary(), so PostgreSQL sees it before a self-referencing foreign key. */ private function key(Blueprint $table, string $column, IdType $type, bool $primary = false): ColumnDefinition { @@ -482,7 +473,7 @@ private function key(Blueprint $table, string $column, IdType $type, bool $prima return $definition; } - /** A title, label or description: text, or a JSON map of locale to text (D-8). */ + /** A title, label or description: text, or a JSON map of locale to text. */ private function translatable(Blueprint $table, string $column, SchemaShape $shape, bool $nullable = true): void { $definition = $shape->translations === TranslationsMode::Json @@ -494,7 +485,12 @@ private function translatable(Blueprint $table, string $column, SchemaShape $sha } } - /** The binary collation of the identity columns on this connection's driver (G-38). */ + private function collate(ColumnDefinition $column, ?string $binary): ColumnDefinition + { + return $binary === null ? $column : $column->collation($binary); + } + + /** The binary collation for identity columns on this connection's driver. */ private function binaryCollation(string $connection): ?string { return match (DB::connection($connection)->getDriverName()) { @@ -504,7 +500,7 @@ private function binaryCollation(string $connection): ?string }; } - /** The tenant column of column-mode tenancy: '' is the central (no tenant) partition. */ + /** The tenant column of column-mode tenancy: '' is the central partition. */ private function tenant(Blueprint $table, SchemaShape $shape): void { if ($shape->tenancy === TenancyMode::Column) { diff --git a/docs/architecture.md b/docs/architecture.md index 1ed8a8b..69e0297 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -79,13 +79,22 @@ them. The design borrows from each and credits them here as each idea lands. Driver names arrive from configuration, and in multi-tenant installs possibly from database rows. Resolving them through an enum with an exhaustive `match` (the pattern `laranail/captcha` uses) means a name that is not a known driver resolves to nothing, rather than being interpolated into a -method call. Custom drivers are registered with closures, never class names. +method call. Custom drivers are registered with closures, never class names. The same holds for a stored +`type`: it must be a registered caster alias, and the rules a definitions-table row carries are +filtered through `definitions.allowed_rules`, so no row can make the package run arbitrary code. ## Why fail closed after installation? A short database outage on a live install must not quietly serve shipped defaults (for example a maintenance flag) or scatter writes into each server's local file. Falling back is allowed only on -positive evidence that installation is still in progress. +positive evidence that installation is still in progress: the operator's `bootstrap` flag, or +laranail/installer-headless reporting an install under way. Its `isInstalled()` is not used, +because it probes the database, and an outage would read as "not installed". A required layer +that cannot be reached raises `DriverUnavailable`. + +The encrypter is resolved only when a value is encrypted or decrypted, so an application without +an `APP_KEY` yet still boots and reads its unencrypted settings. Decryption also tries the keys in +`APP_PREVIOUS_KEYS`. ## Why version-checked writes? @@ -96,6 +105,13 @@ index, which the driver reports as `ConcurrentModification`. A plain upsert cann version, so it is not used. The insert runs in a savepoint, because on Postgres a failed statement would otherwise abort the whole surrounding transaction. +A write tries an update at the expected version, then the restore of a trashed row at that +version, then an insert. The one retry of a plain `set()` re-reads the row `FOR UPDATE`, because +under MySQL's REPEATABLE READ a plain re-read returns the old snapshot. A row created again after +a forget continues its version from the history, so "version N" always names one value. An +approved change request is applied against the version it was opened at, and a rollback is +written as a new version through the same pipeline, so it can itself be rolled back. + ## Why is the audit row in the write's transaction? An audit trail that can miss a change is not an audit trail. With a database layer, the change @@ -103,6 +119,10 @@ and its audit row commit together, so a failed audit insert rolls the change bac failures are written outside any transaction, because there is nothing to roll back and the record of the refusal must survive it. +`AuditedTransaction` is the single commit path for every write action, category change and +promotion. On failure it rolls back, records a `failed` entry outside the transaction and +rethrows the original exception, which still wins if recording the failure fails too. + ## Why is `scope` a column, not just `settable_type` and `settable_id`? A unique index treats `NULL`s as distinct, so global rows (no owner) could repeat. `scope` @@ -114,7 +134,7 @@ Postgres. `settable_*` remain for reporting and for an application's own `morphT The package is used from controllers, jobs, commands and other packages, and it cannot know which of those calls are on a person's behalf. So the caller says: `as($user)` makes every operation, reads included, go through one `Authorizer` seam (Laravel's gate by default, so a host's existing policies and `Gate::before` rules apply), and is audited with who did it and why. Code that passes no actor is the application itself and keeps working unchanged, audited as `system`; a host that wants every call attributed turns on `authorization.require_actor`, and trusted code then has to say `asSystem()`. Undefined abilities deny, so forgetting to define a gate fails closed. A token is a ceiling on top of the gate, never a grant, so a leaked token cannot exceed its owner. -Every write is one `final` action (`Actions\SetSetting`, …) that authorizes, writes and audits. The PHP API delegates to it today; console commands and the REST API will delegate to the same actions, so the rules cannot drift between channels. +Every write is one `final` action (`Actions\SetSetting`, …) that authorizes, writes and audits. The PHP API, the console commands and the REST API all delegate to these actions, so the rules cannot drift between channels. ## Why are the table shapes switches, and why are they recorded? @@ -184,19 +204,26 @@ costs nothing. Another tenancy package adds its event to the list. The cache holds each scope's raw rows (a "bag"), never resolved values. A resolved value depends on every scope the cascade walked (owner, team, tenant, global), so caching it would make a write -to `team:7` stale in every user's entry that inherited from it, with no cheap way to find them -(G-32). A bag depends on one scope only: the write invalidates exactly one entry and every +to `team:7` stale in every user's entry that inherited from it, with no cheap way to find them. +A bag depends on one scope only: the write invalidates exactly one entry and every inheriting user resolves the new value on the next read, in memory, from bags that are still valid. Resolution stays a pure function of the bags, so `explain()` and the cascade behave the same cached or not. Invalidation replaces a random generation token instead of deleting the entry, so a stale-while-revalidate refresh started before a write can only land under a generation no reader -uses any more (R-23), and an evicted token cannot revive an old entry the way a restarted counter -could (R-41). The key hashes connection, database, tenant, store, table and scope as a +uses any more, and an evicted token cannot revive an old entry the way a restarted counter +could. The key hashes connection, database, tenant, store, table and scope as a length-prefixed tuple, so neither a shared cache store nor a `:` inside a scope can make two -tenants or databases meet (G-37, R-63). While a transaction is open on a layer's connection the -layer bypasses the cache, so nothing uncommitted is ever cached. +tenants or databases meet. While a transaction is open on a layer's connection the +layer bypasses the cache, so nothing uncommitted is ever cached; so does a layer in bootstrap +mode, so the empty answers before installation are never cached. + +A bag holds every row of its scope, not only the autoload rows, because a cached bag is treated +as complete: a partial bag would turn a non-autoload value into a miss. It is stored as plain +arrays, never objects, so the cache never unserializes a package class (applications may restrict +`cache.serializable_classes`), and an entry written by another release, or a corrupted one, reads +as a miss, never as an empty scope. Measured with `composer bench` (phpbench 1.7, PHP 8.5.7, SQLite file database, 200 revolutions x 5 iterations per subject; one revolution is one request reading ten settings through @@ -222,12 +249,78 @@ 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, 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. +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; it lives here 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. +## Why code definitions win over the definitions table + +The definitions table holds `is_system` copies of code and config definitions for admin screens, +and they are never read back: code stays the source of truth, so a synced copy from an older +release cannot override a new release's default. A row edited at runtime only answers for a key no +code definition covers. + +## Why owners are stored by morph alias + +Owners are referenced by alias and id (`user:7`), never by class name. Renaming a model class +orphans nothing, resolving a parent loads no model, and an alias read from the database is never +instantiated as a class. `rescope` renames an alias in values, history and change requests, and +leaves the audit trail as it was, because the trail records what happened under the old name. + +## Why keys and locales are normalised + +Keys are lower-cased and may not contain hyphens, which keeps the key-to-slug mapping one-to-one +(`mail.host` and `mail-host`). Locales normalise to `ll` or `ll_CC`, so two spellings never become +two rows. The identity columns are binary-collated so MySQL compares them the way the other +databases do. + +## Why events carry no values + +Every event carries identifiers only, so a queued listener cannot leak a secret into the jobs +table. Most events dispatch after commit. `AccessWasDenied` and `VerificationWasRequired` +dispatch at once, because the refusal usually rolls the surrounding transaction back and a +security listener must still hear of it. + +## Why alerts never throw + +An alert reports a change that has already committed, so an alert that cannot be sent is logged +rather than raised. When the throttle's cache fails the alert is sent anyway: a repeated alert is +better than a missed one. + +## Why persisted configuration loads lazily + +Persisted stores and layers are read on first use, never at boot, and an invalid row is logged and +skipped (`doctor` lists it), so a bad row cannot stop the application from booting. A persisted +entry may not re-layer a store the configuration file defines, because moving data between drivers +is `promote`'s job. + +## Why promotion never copies shipped defaults + +`promote` copies only values written to the runtime file before installation, so a later release +can still change a shipped default. The runtime file is archived afterwards, so a second run does +nothing. Its lock is only as wide as the cache store, so a multi-server install needs a shared +cache. + +## Why install checks for foreign tables + +A bare `settings` table plausibly belongs to the application. Installing over it would fail half +way or write into it, so `install` recognises the package's tables by columns only they have and +refuses to run over anything else. An unreachable database is not reported as foreign. + +## Why `settings()` is namespaced + +A global `settings()` function is a name many packages and applications already define, and a +second definition either fatals or silently wins. The helper lives in the package's namespace. + +## Why the models get a static context + +Eloquent builds models with `new static`, so nothing can be injected into them. The provider gives +`ModelContext` closures that resolve the scoped schema, tenant and default store on each call, so +no request or tenant state is held statically. The engine never reads through the models; they +exist for factories, seeders, admin screens and tests. + ## How the container builds it Most classes are autowired. A class's lifetime is an attribute on the class (`#[Scoped]` for diff --git a/docs/tools/approvals.md b/docs/tools/approvals.md index 3f82d87..456b405 100644 --- a/docs/tools/approvals.md +++ b/docs/tools/approvals.md @@ -1,6 +1,6 @@ # Approvals -Four-eyes changes (§16.7): a write to a setting that needs approval becomes a change request, and is applied only after someone else approves it. +Four-eyes changes: a write to a setting that needs approval becomes a change request, and is applied only after someone else approves it. ## Which writes need approval diff --git a/docs/tools/audit-and-logging.md b/docs/tools/audit-and-logging.md index 38108f5..6e99b9b 100644 --- a/docs/tools/audit-and-logging.md +++ b/docs/tools/audit-and-logging.md @@ -77,7 +77,23 @@ Schedule::command('laranail::settings.prune-audit')->weekly(); ## The operational log -Refusals are logged as warnings, and runtime configuration changes and log-sink audit entries at `info`, with store, key, scope and actor identifiers. +Refusals are logged as warnings, and runtime configuration changes and log-sink audit entries at `info`. + +Every entry's context starts with the same five keys, in this order, `null` where the entry has +none, followed by anything specific to the entry (`reason`, `operation`, `event`, …). No context +holds a value. + +| Context key | Holds | +|---|---| +| `store` | the store name | +| `key` | the setting key | +| `scope` | `global` or `alias:id` | +| `actor` | `type`, `alias` and `id` of the actor, plus its `channel` where known | +| `channel` | `php`, `rest`, `console` or `queue` | + +So a log query such as `context.store = "settings" and context.key = "mail.host"` finds every +entry about one setting, whichever part of the package wrote it. The keys are listed in +`Logging\LogContext::KEYS`. | Key | Default | Effect | |---|---|---| diff --git a/docs/tools/caching.md b/docs/tools/caching.md index 5a3d0b6..22f924d 100644 --- a/docs/tools/caching.md +++ b/docs/tools/caching.md @@ -26,7 +26,7 @@ A read through the cascade (owner, parents, global) costs, per distinct store in A bag's key is `::`. The first hash covers connection name, database name, tenant, store, table and scope as a length-prefixed tuple, so `a` + `b:c` and `a:b` + `c` never meet, and neither do two tenants or two databases that both -have a `global` scope (G-37). The tenant comes from the configured `TenantDiscriminator` in every +have a `global` scope. The tenant comes from the configured `TenantDiscriminator` in every tenancy mode, `none` included. ## Invalidation diff --git a/docs/tools/commands.md b/docs/tools/commands.md index 8680efb..aa26332 100644 --- a/docs/tools/commands.md +++ b/docs/tools/commands.md @@ -1,6 +1,6 @@ # Commands -Eighteen Artisan commands, all named `laranail::settings.`. +Nineteen Artisan commands, all named `laranail::settings.`. ## The commands @@ -10,6 +10,7 @@ Eighteen Artisan commands, all named `laranail::settings.`. | `laranail::settings.make-store {store} [--owner=*] [--connection=]` | writes a new store's migration (a copy of the package migration pinned to that store), records it in the schema file and prints its configuration entry | | `laranail::settings.promote [store] [--force] [--from=]` | copies values written before install from the runtime file into the database | | `laranail::settings.doctor [--json] [--fix]` | checks readiness, schema drift against the schema file and rows the database cannot guard; `--fix` syncs definitions first | +| `laranail::settings.show {key} [--store=] [--owner=] [--locale=] [--reveal]` | prints how one setting resolves: value, layer, scope, type, version, flags and the latest audit entry | | `laranail::settings.sync-definitions` | copies code and config definitions into the definitions table as system rows | | `laranail::settings.prune-orphans [--dry-run]` | removes the settings of owners that no longer exist | | `laranail::settings.prune-audit [--days=]` | removes audit rows older than `audit.keep_days` | @@ -57,10 +58,49 @@ For every store with a database layer: | schema | a column the recorded shape uses is missing, or `id` has the wrong type (warns on a column the shape does not have) | | scopes | a scope names a class instead of a morph alias (fails) or an alias the store does not list (warns) | | categories | a row points at a category of another store | +| category keys | warns when a value's key does not start with its category's slug | -It exits non-zero on a failure, so it can gate a deploy. `--json` prints a machine-readable +After the stores it checks code and config definitions the same way (`definitions: category +keys`, a warning) and lists persisted configuration entries skipped as invalid. + +It exits non-zero on a failure, not on a warning, so it can gate a deploy. `--json` prints a machine-readable report. +## `show` + +```bash +php artisan laranail::settings.show mail.from_address +php artisan laranail::settings.show theme --owner=user:42 --locale=fr +``` + +```text ++------------+---------------------------------------------------------------------+ +| Field | Value | ++------------+---------------------------------------------------------------------+ +| Key | mail.from_address | +| Store | settings | +| Scope | global | +| Locale | - | +| Value | "hello@example.com" | +| Layer | database | +| From scope | global | +| Type | string | +| Version | 3 | +| Locked | no | +| Encrypted | no | +| Sensitive | no | +| Defined | yes | +| Last audit | update allowed by user:user:1 via rest at 2026-11-10T09:12:44+00:00 | ++------------+---------------------------------------------------------------------+ +``` + +The resolution steps follow the table, one per line, as `explain()` returns them. The value of a +sensitive or encrypted setting prints as `[protected]` unless `--reveal` is given. `Version` and +the flags come from the row that answered; for a definition default or a miss they come from the +definition, or show `-`. `Last audit` is the newest entry for that key and scope, or `-` when the +audit trail is not stored in the database. The command runs as the system actor, through the same +`Actions\Reads\ExplainSetting` action as `explain()` and the REST API. + ## `prune-orphans` Lists, per store and alias, the owner scopes whose model no longer exists (soft-deleted models diff --git a/docs/tools/import-export.md b/docs/tools/import-export.md index c6a183b..194964d 100644 --- a/docs/tools/import-export.md +++ b/docs/tools/import-export.md @@ -1,6 +1,6 @@ # Import and export -A store as one portable JSON document: categories by slug, settings by scope, key and locale, never by a numeric id (G-42). +A store as one portable JSON document: categories by slug, settings by scope, key and locale, never by a numeric id. ## The document @@ -22,7 +22,7 @@ A store as one portable JSON document: categories by slug, settings by scope, ke A value is the stored JSON exactly as it is, so nothing is lost whatever its type. Only the current tenant's rows are exported. -## Secrets (G-10) +## Secrets | Mode | Encrypted values | How | |---|---|---| diff --git a/docs/tools/importers.md b/docs/tools/importers.md index c5368af..8f8a736 100644 --- a/docs/tools/importers.md +++ b/docs/tools/importers.md @@ -1,6 +1,6 @@ # Importers -Three importers read another package's settings into an export document (G-43), which the normal [import](import-export.md) then writes. None of those packages is needed. +Three importers read another package's settings into an export document, which the normal [import](import-export.md) then writes. None of those packages is needed. ## Shipped importers diff --git a/docs/tools/persisted-configuration.md b/docs/tools/persisted-configuration.md index 554a950..37a1efa 100644 --- a/docs/tools/persisted-configuration.md +++ b/docs/tools/persisted-configuration.md @@ -1,6 +1,6 @@ # Persisted configuration -Stores, layers and definitions saved in the database and edited through the PHP and REST APIs (§16.11), beside the configuration file. +Stores, layers and definitions saved in the database and edited through the PHP and REST APIs, beside the configuration file. ## Turning it on diff --git a/docs/tools/reencryption.md b/docs/tools/reencryption.md index 4a0270f..f55993e 100644 --- a/docs/tools/reencryption.md +++ b/docs/tools/reencryption.md @@ -1,6 +1,6 @@ # Re-encryption and rescoping -Two maintenance commands that rewrite stored rows: re-encrypting secrets after a key rotation (§6), and renaming an owner alias (G-30). +Two maintenance commands that rewrite stored rows: re-encrypting secrets after a key rotation, and renaming an owner alias. ## After rotating `APP_KEY` @@ -24,7 +24,7 @@ The `scope` of a stored value embeds its owner's morph alias (`user:42`). After ```bash php artisan laranail::settings.rescope user member -php artisan laranail::settings.rescope 'App\Models\User' user # rows from before the alias allow-list (G-6) +php artisan laranail::settings.rescope 'App\Models\User' user # rows written with a class name instead of an alias ``` Every scope `:` becomes `:` in every database store, with `settable_type` and the per-row slug of `slug_per_row`, in the history, and in change requests, in chunks of 500. The audit trail is left as it was: it records what happened under the old name. Then update the stores' `owners` lists to the new alias. A row whose new identity already exists makes the database refuse the rename, inside a transaction, so nothing changes. diff --git a/docs/tools/rest-api.md b/docs/tools/rest-api.md index 290e0ac..45853ba 100644 --- a/docs/tools/rest-api.md +++ b/docs/tools/rest-api.md @@ -1,6 +1,6 @@ # REST API -A JSON API over every capability of the PHP API (§16.10), in this package and off by default. +A JSON API over every capability of the PHP API, in this package and off by default. ## Turning it on diff --git a/docs/tools/schema-switches.md b/docs/tools/schema-switches.md index c5e6f13..5072e25 100644 --- a/docs/tools/schema-switches.md +++ b/docs/tools/schema-switches.md @@ -37,7 +37,7 @@ type, so the composite foreign key from a values table to its store's categories `ids.owner_key = typed` types `settable_id` like `laranail.db-tools.id_type` (the key type of the application's models). A write for an owner id of another shape (`user:abc` against bigint keys) raises `OwnerNotAllowed`. The package itself never queries by `settable_id`: every read goes -through `scope`, so the owner key type never meets the column type (G-26). +through `scope`, so the owner key type never meets the column type. ## Dedicated stores @@ -90,7 +90,7 @@ plain text or translation keys and `translations` is ignored. ## The definitions table -`definitions.table = true` creates `settings_definitions` (§4.4 of the design). Code and config +`definitions.table = true` creates `settings_definitions`. Code and config definitions are copied in as read-only `is_system` rows by `laranail::settings.sync-definitions` (also run by `install` once the table exists, and by `doctor --fix`), so UIs can list them; system rows nothing defines any more are removed. diff --git a/docs/tools/typed-settings.md b/docs/tools/typed-settings.md index 659288b..720681f 100644 --- a/docs/tools/typed-settings.md +++ b/docs/tools/typed-settings.md @@ -1,6 +1,6 @@ # Typed settings -Classes whose typed properties are settings, loaded and saved through the key-value engine (Phase 5). The idea comes from [spatie/laravel-settings](https://github.com/spatie/laravel-settings), credited with thanks; here a typed class is a view over keys, not a store of its own. +Classes whose typed properties are settings, loaded and saved through the key-value engine. The idea comes from [spatie/laravel-settings](https://github.com/spatie/laravel-settings), credited with thanks; here a typed class is a view over keys, not a store of its own. ## A typed class @@ -50,7 +50,7 @@ Resolving a class listed in `typed.classes` from the container loads it through Register a class with an `#[Encrypted]` property before saving it, or the value is stored like any other. -## Settings migrations (G-17) +## Settings migrations Rename, move, add and delete keys in a migration, in order with the application's other migrations: diff --git a/helpers/helpers.php b/helpers/helpers.php index d769059..18a3baa 100644 --- a/helpers/helpers.php +++ b/helpers/helpers.php @@ -3,19 +3,14 @@ declare(strict_types=1); /* - * laranail/settings: the `settings()` helper, a consumer convenience over the Settings contract. - * - * It is a namespaced function, never a global one: a bare global `settings()` is a name many - * packages and applications already define, and the second definition would silently win (or - * fatal). Import it where you want it: + * The `settings()` helper. It is namespaced because a global `settings()` would collide with + * other packages. Import it where you want it: * * use function Simtabi\Laranail\Settings\settings; * * settings('site.name'); // Settings::get('site.name') * settings('site.tagline', 'Welcome'); // with a default * settings()->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; @@ -25,8 +20,7 @@ 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. + * The settings handle, or the value of `$key` when one is given. * * @return ($key is null ? Settings : mixed) */ diff --git a/routes/api.php b/routes/api.php index 7762ad3..f1c7e42 100644 --- a/routes/api.php +++ b/routes/api.php @@ -14,19 +14,14 @@ use Simtabi\Laranail\Settings\Http\Controllers\ConfigurationController; /* - * The laranail/settings REST API (design §16.10). SettingsServiceProvider loads this file only - * when `laranail.settings.http.enabled` is on, inside one group that adds the `http.prefix`/v1 - * URI prefix, the `laranail-settings.api.` name prefix, `http.middleware`, the - * `laranail-settings` rate limiter and the parameter patterns. `route:cache` caches these routes - * like the application's own. - * - * Each `http.routes.` switch leaves its group out when it is false. Every write passes the - * idempotency middleware. + * The REST API, loaded only when `laranail.settings.http.enabled` is on. The provider wraps it in + * the `http.prefix`/v1 prefix, the `laranail-settings.api.` name prefix, the configured middleware + * and rate limiter. Each `http.routes.` switch can turn a group off. */ $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. +// The same setting routes, globally and for an owner. $settings = static function () use ($enabled): void { Route::prefix('settings')->name('settings.')->group(static function () use ($enabled): void { if ($enabled('settings')) { diff --git a/routes/web.php b/routes/web.php index a34436b..fdc54b7 100644 --- a/routes/web.php +++ b/routes/web.php @@ -3,12 +3,7 @@ declare(strict_types=1); /* - * laranail/settings web routes. Not loaded: the package is headless (design §16.1), so it serves - * no pages and this file holds no routes. - * - * A route belongs here only if it answers a browser rather than an API client, such as a signed - * link an alert mail points at, and it is named `laranail-settings.web.`. 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. + * Not loaded: the package is headless and serves no pages. A route answering a browser, such as a + * signed link in an alert mail, would go here as `laranail-settings.web.`, loaded from the + * service provider behind `http.enabled`. */ diff --git a/src/Actions/Approvals/ApproveChange.php b/src/Actions/Approvals/ApproveChange.php index 7b297dc..a908c10 100644 --- a/src/Actions/Approvals/ApproveChange.php +++ b/src/Actions/Approvals/ApproveChange.php @@ -35,12 +35,9 @@ use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** - * Approve a change request (§16.7): needs `approve` on its setting. The requester cannot approve - * their own request unless `approvals.allow_self` is on. Once `approvals.min_approvals` approvals - * are in, the change is applied through the normal write pipeline with the request's base version - * as the expected version, so a setting that changed since the request was opened is never - * overwritten: the request becomes `stale` instead (and is returned, not thrown). An expired - * request is marked `expired` and refused. Returns the request as it now stands. + * Approve a change request; needs `approve` on its setting. With enough approvals the change is + * written against the request's base version, and a setting that moved on since makes the + * request `stale` instead. Returns the request as it now stands. */ final readonly class ApproveChange { diff --git a/src/Actions/Approvals/CancelChange.php b/src/Actions/Approvals/CancelChange.php index d4b04b3..940fe33 100644 --- a/src/Actions/Approvals/CancelChange.php +++ b/src/Actions/Approvals/CancelChange.php @@ -22,9 +22,7 @@ use Simtabi\Laranail\Settings\Exceptions\ChangeRequestClosed; use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; -/** - * Withdraw a change request: only its requester (or trusted code) may. Nothing is written. - */ +/** Withdraw a change request; only its requester or trusted code may. */ final readonly class CancelChange { public function __construct( diff --git a/src/Actions/Approvals/ProposeChange.php b/src/Actions/Approvals/ProposeChange.php index b85507b..fb4fdef 100644 --- a/src/Actions/Approvals/ProposeChange.php +++ b/src/Actions/Approvals/ProposeChange.php @@ -25,12 +25,8 @@ use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** - * Open a change request (§16.7): needs the ability of the write it proposes (`update` for a set, - * `forget`, `lock` or `unlock`). A proposed value is validated and encoded now, exactly as a write - * would store it, so an encrypted definition's value is encrypted at rest and an invalid value is - * refused at once rather than at approval. The request records the setting's current version as - * its base; applying it later checks that version. The request and its `pending` audit entry - * commit together. + * Open a change request; needs the ability of the write it proposes. The value is validated and + * encoded now, as a write would store it, so it is encrypted at rest and refused early when invalid. */ final readonly class ProposeChange { diff --git a/src/Actions/Approvals/PruneChanges.php b/src/Actions/Approvals/PruneChanges.php index 7256e49..0c99bd7 100644 --- a/src/Actions/Approvals/PruneChanges.php +++ b/src/Actions/Approvals/PruneChanges.php @@ -17,9 +17,8 @@ use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** - * Sweep the change requests of every connection a store uses: open requests past their expiry - * become `expired`, and decided requests untouched for `approvals.keep_days` are deleted. Needs - * `prune` (checked against the default store) and is audited. Returns [expired, deleted]. + * Expire overdue open change requests and delete decided ones older than `approvals.keep_days`, + * on every connection. Needs `prune`. */ final readonly class PruneChanges { diff --git a/src/Actions/Approvals/QueryChanges.php b/src/Actions/Approvals/QueryChanges.php index 1206a2f..97f5f02 100644 --- a/src/Actions/Approvals/QueryChanges.php +++ b/src/Actions/Approvals/QueryChanges.php @@ -14,9 +14,7 @@ use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** - * List a store's change requests, newest first. An actor holding `approve` on the store sees - * every request; any other actor sees only their own (so a requester can follow theirs). Trusted - * code sees every request. Payloads never leave the request ({@see ChangeRequest::toArray()}). + * List a store's change requests, newest first. An actor without `approve` sees only their own. */ final readonly class QueryChanges { diff --git a/src/Actions/Approvals/RejectChange.php b/src/Actions/Approvals/RejectChange.php index 31603b7..7a05d3c 100644 --- a/src/Actions/Approvals/RejectChange.php +++ b/src/Actions/Approvals/RejectChange.php @@ -22,10 +22,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\Definitions; use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; -/** - * Reject a change request (§16.7): needs `approve` on its setting. Nothing is written; the - * decision and its reason are recorded on the request and in the audit trail. - */ +/** Reject a change request; needs `approve` on its setting. */ final readonly class RejectChange { public function __construct( diff --git a/src/Actions/Categories/CategoryGuard.php b/src/Actions/Categories/CategoryGuard.php index 9b2e6af..24949d1 100644 --- a/src/Actions/Categories/CategoryGuard.php +++ b/src/Actions/Categories/CategoryGuard.php @@ -14,15 +14,12 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Support\AuditedTransaction; -use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** - * What every category change does around its work: authorize `manage_categories`, then run the - * change, its events and its audit entry in one transaction on the store's connection. A failure - * is audited after the rollback. Categories live in the database, so a store without an active - * database layer refuses the change with {@see StoreNotWritable}. + * Authorizes `manage_categories` and runs a category change, its events and its audit entry in + * one transaction on the store's connection. */ final readonly class CategoryGuard { @@ -35,7 +32,7 @@ public function __construct( * @template T * * @param Closure(CategoryRepository, DatabaseDriver): T $work - * @param list $also more events dispatched after `$after` (what exactly changed) + * @param list $also more events dispatched after `$after` * * @return T */ diff --git a/src/Actions/Categories/CreateCategory.php b/src/Actions/Categories/CreateCategory.php index c17a7cf..0380a69 100644 --- a/src/Actions/Categories/CreateCategory.php +++ b/src/Actions/Categories/CreateCategory.php @@ -12,10 +12,7 @@ use Simtabi\Laranail\Settings\Events\CategorySaving; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; -/** - * Create a category in a store, optionally under a parent of the same store: needs - * `manage_categories`. - */ +/** Create a category, optionally under a parent in the same store. */ final readonly class CreateCategory { public function __construct( diff --git a/src/Actions/Categories/DeleteCategory.php b/src/Actions/Categories/DeleteCategory.php index ae23fea..7ec82df 100644 --- a/src/Actions/Categories/DeleteCategory.php +++ b/src/Actions/Categories/DeleteCategory.php @@ -12,10 +12,7 @@ use Simtabi\Laranail\Settings\Events\CategoryDeleting; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; -/** - * Delete a category: needs `manage_categories`. Its children move to the top level and the - * settings in it keep their values but lose the category. - */ +/** Delete a category; its children move to the top level and its settings keep their values. */ final readonly class DeleteCategory { public function __construct( diff --git a/src/Actions/Categories/ListCategories.php b/src/Actions/Categories/ListCategories.php index bda515b..db5ee0a 100644 --- a/src/Actions/Categories/ListCategories.php +++ b/src/Actions/Categories/ListCategories.php @@ -12,7 +12,7 @@ use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; -/** A store's categories, by sort order then slug: needs `view` on the store. */ +/** List a store's categories by sort order, then slug. */ final readonly class ListCategories { public function __construct( diff --git a/src/Actions/Categories/MoveCategory.php b/src/Actions/Categories/MoveCategory.php index e8cff83..44610b9 100644 --- a/src/Actions/Categories/MoveCategory.php +++ b/src/Actions/Categories/MoveCategory.php @@ -10,15 +10,9 @@ use Simtabi\Laranail\Settings\Events\CategoryMoved; use Simtabi\Laranail\Settings\Events\CategorySaved; use Simtabi\Laranail\Settings\Events\CategorySaving; -use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; -use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; -/** - * Put a category under another of the same store, or at the top level with a null parent: - * needs `manage_categories`. A cycle raises {@see CategoryCycle}; a parent from another store - * raises {@see CategoryStoreMismatch}. - */ +/** Move a category under another in the same store, or to the top level with a null parent. */ final readonly class MoveCategory { public function __construct( diff --git a/src/Actions/Categories/RenameCategory.php b/src/Actions/Categories/RenameCategory.php index 36b430a..c8f743c 100644 --- a/src/Actions/Categories/RenameCategory.php +++ b/src/Actions/Categories/RenameCategory.php @@ -12,9 +12,7 @@ use Simtabi\Laranail\Settings\Events\CategoryRenamed; use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; -/** - * Give a category a new title (its slug, the identifier, stays): needs `manage_categories`. - */ +/** Give a category a new title; its slug stays. */ final readonly class RenameCategory { public function __construct( @@ -23,7 +21,6 @@ public function __construct( public function handle(Store $store, string $slug, string $title, ?Actor $actor = null): void { - // Validates the slug and the title the same way creation does. $input = new NewCategory($slug, $title); $events = [new CategorySaving($store->name->value, $slug), new CategorySaved($store->name->value, $slug)]; diff --git a/src/Actions/ClearCache.php b/src/Actions/ClearCache.php index e4cde60..e905c63 100644 --- a/src/Actions/ClearCache.php +++ b/src/Actions/ClearCache.php @@ -16,13 +16,8 @@ use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; /** - * Reset cached settings (design §7.5, `laranail::settings.clear-cache`): every bag, one store's, - * or one owner's in one store. Needs `manage_stores` when an actor is present, and is audited as - * a `manage_stores` entry naming what was reset. Values are never touched, only cached copies, - * so the next read of anything reset costs one query per store again. - * - * Resetting replaces generation tokens; nothing is deleted from the cache store, and the - * application's other cache entries are never touched. Returns false when caching is off. + * Reset cached settings for every store, one store, or one owner in a store. Returns false when + * caching is off. */ final readonly class ClearCache { diff --git a/src/Actions/Configuration/DeleteConfigurationEntry.php b/src/Actions/Configuration/DeleteConfigurationEntry.php index 08b92a6..3af6a3b 100644 --- a/src/Actions/Configuration/DeleteConfigurationEntry.php +++ b/src/Actions/Configuration/DeleteConfigurationEntry.php @@ -14,7 +14,7 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; -/** Remove a persisted store or layer (§16.11): needs `manage_stores`; audited. Returns whether one was there. */ +/** Remove a persisted store or layer; returns whether one existed. */ final readonly class DeleteConfigurationEntry { public function __construct( diff --git a/src/Actions/Configuration/DeleteDefinition.php b/src/Actions/Configuration/DeleteDefinition.php index 8f37546..f06ebe7 100644 --- a/src/Actions/Configuration/DeleteDefinition.php +++ b/src/Actions/Configuration/DeleteDefinition.php @@ -18,10 +18,7 @@ use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; -/** - * Delete a definition saved through the API (§16.11): needs `manage_definitions`; definitions from - * code or configuration are never deleted here. Audited. Returns whether one was there. - */ +/** Delete a definition saved through the API; returns whether one existed. */ final readonly class DeleteDefinition { public function __construct( diff --git a/src/Actions/Configuration/ListConfigurationEntries.php b/src/Actions/Configuration/ListConfigurationEntries.php index 81d5cb0..209a701 100644 --- a/src/Actions/Configuration/ListConfigurationEntries.php +++ b/src/Actions/Configuration/ListConfigurationEntries.php @@ -12,7 +12,7 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; -/** The valid persisted stores and layers (§16.11): needs `manage_stores`. */ +/** List the valid persisted stores and layers. */ final readonly class ListConfigurationEntries { public function __construct( diff --git a/src/Actions/Configuration/SaveConfigurationEntry.php b/src/Actions/Configuration/SaveConfigurationEntry.php index 609d9ed..a5f1677 100644 --- a/src/Actions/Configuration/SaveConfigurationEntry.php +++ b/src/Actions/Configuration/SaveConfigurationEntry.php @@ -15,10 +15,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; -/** - * Save a persisted store or layer (§16.11): needs `manage_stores` (step-up verification applies by - * default). Validated exactly like the configuration file before it is stored; audited. - */ +/** Save a persisted store or layer, validated like the configuration file. */ final readonly class SaveConfigurationEntry { public function __construct( diff --git a/src/Actions/Configuration/SaveDefinition.php b/src/Actions/Configuration/SaveDefinition.php index a20eb8d..c0d433f 100644 --- a/src/Actions/Configuration/SaveDefinition.php +++ b/src/Actions/Configuration/SaveDefinition.php @@ -22,10 +22,8 @@ use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; /** - * Save a definition through the API (§16.11, D-6) into the definitions table, from the same - * attributes the configuration file takes (`type`, `default`, `rules`, `encrypted`, …): needs - * `manage_definitions`; validated by the definition builder (a type must be a registered caster), - * refused for a key code or configuration defines, audited. Reads see it at once. + * Save a definition into the definitions table from the attributes the configuration file takes. + * A key already defined in code or configuration is refused. */ final readonly class SaveDefinition { diff --git a/src/Actions/DiagnoseSettings.php b/src/Actions/DiagnoseSettings.php index 1462087..af51863 100644 --- a/src/Actions/DiagnoseSettings.php +++ b/src/Actions/DiagnoseSettings.php @@ -18,22 +18,19 @@ use Simtabi\Laranail\Package\Tools\Services\Doctor\DoctorResult; use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; +use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; /** - * What `laranail::settings.doctor` reports, per store with a database layer: readiness (the - * connection answers and the tables exist), schema drift (columns this release reads that the - * tables lack), scopes naming a class instead of a morph alias or an alias the store does not - * list (G-6, G-30), rows whose category belongs to another store (G-33), encrypted values no key - * can read any more (§6), open change requests past their expiry (§16.7) and persisted - * configuration entries that were skipped as invalid (§16.11). Read-only. + * The findings of `laranail::settings.doctor`. Read-only. * - * Schema drift is three comparisons (§4.0): the schema file against the configuration (a switch - * changed after migrating changes nothing until a migration does), the file's shape version - * against this release's (an upgrade migration that was never published), and the live tables - * against the recorded shape (missing columns fail; columns the shape does not have, such as - * `deleted_at` on a store without soft deletes, warn). + * Per store with a database layer: readiness, schema drift, scopes that name a class or an alias + * the store does not list, category links to another store, keys outside their category, + * encrypted values no key can read, and overdue change requests. Then: every code or config + * definition whose key sits outside its category, and persisted configuration entries skipped as + * invalid. Schema drift compares the schema file with configuration, its shape version with this + * release's, and the live tables with the recorded shape. */ final readonly class DiagnoseSettings { @@ -57,6 +54,7 @@ public function __construct( private SchemaShapeRepository $shapes, private LaravelValueEncrypter $encrypter, private PersistedConfiguration $persisted, + private DefinitionRegistry $definitions, ) {} /** @return list */ @@ -85,6 +83,7 @@ public function handle(): array $findings[] = $this->drift($store, $database); $findings[] = $this->scopes($store, $database); $findings[] = $this->categories($store, $database); + $findings[] = $this->categoryKeys($store, $database); $findings[] = $this->encryption($store, $database, $this->encrypter); @@ -93,6 +92,8 @@ public function handle(): array } } + $findings[] = $this->definitionCategories(); + $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).') @@ -320,4 +321,30 @@ private function categories(Store $store, DatabaseDriver $database): Finding ? DoctorResult::pass('Every category link stays inside the store.') : DoctorResult::fail(sprintf('%d row(s) point at a category of another store.', $count))); } + + /** Values whose key does not start with their category's slug: a warning, not a failure. */ + private function categoryKeys(Store $store, DatabaseDriver $database): Finding + { + $keys = new SchemaInspector($database)->keysOutsideTheirCategory($store->name); + + return new Finding("{$store->name}: category keys", 'Each key starts with its category\'s slug', $keys === [] + ? DoctorResult::pass('Every categorised key starts with its category\'s slug.') + : DoctorResult::warn(sprintf('%d key(s) do not start with their category\'s slug: %s', count($keys), implode(', ', $keys)), ['keys' => $keys])); + } + + /** Code and config definitions whose key does not start with their category's slug. */ + private function definitionCategories(): Finding + { + $keys = []; + + foreach ($this->definitions->all() as $definition) { + if ($definition->category !== null && $definition->key->group() !== $definition->category) { + $keys[] = sprintf('%s:%s (%s)', $definition->store, $definition->key, $definition->category); + } + } + + return new Finding('definitions: category keys', 'Each defined key starts with its category\'s slug', $keys === [] + ? DoctorResult::pass('Every categorised definition starts with its category\'s slug.') + : DoctorResult::warn(sprintf('%d definition(s) do not start with their category\'s slug: %s', count($keys), implode(', ', $keys)), ['keys' => $keys])); + } } diff --git a/src/Actions/DiffHistory.php b/src/Actions/DiffHistory.php index 7e324d2..6352d46 100644 --- a/src/Actions/DiffHistory.php +++ b/src/Actions/DiffHistory.php @@ -17,11 +17,8 @@ use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** - * The value of one setting at two versions: needs `view_history`. A value that is encrypted, or - * whose definition is sensitive, is decrypted only for an actor holding `view_sensitive` (or a - * trusted call without an actor, which reads every value as `get()` does); anyone else gets a - * redacted diff that says only whether the stored payloads differ. Nothing is decrypted before - * that decision. + * Compare one setting at two versions. Sensitive values are decrypted only for an actor with + * `view_sensitive`; anyone else gets a redacted diff saying only whether they differ. */ final readonly class DiffHistory { diff --git a/src/Actions/FindForeignTables.php b/src/Actions/FindForeignTables.php index 18748ff..22a6588 100644 --- a/src/Actions/FindForeignTables.php +++ b/src/Actions/FindForeignTables.php @@ -9,11 +9,8 @@ use Simtabi\Laranail\Settings\Services\Database\SchemaInspector; /** - * The tables `install` would create that already exist and are not this package's (D-4). A bare - * `settings` table is a plausible collision with an application's own; installing over it would - * fail half-way or, worse, write into it. A table is recognised as the package's by the columns - * only it has. A database that cannot be reached is not reported: there is nothing to collide - * with yet. + * Find the tables `install` would create that already exist and are not this package's, + * recognised by columns only the package's tables have. */ final readonly class FindForeignTables { @@ -48,7 +45,7 @@ public function handle(): array $inspector = new SchemaInspector($database); foreach ($tables as $table => $signature) { - // Unreachable (null): nothing exists to collide with. + // An unreachable database has nothing to collide with. $columns = $inspector->hasTable($table) === true ? $inspector->columns($table) : null; if ($columns !== null && array_diff($signature, $columns) !== []) { diff --git a/src/Actions/FindOrphans.php b/src/Actions/FindOrphans.php index 519b130..5f47bc3 100644 --- a/src/Actions/FindOrphans.php +++ b/src/Actions/FindOrphans.php @@ -12,11 +12,8 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; /** - * Find the settings of owners that no longer exist (G-7): rows left by bulk deletes, which fire - * no model events. For each store's owner aliases it lists the owner scopes in the database - * layer and asks the aliased model which ids still exist, soft-deleted ones included (a - * soft-deleted owner keeps its settings for a restore). An alias with no model in the morph map - * is reported, never guessed at. Read-only; {@see PruneOrphans} removes what it finds. + * Find settings whose owner no longer exists, such as rows left by bulk deletes. Soft-deleted + * owners keep their settings, and aliases missing from the morph map are reported, not guessed. */ final readonly class FindOrphans { diff --git a/src/Actions/FlushScope.php b/src/Actions/FlushScope.php index 67b22ca..6c077a2 100644 --- a/src/Actions/FlushScope.php +++ b/src/Actions/FlushScope.php @@ -19,12 +19,7 @@ use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Services\Access\AccessGuard; -/** - * Remove every value an owner holds in a store, from every writable layer: needs `forget`. Used - * when an owner is deleted (G-7) and by `prune-orphans`. The removal and its audit entry share - * one transaction on the store's connection; the scope's cached bag is forgotten when it commits. - * Returns how many rows went. - */ +/** Remove every value an owner holds in a store; returns the number of rows removed. */ final readonly class FlushScope { public function __construct( @@ -53,8 +48,7 @@ public function handle(Store $store, OwnerRef $owner, ?Actor $actor = null): int : $this->forgetEach($store, $layer->driver, $scope); } - // The rows went straight to the database, past the cache: forget the scope's bag - // once this transaction commits. + // The delete bypassed the cache, so drop the scope's bag after commit. $store->forgetCached($scope); $this->access->auditor()->record(AuditAction::Forget, AuditOutcome::Allowed, $subject, $actor, meta: ['flushed' => $removed]); diff --git a/src/Actions/ForgetSetting.php b/src/Actions/ForgetSetting.php index dc41947..214ee48 100644 --- a/src/Actions/ForgetSetting.php +++ b/src/Actions/ForgetSetting.php @@ -12,10 +12,7 @@ use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; -/** - * Remove a scope's own value so reads fall through again: needs `forget` (and `override_lock` - * over a locked row the store lets be overridden). - */ +/** Remove a scope's own value so reads fall through to the next scope or layer. */ final readonly class ForgetSetting { public function __construct( diff --git a/src/Actions/LockSetting.php b/src/Actions/LockSetting.php index 9d27973..7923a71 100644 --- a/src/Actions/LockSetting.php +++ b/src/Actions/LockSetting.php @@ -12,9 +12,7 @@ use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; -/** - * Lock one scope's row against writes: needs `lock`. - */ +/** Lock one scope's row against writes. */ final readonly class LockSetting { public function __construct( diff --git a/src/Actions/MakeStore.php b/src/Actions/MakeStore.php index 4e37fdc..018c333 100644 --- a/src/Actions/MakeStore.php +++ b/src/Actions/MakeStore.php @@ -14,17 +14,9 @@ use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** - * Generate a new database store (G-3: no runtime DDL): one migration for it, a copy of the - * package's migration (`create_laranail_settings_tables.php`) with its `$only` line naming the - * store and, with a connection, its `$pinnedConnection` line naming that connection. The copy - * creates the store's values table and, on a connection of its own, that connection's categories - * and audit tables (each connection keeps its own). Returns the file written and the - * configuration entry to add by hand. - * - * The store's shape (mode, soft deletes, owner table) is recorded in the schema file (§4.0): - * taken from its configuration entry when it has one, else the default polymorphic shape on the - * given connection. The file's switches (key type, identity, translations, tenancy) are kept, so - * the new table's `category_id` always matches the categories key it points at. + * Generate the migration for a new database store: a copy of the package migration with its + * `$only` (and optionally `$pinnedConnection`) line rewritten, and record the store's shape. + * Returns the file written and the configuration entry to add. */ final readonly class MakeStore { @@ -36,8 +28,7 @@ private const string CONNECTION_LINE = 'private ?string $pinnedConnection = null;'; /** - * @param string $migration the package migration file make-store copies (a directory, as - * before 0.1's single migration, means that directory's copy of it) + * @param string $migration the package migration file to copy, or a directory holding it * @param string $migrations the application's migrations directory */ public function __construct( diff --git a/src/Actions/MigrateSettings.php b/src/Actions/MigrateSettings.php index 41812fe..8af7fbd 100644 --- a/src/Actions/MigrateSettings.php +++ b/src/Actions/MigrateSettings.php @@ -24,13 +24,9 @@ use Simtabi\Laranail\Settings\Services\Definitions\Definitions; /** - * Run one settings migration step (G-17): rename or move a key across every owner and locale, - * delete it everywhere, or add a global value. Values are read and written through the value - * pipeline (so a value is re-validated, re-cast and re-encrypted under the destination's - * definition), with history; locks move with them. A migration is deploy-time code, so it writes - * past approvals the way trusted code does, needs `manage_definitions` when given an actor, and is - * audited once per step. On a database store every scope is migrated; on a file-only store, the - * global value. Returns how many values it touched. + * Run one settings migration step: rename, move or delete a key across every owner and locale, + * or add a global value. Values are re-validated and re-encrypted under the destination's + * definition. Returns how many values it touched. */ final readonly class MigrateSettings { diff --git a/src/Actions/PromoteStore.php b/src/Actions/PromoteStore.php index 0fc8c7d..6d51c78 100644 --- a/src/Actions/PromoteStore.php +++ b/src/Actions/PromoteStore.php @@ -30,17 +30,8 @@ use Simtabi\Laranail\Settings\Services\Definitions\Definitions; /** - * Promote a store's runtime file into its database layer (design §7.4): needs `promote`. - * - * Only what was written at runtime is copied; the shipped layer is never read, so a later - * release can still change a shipped default (G-28). Each record goes through the value - * pipeline again (validated, re-encrypted under the current key). A key that already has a - * database row is skipped unless forced, as is a key a strict store no longer defines. The - * records and the audit entry commit together; the runtime file is then archived as - * `.promoted-.json`, so a second run finds nothing and is a no-op. - * - * A cache lock (the cache store's atomic lock) keeps two promotions of one store apart. On a - * node-local cache store that protects one node only; multi-node installs need a shared one. + * Copy a store's runtime file into its database layer, then archive the file as + * `.promoted-.json`. Keys that already have a database row are skipped unless forced. */ final readonly class PromoteStore { @@ -102,7 +93,7 @@ private function promote(Store $store, PromotionRequest $request, ?Actor $actor, ]], ); - // Promoted rows were written past the cache: reset the store's bags. + // The rows bypassed the cache, so reset the store's bags. $store->forgetCachedStore(); $archive = $request->from === null ? $runtime->archive($store->name, CarbonImmutable::now()) : null; @@ -161,7 +152,7 @@ private function copy(Store $store, PromotionRequest $request, DatabaseDriver $d return [$promoted, $skipped]; } - /** The first writable JSON layer: where values written before the database existed live. */ + /** The first writable JSON layer. */ private function runtime(Store $store): ?JsonDriver { foreach ($store->layers as $layer) { diff --git a/src/Actions/PruneAudit.php b/src/Actions/PruneAudit.php index f2dce56..785452c 100644 --- a/src/Actions/PruneAudit.php +++ b/src/Actions/PruneAudit.php @@ -18,12 +18,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Database\AuditRepository; -/** - * Delete audit rows older than `audit.keep_days` from the audit table of every connection a - * store uses. Returns the number of rows removed. With an actor it needs `prune` (checked - * against the default store); the prune itself is audited, so the trail records who shortened - * it. - */ +/** Delete audit rows older than `audit.keep_days` on every connection; returns the number removed. */ final readonly class PruneAudit { public function __construct( diff --git a/src/Actions/PruneHistory.php b/src/Actions/PruneHistory.php index 437136f..a75b704 100644 --- a/src/Actions/PruneHistory.php +++ b/src/Actions/PruneHistory.php @@ -19,11 +19,8 @@ use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** - * Apply the history retention policy (G-29) to the history table of every connection a store - * uses: drop entries older than `history.keep_days`, and entries more than - * `history.keep_versions` versions behind their setting's newest. Either rule may be off (null), - * not both. Needs `prune` when an actor is present (checked against the default store); the prune - * is audited, so the trail records who shortened the history. Returns the number removed. + * Delete history entries older than `history.keep_days` or more than `history.keep_versions` + * behind their setting's newest, on every connection. Returns the number removed. */ final readonly class PruneHistory { diff --git a/src/Actions/PruneOrphans.php b/src/Actions/PruneOrphans.php index 8ba85c8..db51d7f 100644 --- a/src/Actions/PruneOrphans.php +++ b/src/Actions/PruneOrphans.php @@ -14,12 +14,7 @@ use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -/** - * Remove the settings of owners that no longer exist (G-7), as {@see FindOrphans} finds them. - * - * Removing needs `prune` when an actor is present (and, per owner, the `forget` that flushing - * needs); the run is audited as one `prune` entry besides the per-owner `forget` entries. - */ +/** Remove the settings of owners that no longer exist, as {@see FindOrphans} finds them. */ final readonly class PruneOrphans { public function __construct( @@ -30,9 +25,7 @@ public function __construct( private Dispatcher $events, ) {} - /** - * Remove every orphan's settings; returns the number of rows removed. - */ + /** Remove every orphan's settings; returns the number of rows removed. */ public function handle(?Actor $actor = null): int { $subject = new Subject($this->stores->default()->name); diff --git a/src/Actions/QueryAudit.php b/src/Actions/QueryAudit.php index d5a263e..1d0a8b2 100644 --- a/src/Actions/QueryAudit.php +++ b/src/Actions/QueryAudit.php @@ -19,12 +19,7 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Database\AuditRepository; -/** - * Read the audit trail (§16.8): needs `view_audit` when an actor is present (a trusted call - * without one reads freely unless an actor is required). Entries come from the audit table on - * the connection of the filtered store (the default store when none is named), newest first. - * Entries never carry a value, so there is nothing to redact. - */ +/** Read the audit trail of the filtered store, or the default store, newest first. */ final readonly class QueryAudit { public function __construct( @@ -50,7 +45,7 @@ public function cursor(AuditFilter $filter, ?Actor $actor = null): LazyCollectio return $this->query($filter, $actor)->cursor()->map(fn (object $row): AuditEntry => $this->entry((array) $row)); } - /** One page, newest first; pass the page's `nextCursor` back for the next one. */ + /** One page; pass its `nextCursor` back for the next. */ public function paginate(AuditFilter $filter, ?Actor $actor = null, int $perPage = 50, ?string $cursor = null): AuditPage { $page = $this->query($filter, $actor)->cursorPaginate(max(1, $perPage), ['*'], 'cursor', $cursor === null ? null : Cursor::fromEncoded($cursor)); diff --git a/src/Actions/QueryHistory.php b/src/Actions/QueryHistory.php index f0c2297..9795991 100644 --- a/src/Actions/QueryHistory.php +++ b/src/Actions/QueryHistory.php @@ -15,12 +15,7 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; -/** - * Read the value history (§4.3): needs `view_history` when an actor is present (a trusted call - * without one reads freely unless an actor is required). Returns the query for the filtered - * store (the default store when none is named), newest version first; the entry point maps and - * redacts its rows. - */ +/** Build the value history query for the filtered store, or the default store. */ final readonly class QueryHistory { public function __construct( diff --git a/src/Actions/Reads/ExplainSetting.php b/src/Actions/Reads/ExplainSetting.php index c7c8c4c..00dd931 100644 --- a/src/Actions/Reads/ExplainSetting.php +++ b/src/Actions/Reads/ExplainSetting.php @@ -10,7 +10,7 @@ use Simtabi\Laranail\Settings\Resolution\Explanation; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; -/** How a read resolves (§7.2), for a channel other than PHP: the same handle's `explain()`. */ +/** Explain how a read resolves, through the handle's `explain()`. */ final readonly class ExplainSetting { public function __construct( diff --git a/src/Actions/Reads/ListDefinitions.php b/src/Actions/Reads/ListDefinitions.php index d9ee0d2..31cbdb3 100644 --- a/src/Actions/Reads/ListDefinitions.php +++ b/src/Actions/Reads/ListDefinitions.php @@ -13,11 +13,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Services\Definitions\DatabaseDefinitions; -/** - * A store's definitions (code, configuration and the definitions table; D-6), in key order, for - * UIs and API clients: needs `view` on the store. A definition never carries a value, but an - * encrypted one's default stays in code and is left out. - */ +/** List a store's definitions in key order; an encrypted definition's default is left out. */ final readonly class ListDefinitions { public function __construct( diff --git a/src/Actions/Reads/ListStores.php b/src/Actions/Reads/ListStores.php index 6876222..ecbf9a9 100644 --- a/src/Actions/Reads/ListStores.php +++ b/src/Actions/Reads/ListStores.php @@ -11,7 +11,7 @@ use Simtabi\Laranail\Settings\Services\Access\AccessGuard; use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; -/** The configured stores an actor may view (every one for trusted code). */ +/** List the configured stores the actor may view. */ final readonly class ListStores { public function __construct( diff --git a/src/Actions/Reads/ReadHistory.php b/src/Actions/Reads/ReadHistory.php index 273fe75..f8f6840 100644 --- a/src/Actions/Reads/ReadHistory.php +++ b/src/Actions/Reads/ReadHistory.php @@ -10,11 +10,7 @@ use Simtabi\Laranail\Settings\Data\SettingAddress; use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; -/** - * A page of one setting's history (§4.3), for a channel other than PHP: the same handle's - * `history()`, so `view_history` applies and a sensitive value is removed for an actor who may not - * see it, as in PHP. - */ +/** Read a page of one setting's history through the handle's `history()`. */ final readonly class ReadHistory { public function __construct( diff --git a/src/Actions/Reads/ReadSetting.php b/src/Actions/Reads/ReadSetting.php index 01acdf1..2d79d45 100644 --- a/src/Actions/Reads/ReadSetting.php +++ b/src/Actions/Reads/ReadSetting.php @@ -12,10 +12,8 @@ use Simtabi\Laranail\Settings\Services\Resolution\SettingTargets; /** - * Read one setting for a channel other than PHP (§16.2): through the same settings handle the PHP - * API uses, so `view` and `view_sensitive` apply exactly as they do there, plus the version of the - * address's own row for the ETag. A sensitive value the actor may not see is redacted, not - * refused, when the actor may still view the key. + * Read one setting through the settings handle, with its row version for the ETag. A sensitive + * value the actor may not see is redacted rather than refused. */ final readonly class ReadSetting { diff --git a/src/Actions/Reads/ReadSettings.php b/src/Actions/Reads/ReadSettings.php index f584d53..f4049bd 100644 --- a/src/Actions/Reads/ReadSettings.php +++ b/src/Actions/Reads/ReadSettings.php @@ -14,10 +14,8 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** - * A page of an owner's (or the global) settings, for a channel other than PHP: every key the - * scope holds in any layer of the store, or that a definition of the store names, in key order, - * each read through the settings handle. A key the actor may not view is left out, not masked - * (§16.10). `$after` is the last key of the previous page. + * Read a page of a scope's settings in key order, leaving out keys the actor may not view. + * `$after` is the last key of the previous page. */ final readonly class ReadSettings { diff --git a/src/Actions/ReencryptSettings.php b/src/Actions/ReencryptSettings.php index c2d7e83..fd06c3c 100644 --- a/src/Actions/ReencryptSettings.php +++ b/src/Actions/ReencryptSettings.php @@ -18,13 +18,8 @@ use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** - * Re-encrypt every encrypted value under the current key after a key rotation (§6): live rows - * (every tenant's, trashed ones too), the history's old and new values, and pending change - * requests, on every connection a database store uses. Each payload is decrypted with the current - * or a previous key (`APP_PREVIOUS_KEYS`) and encrypted again with the current one; one that no - * key can read is counted as failed and left untouched, so the run never destroys a value. Needs - * `manage_stores` (step-up verification applies by default) and is audited; the cached values of - * every store it touched are forgotten. + * Re-encrypt every encrypted value, history payload and pending change request under the current + * key after a key rotation. A payload no key can read is counted as failed and left untouched. */ final readonly class ReencryptSettings { @@ -63,7 +58,7 @@ public function handle(?Actor $actor = null): array $totals['failed'] += $failed; $store->forgetCachedStore(); - // The history and change requests tables are per connection, so once each. + // The history and change requests tables are per connection. if (isset($connections[$database->connectionName()])) { continue; } diff --git a/src/Actions/RescopeOwners.php b/src/Actions/RescopeOwners.php index d7e72ed..c9de0d9 100644 --- a/src/Actions/RescopeOwners.php +++ b/src/Actions/RescopeOwners.php @@ -19,12 +19,8 @@ use Simtabi\Laranail\Settings\Services\Database\ChangeRequestRepository; /** - * Rename an owner alias in stored settings (G-30), after the application renamed it in its morph - * map: every scope `:` becomes `:` in every database store (with `settable_type` - * and per-row slugs), in the history and in change requests, in chunks (G-44). `$from` may be a - * class name, which is how rows written before the alias allow-list look (G-6). The audit trail is - * left as it was: it records what happened under the old name. Needs `manage_stores`; audited. - * Update the stores' `owners` lists to the new alias as well. + * Rename an owner alias in stored values, history and change requests after the application + * renamed it in its morph map. `$from` may be a class name. The audit trail is left unchanged. */ final readonly class RescopeOwners { diff --git a/src/Actions/RollbackSetting.php b/src/Actions/RollbackSetting.php index 7025ff2..a6cf09c 100644 --- a/src/Actions/RollbackSetting.php +++ b/src/Actions/RollbackSetting.php @@ -18,12 +18,8 @@ use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** - * Return a setting to the value it held at an earlier version: needs `rollback` (step-up - * verification applies when `verification.abilities` lists it, which it does by default), and - * `override_lock` over a locked row the store lets be overridden. The old value is read back from - * the history, decrypted and decoded, and written as a new version through the normal write - * pipeline (validation, casting, encryption, the version check against the current row, history - * and audit), so a rollback is itself a change that can be rolled back. Returns the new version. + * Write a setting's value from an earlier version as a new version, through the normal write + * pipeline. Returns the new version. */ final readonly class RollbackSetting { diff --git a/src/Actions/SetSetting.php b/src/Actions/SetSetting.php index 16927fa..b8270b0 100644 --- a/src/Actions/SetSetting.php +++ b/src/Actions/SetSetting.php @@ -12,11 +12,7 @@ use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; -/** - * Store a value: needs `update` (and `override_lock` over a locked row the store lets be - * overridden). Shared by the PHP API and, later, the console and REST channels. A write naming - * the version it expects is checked against it and never retried. - */ +/** Store a value. A write naming an expected version is checked against it and never retried. */ final readonly class SetSetting { public function __construct( diff --git a/src/Actions/SyncDefinitions.php b/src/Actions/SyncDefinitions.php index 41de494..bebb751 100644 --- a/src/Actions/SyncDefinitions.php +++ b/src/Actions/SyncDefinitions.php @@ -19,12 +19,9 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** - * Copy every code and config definition into the definitions table as an `is_system` row (D-6, - * §4.4), so UIs can list them; remove system rows whose definition is gone. Rows edited at - * runtime (not `is_system`) are never touched; one that shares a key with a code definition is - * reported as a conflict, because code wins in the merge. Needs `manage_definitions` when an - * actor is present; audited. Stores without an active database layer, or a schema without the - * table, are skipped. + * Copy code and config definitions into the definitions table as system rows and remove system + * rows whose definition is gone. Runtime rows are never touched; one sharing a key with a code + * definition is reported as a conflict. * * @phpstan-type SyncReport array{synced: int, removed: int, conflicts: list, skipped: list} */ diff --git a/src/Actions/Transfer/DiffStore.php b/src/Actions/Transfer/DiffStore.php index 9dee1bb..e4f7f31 100644 --- a/src/Actions/Transfer/DiffStore.php +++ b/src/Actions/Transfer/DiffStore.php @@ -13,11 +13,7 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Services\Transfer\StoreSnapshots; -/** - * Compare a store with an export file (G-42): which identities an import would add, which the - * store holds that the file does not, and which differ. Needs `export` (it reads the whole store); - * the result never carries a value. - */ +/** Compare a store with an export file, without exposing any value. */ final readonly class DiffStore { public function __construct( diff --git a/src/Actions/Transfer/ExportStore.php b/src/Actions/Transfer/ExportStore.php index f48b3f5..3828147 100644 --- a/src/Actions/Transfer/ExportStore.php +++ b/src/Actions/Transfer/ExportStore.php @@ -15,11 +15,7 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; use Simtabi\Laranail\Settings\Services\Transfer\StoreSnapshots; -/** - * Export a store's settings and categories (G-10, G-42): needs `export`, and `view_sensitive` too - * for decrypted values. Encrypted values are redacted unless the request asks for their - * ciphertext or plaintext. Audited (the mode and how many settings, never a value). - */ +/** Export a store's settings and categories; encrypted values are redacted unless asked for. */ final readonly class ExportStore { public function __construct( diff --git a/src/Actions/Transfer/ImportStore.php b/src/Actions/Transfer/ImportStore.php index a85e24a..a350dd0 100644 --- a/src/Actions/Transfer/ImportStore.php +++ b/src/Actions/Transfer/ImportStore.php @@ -34,13 +34,8 @@ use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** - * Import an export file (G-42) or an importer's document (G-43): needs `import` (step-up - * verification applies by default). A dry run unless the request says apply. Categories are - * created first, by slug, parents before children; then each setting is written through the - * normal write pipeline as the actor (validation, casting, encryption, history, one audit row per - * key), so a setting that needs approval opens a change request instead. All of it runs in one - * transaction: one failed write leaves the store as it was. Redacted values are skipped; locks and - * system categories are applied only when the request is trusted (G-10). + * Import an export or importer document in one transaction, as a dry run unless the request + * applies it. Locks and system categories in the document apply only to a trusted import. */ final readonly class ImportStore { @@ -172,7 +167,7 @@ private function categoriesToCreate(array $incoming, array $existing): array while ($pending !== []) { $ready = array_values(array_filter($pending, static fn (ExportedCategory $category): bool => ! $category->parent instanceof CategorySlug || isset($known[$category->parent->value]))); - // A parent the file names but does not hold: create the child at the top level. + // The parent is missing from the file, so create the child at the top level. $ready = $ready === [] ? [array_shift($pending)] : $ready; foreach ($ready as $category) { diff --git a/src/Actions/UnlockSetting.php b/src/Actions/UnlockSetting.php index 12f0383..f84b12e 100644 --- a/src/Actions/UnlockSetting.php +++ b/src/Actions/UnlockSetting.php @@ -12,9 +12,7 @@ use Simtabi\Laranail\Settings\Enums\ChangeOperation; use Simtabi\Laranail\Settings\Services\Stores\SettingWriter; -/** - * Unlock one scope's row against writes: needs `unlock`. - */ +/** Unlock one scope's row. */ final readonly class UnlockSetting { public function __construct( diff --git a/src/Actions/WarmCache.php b/src/Actions/WarmCache.php index fe1328f..9a40bea 100644 --- a/src/Actions/WarmCache.php +++ b/src/Actions/WarmCache.php @@ -15,14 +15,8 @@ use Simtabi\Laranail\Settings\Services\Access\AccessGuard; /** - * Load one scope's bag into the cache ahead of the first read (design §7.5, - * `laranail::settings.warm`): the global scope by default, or one owner's. One query per cached - * database layer on a miss, none when the bag is already cached. Needs `manage_stores` when an - * actor is present and is audited as a `manage_stores` entry. Returns how many records the bag - * holds (0 when the store is not cached). - * - * The bag is the scope's whole set of rows, not only its `autoload` rows: a bag is answered as - * complete, so a partial one would turn a non-autoload value into a miss. + * Load one scope's bag into the cache ahead of the first read. Returns how many records the bag + * holds, or 0 when the store is not cached. */ final readonly class WarmCache { diff --git a/src/Actions/WriteGuard.php b/src/Actions/WriteGuard.php index be4e2a5..b4e7284 100644 --- a/src/Actions/WriteGuard.php +++ b/src/Actions/WriteGuard.php @@ -19,14 +19,8 @@ use Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange; /** - * What every write action does around its write, in this order: authorize the ability (or - * check that an actor is not required), turn a write to a setting that needs approval into a - * change request (or refuse it where the store cannot hold one), decide whether a - * locked row may be overridden, run the write, and audit the outcome. Denials are audited by - * the {@see AccessGuard}; failures and successes here. An allowed write and its audit entry run - * in one transaction on the store's database connection (when it has one), so a failed audit - * insert rolls the write back; failures are audited after the rollback. Values never reach the - * audit. + * Wraps every write: authorize, open a change request when approval is needed, decide lock + * overrides, run the write and audit it in one transaction. */ final readonly class WriteGuard { @@ -39,7 +33,7 @@ public function __construct( /** * @param bool $respectsLocks whether a locked row stops this write (set and forget, not lock and unlock) * @param Closure(bool): array{?int, ?int} $write runs the write (told whether to override a lock); returns [version before, version after] - * @param ?ChangeProposal $proposal the change request to open instead, when the setting needs approval (§16.7) + * @param ?ChangeProposal $proposal the change request to open instead, when the setting needs approval * * @return ?ChangeRequest the change request opened instead of writing, or null when the write ran */ @@ -51,7 +45,6 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $this->access->authorize($actor, $ability, $subject); if ($subject->requiresApproval) { - // A store that can hold change requests turns the write into one (§16.7). if ($proposal instanceof ChangeProposal && $target->store->acceptsChangeRequests()) { return $this->proposer->handle($proposal, $actor); } @@ -65,7 +58,6 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $override = $respectsLocks && $this->mayOverrideLock($target, $actor); - // The write and its audit row commit together: an audit failure rolls the write back. new AuditedTransaction($this->access)->run( $target->store, $action, @@ -79,10 +71,7 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool return null; } - /** - * A locked row may be written only by an actor holding `override_lock` on a store whose - * locks are overridable. Anything else leaves the lock to refuse the write, as before. - */ + /** Whether the actor may write over a lock: `override_lock` on a store with overridable locks. */ private function mayOverrideLock(SettingTarget $target, ?Actor $actor): bool { if (! $actor instanceof Actor || $actor->isSystem() || ! $target->store->locksOverridable) { @@ -99,7 +88,7 @@ private function mayOverrideLock(SettingTarget $target, ?Actor $actor): bool return false; } - // Allowed: enforce it properly, so step-up verification and auditing of a refusal apply. + // Enforce again so step-up verification and refusal auditing apply. $this->access->authorize($actor, Ability::OverrideLock, $subject); return true; diff --git a/src/Approvals/Approvals.php b/src/Approvals/Approvals.php index 42a5e0e..086d5b7 100644 --- a/src/Approvals/Approvals.php +++ b/src/Approvals/Approvals.php @@ -24,9 +24,9 @@ use Simtabi\Laranail\Settings\Exceptions\UnknownChangeRequest; /** - * The change requests of one store (§16.7), as the handle's actor: list them (`->pending()`, - * `->status()`, `->key()`, `->for($owner)`, then `->get()`), and approve, reject or cancel one by - * id. Immutable: every narrowing returns a new query. + * The change requests of one store, seen as the handle's actor. Narrow with `pending()`, + * `status()`, `key()` or `for($owner)`, then `get()`; approve, reject or cancel one by id. + * Every narrowing returns a new instance. */ final readonly class Approvals { diff --git a/src/Audit/AuditQuery.php b/src/Audit/AuditQuery.php index 3a0f99b..ee0dd1c 100644 --- a/src/Audit/AuditQuery.php +++ b/src/Audit/AuditQuery.php @@ -21,8 +21,7 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; /** - * `$settings->audit()`: an immutable query over the audit trail. Each condition returns a new - * query; `get()`, `cursor()` and `paginate()` run it through {@see QueryAudit}, which checks + * An immutable query over the audit trail, returned by `$settings->audit()`. Running it checks * `view_audit` for the handle's actor. Entries hold actions and identifiers, never values. * * $settings->as($admin)->audit()->for($user)->key('mail.from_address') diff --git a/src/Audit/DatabaseAuditSink.php b/src/Audit/DatabaseAuditSink.php index 0625dee..f179ade 100644 --- a/src/Audit/DatabaseAuditSink.php +++ b/src/Audit/DatabaseAuditSink.php @@ -13,10 +13,8 @@ use Simtabi\Laranail\Settings\Services\Database\AuditRepository; /** - * Writes each audit entry as a row of `settings_audit` on the connection of the entry's store - * (or of the default store, for entries without one), so an allowed write and its audit row - * share one transaction: if the audit insert fails, the write rolls back. The row has no value - * column; entries never carry one. + * Writes audit entries to the audit table on the connection of the entry's store (or the default + * store). The write and its audit row share a transaction, so a failed insert rolls the write back. */ final readonly class DatabaseAuditSink implements AuditSink { diff --git a/src/Audit/InMemoryAuditSink.php b/src/Audit/InMemoryAuditSink.php index a8a9144..cc21025 100644 --- a/src/Audit/InMemoryAuditSink.php +++ b/src/Audit/InMemoryAuditSink.php @@ -7,10 +7,7 @@ use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Contracts\AuditSink; -/** - * Keeps entries in memory for the current process: used by `Settings::fake()` and by tests that - * assert on the audit trail. - */ +/** Keeps audit entries in memory, for `Settings::fake()` and tests. */ final class InMemoryAuditSink implements AuditSink { /** @var list */ diff --git a/src/Audit/LogAuditSink.php b/src/Audit/LogAuditSink.php index 06d2c18..8b4b09f 100644 --- a/src/Audit/LogAuditSink.php +++ b/src/Audit/LogAuditSink.php @@ -6,12 +6,10 @@ use Psr\Log\LoggerInterface; use Simtabi\Laranail\Settings\Data\AuditEntry; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Contracts\AuditSink; -/** - * Writes each audit entry to the package's log channel at `info`, so `logging.channel` and - * `logging.level` apply to it too. - */ +/** Writes audit entries to the package's operational log at `info`. */ final readonly class LogAuditSink implements AuditSink { public function __construct( @@ -22,7 +20,10 @@ public function record(AuditEntry $entry): void { $this->logger->info( sprintf('laranail/settings audit: %s %s', $entry->action->value, $entry->outcome->value), - $entry->toArray(), + LogContext::of($entry->store, $entry->key, $entry->scope, channel: $entry->channel->value, extra: [ + ...$entry->toArray(), + 'actor' => ['type' => $entry->actorType->value, 'alias' => $entry->actorAlias, 'id' => $entry->actorId], + ]), ); } } diff --git a/src/Audit/NullAuditSink.php b/src/Audit/NullAuditSink.php index fdbfbdf..96b0075 100644 --- a/src/Audit/NullAuditSink.php +++ b/src/Audit/NullAuditSink.php @@ -7,9 +7,7 @@ use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Contracts\AuditSink; -/** - * Discards every entry. For hosts that audit elsewhere, through the package's events. - */ +/** Discards every audit entry, for hosts that audit through the package's events instead. */ final readonly class NullAuditSink implements AuditSink { public function record(AuditEntry $entry): void {} diff --git a/src/Authentication/ClosureActorResolver.php b/src/Authentication/ClosureActorResolver.php index 611a822..be2d7f0 100644 --- a/src/Authentication/ClosureActorResolver.php +++ b/src/Authentication/ClosureActorResolver.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Contracts\ActorResolver; -/** - * A resolver from a closure, registered at runtime with `configuration()->resolveActorsUsing()`. - */ +/** Resolves the actor with a closure set through `configuration()->resolveActorsUsing()`. */ final readonly class ClosureActorResolver implements ActorResolver { /** @param Closure(?Request): ?Actor $callback */ diff --git a/src/Authentication/GuardActorResolver.php b/src/Authentication/GuardActorResolver.php index 0c522ab..21105f3 100644 --- a/src/Authentication/GuardActorResolver.php +++ b/src/Authentication/GuardActorResolver.php @@ -13,8 +13,8 @@ use Simtabi\Laranail\Settings\Contracts\ActorResolver; /** - * The default resolver: the first configured guard (`authentication.guards`, in order; empty - * means the application's default guard) that has a user. The host's middleware authenticates. + * Resolves the user of the first guard in `authentication.guards` that has one, or of the + * default guard when the list is empty. */ final readonly class GuardActorResolver implements ActorResolver { diff --git a/src/Authentication/SanctumActorResolver.php b/src/Authentication/SanctumActorResolver.php index 8e81a3b..4aa04ce 100644 --- a/src/Authentication/SanctumActorResolver.php +++ b/src/Authentication/SanctumActorResolver.php @@ -14,12 +14,9 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * Resolves through Sanctum's guard and copies the current token's abilities into - * {@see Actor::$abilities}, so a token's `settings:` (or `settings:*`) is an extra - * ceiling on top of the authorizer, never a grant by itself. A first-party session (Sanctum's - * transient token) carries no abilities and is not limited. - * - * laravel/sanctum is only suggested; this resolver refuses to build without it. + * Resolves through Sanctum and copies the token's abilities onto the actor. A token's + * `settings:` limits what the authorizer may allow; it never grants anything itself. + * A first-party session has no token and is not limited. Requires laravel/sanctum. */ final readonly class SanctumActorResolver implements ActorResolver { diff --git a/src/Authorization/ChainAuthorizer.php b/src/Authorization/ChainAuthorizer.php index 6f18530..1ba7bee 100644 --- a/src/Authorization/ChainAuthorizer.php +++ b/src/Authorization/ChainAuthorizer.php @@ -10,10 +10,7 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Contracts\Authorizer; -/** - * Asks each authorizer in order; the first that does not abstain decides. When all abstain the - * chain abstains, and `authorization.undefined` applies. - */ +/** Asks each authorizer in order; the first that does not abstain decides. */ final readonly class ChainAuthorizer implements Authorizer { /** @param list $authorizers */ diff --git a/src/Authorization/ClosureAuthorizer.php b/src/Authorization/ClosureAuthorizer.php index 476d3ac..b833163 100644 --- a/src/Authorization/ClosureAuthorizer.php +++ b/src/Authorization/ClosureAuthorizer.php @@ -11,10 +11,7 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Contracts\Authorizer; -/** - * An authorizer from a closure. Returning null abstains; `true` and `false` are shorthand for - * allow and deny. - */ +/** Authorizes with a closure that returns a Decision, true, false, or null to abstain. */ final readonly class ClosureAuthorizer implements Authorizer { /** @param Closure(Actor, Ability, Subject): (Decision|bool|null) $callback */ diff --git a/src/Authorization/GateAuthorizer.php b/src/Authorization/GateAuthorizer.php index 4cd6bc9..5121a06 100644 --- a/src/Authorization/GateAuthorizer.php +++ b/src/Authorization/GateAuthorizer.php @@ -12,9 +12,8 @@ use Simtabi\Laranail\Settings\Contracts\Authorizer; /** - * Asks Laravel's gate for `laranail-settings.`, passing the {@see Subject}. The host - * defines those gates (or a `Gate::before` callback). An ability with no gate abstains, so - * `authorization.undefined` decides it (deny by default). + * Asks Laravel's gate for `laranail-settings.` with the {@see Subject}. An ability + * with no gate defined abstains. */ final readonly class GateAuthorizer implements Authorizer { diff --git a/src/Authorization/PermissionsAuthorizer.php b/src/Authorization/PermissionsAuthorizer.php index 5cd9bd1..271a6bf 100644 --- a/src/Authorization/PermissionsAuthorizer.php +++ b/src/Authorization/PermissionsAuthorizer.php @@ -13,9 +13,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * Maps each ability to a permission name and asks the user's own `can()`, so - * spatie/laravel-permission, Bouncer or any `can()`-aware package works without a dependency. - * Names may use `{ability}`, `{store}` and `{key}`. An unmapped ability abstains. + * Maps each ability to a permission name and asks the user's `can()`. Names may use + * `{ability}`, `{store}` and `{key}`; an unmapped ability abstains. */ final readonly class PermissionsAuthorizer implements Authorizer { diff --git a/src/Casting/EnumCaster.php b/src/Casting/EnumCaster.php index 2866cfb..ddb7270 100644 --- a/src/Casting/EnumCaster.php +++ b/src/Casting/EnumCaster.php @@ -9,7 +9,7 @@ use Simtabi\Laranail\Settings\Contracts\Caster; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; -/** A backed enum, stored as its backing value. Registered under `enum:`, never a class name. */ +/** A backed enum, stored as its backing value and registered under `enum:`. */ final readonly class EnumCaster implements Caster { /** @param class-string $enum */ diff --git a/src/Categories/CategoryManager.php b/src/Categories/CategoryManager.php index 27db5ba..7653d29 100644 --- a/src/Categories/CategoryManager.php +++ b/src/Categories/CategoryManager.php @@ -23,9 +23,8 @@ use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** - * The categories of one store, for the actor of the handle that returned it - * (`$settings->store('settings')->as($user)->categories()`). Changes go through the category - * actions (gated by `manage_categories`, audited); reads need `view`. + * The categories of one store, as the handle's actor. Reads need `view`; changes need + * `manage_categories` and are audited. */ final readonly class CategoryManager { diff --git a/src/Concerns/HasSettings.php b/src/Concerns/HasSettings.php index 5e9ab21..686deb4 100644 --- a/src/Concerns/HasSettings.php +++ b/src/Concerns/HasSettings.php @@ -25,14 +25,9 @@ * $user->settings()->get('ui.theme'); * User::query()->withSettings()->paginate(); // one query per store for the page * - * The owner is the model's morph alias and key, never its class name: a model without a morph - * map entry has a class name for an alias, which the package refuses (G-6). Deleting the model - * deletes its settings; a soft-deletable model keeps them until it is force-deleted, so a restore - * finds them again (G-7). Bulk deletes fire no model events: run `prune-orphans` for those. - * - * An application convenience, like the facade it uses: the package's own classes never use it. - * A model that already has a `settings` attribute or relation renames the method: - * `use HasSettings { settings as preferences; }`. + * The owner is the model's morph alias and key; a model without a morph map entry is refused. + * Deleting the model deletes its settings, and a soft-deleted model keeps them until it is + * force-deleted. Bulk deletes fire no model events, so run `prune-orphans` after them. * * @phpstan-require-extends Model */ @@ -48,8 +43,7 @@ public static function bootHasSettings(): void try { SettingsFacade::for(new OwnerRef($model->getMorphClass(), self::ownerKey($model)))->asSystem('owner deleted')->flush(); } catch (OwnerNotAllowed|InvalidIdentifier) { - // No store holds settings for this alias (or it is a class name, which never - // owns any), so there is nothing to remove. + // No store holds settings for this alias, so there is nothing to remove. } }); } @@ -61,9 +55,8 @@ public function settingsOwner(): OwnerRef } /** - * Owners this one may inherit from, nearest first. Override it, building the list from - * foreign keys rather than relations so no model is loaded: - * `return OwnerRef::list(['team' => $this->team_id]);`. + * Owners this one inherits from, nearest first. Build the list from foreign keys so no model + * is loaded: `return OwnerRef::list(['team' => $this->team_id]);`. * * @return list */ @@ -79,8 +72,7 @@ public function settings(): Settings } /** - * Eager-load the settings of every model the query returns (one read per store), so reading - * each model's settings afterwards costs no query. + * Eager-load the settings of every model the query returns, one read per store. * * @param Builder $query */ diff --git a/src/Configuration/PersistedConfigurationEditor.php b/src/Configuration/PersistedConfigurationEditor.php index f461e6d..c909753 100644 --- a/src/Configuration/PersistedConfigurationEditor.php +++ b/src/Configuration/PersistedConfigurationEditor.php @@ -18,13 +18,12 @@ use Simtabi\Laranail\Settings\Actions\Configuration\ListConfigurationEntries; /** - * Persisted configuration (§16.11) edited as a handle's actor: stores and layers saved in the - * `settings_stores` table, definitions in the definitions table of the handle's store. Each change - * is validated like configuration, gated (`manage_stores`, `manage_definitions`) and audited. + * Edits the stores, layers and definitions kept in the database, as a handle's actor. Each change + * is validated, authorized and audited. */ final readonly class PersistedConfigurationEditor { - /** The store and actor are set by {@see in()}; without them, the default store as trusted code. */ + /** Without {@see in()}, edits the default store as trusted code. */ public function __construct( private ListConfigurationEntries $list, private SaveConfigurationEntry $save, diff --git a/src/Console/ClearCacheCommand.php b/src/Console/ClearCacheCommand.php index 046b356..b1b2fbf 100644 --- a/src/Console/ClearCacheCommand.php +++ b/src/Console/ClearCacheCommand.php @@ -13,9 +13,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.clear-cache`: reset the settings cache, for every store or the named ones, - * across every tenant. Only cached copies are reset (generation tokens are replaced); stored - * values and the application's other cache entries are untouched. + * Reset the settings cache for every store, or the named ones, across every tenant. Stored values + * and the application's other cache entries are untouched. */ final class ClearCacheCommand extends Command { diff --git a/src/Console/DiffCommand.php b/src/Console/DiffCommand.php index c905ec6..426f447 100644 --- a/src/Console/DiffCommand.php +++ b/src/Console/DiffCommand.php @@ -16,8 +16,7 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.diff {path}`: compare a store with an export file (G-42), by identity only, - * never printing a value. Exits 1 when they differ, so it can gate a deploy. + * Compare a store with an export file by identity, never printing a value. Exits 1 when they differ. */ final class DiffCommand extends Command { diff --git a/src/Console/DoctorCommand.php b/src/Console/DoctorCommand.php index a01ea71..b549038 100644 --- a/src/Console/DoctorCommand.php +++ b/src/Console/DoctorCommand.php @@ -13,11 +13,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.doctor`: per database store, whether it is ready, whether its tables have - * drifted from what this release uses, and whether any rows break the rules the database cannot - * enforce (class-name scopes, unlisted aliases, cross-store categories), and drift between the - * configuration, the recorded schema file and the database. Exits non-zero on a failure, so it - * can gate a deploy. `--fix` first refreshes the definitions table's system rows. + * Check each database store's readiness, schema drift and the rows the database cannot guard. + * Exits non-zero on a failure; `--fix` refreshes the definitions table's system rows first. */ final class DoctorCommand extends Command { diff --git a/src/Console/ExportCommand.php b/src/Console/ExportCommand.php index ba8b5a4..6fc0676 100644 --- a/src/Console/ExportCommand.php +++ b/src/Console/ExportCommand.php @@ -12,11 +12,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.export {path?}`: write a store's settings and categories as JSON (G-42), to - * a file or standard output. Encrypted values are left out unless `--with-secrets` (their - * ciphertext, importable only under the same APP_KEY or one in APP_PREVIOUS_KEYS) or `--decrypt` - * (plaintext, which asks you to type the store name, or takes it as `--confirm=`). Runs as - * the system actor and is audited; never logs a value. + * Write a store's settings and categories as JSON, to a file or standard output. Secrets are left + * out unless `--with-secrets` (ciphertext) or `--decrypt` (plaintext, after confirming the store name). */ final class ExportCommand extends Command { diff --git a/src/Console/HistoryCommand.php b/src/Console/HistoryCommand.php index d89b5a8..f12c9cc 100644 --- a/src/Console/HistoryCommand.php +++ b/src/Console/HistoryCommand.php @@ -13,10 +13,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.history {key}`: list a setting's versions (newest first, no values), show - * the value at two versions (`--diff=3..5`), or roll it back to one (`--rollback=3`). Runs as the - * system actor, so the rollback and its audit entry name this command. An encrypted or sensitive - * value prints as `[protected]` unless `--reveal` is given. + * List a setting's versions, compare two (`--diff=3..5`) or roll back to one (`--rollback=3`). + * Sensitive values print as `[protected]` unless `--reveal` is given. */ final class HistoryCommand extends Command { diff --git a/src/Console/ImportCommand.php b/src/Console/ImportCommand.php index 058cb30..c68f241 100644 --- a/src/Console/ImportCommand.php +++ b/src/Console/ImportCommand.php @@ -19,11 +19,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.import {source}`: import an export file (G-42), or with `--from=` - * another package's settings (G-43: `spatie`, `toolkit`, `akaunting`, or one configured in - * `importers`). A dry run unless `--apply`: it prints what would be created, updated and skipped. - * `--trusted` lets the file set locks and system categories (G-10). Everything is written through - * the write pipeline as the system actor, in one transaction, and audited. + * Import an export file, or another package's settings with `--from=`. A dry run unless + * `--apply`; `--trusted` lets the file set locks and system categories. */ final class ImportCommand extends Command { diff --git a/src/Console/MakeStoreCommand.php b/src/Console/MakeStoreCommand.php index 3bb3931..8082413 100644 --- a/src/Console/MakeStoreCommand.php +++ b/src/Console/MakeStoreCommand.php @@ -11,8 +11,7 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.make-store`: write the migration for a new database store and print the - * configuration entry to add. Nothing is created at runtime (G-3). + * Write the migration for a new database store and print the configuration entry to add. */ final class MakeStoreCommand extends Command { diff --git a/src/Console/PromoteCommand.php b/src/Console/PromoteCommand.php index 841d553..fea3fdb 100644 --- a/src/Console/PromoteCommand.php +++ b/src/Console/PromoteCommand.php @@ -11,9 +11,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.promote`: copy the values written to a store's runtime file before the - * database existed into its database layer, then archive the file. Shipped defaults are never - * copied. Safe to run again: a second run finds nothing to do. + * Copy values written to a store's runtime file before install into its database layer, then + * archive the file. Shipped defaults are never copied, and a second run does nothing. */ final class PromoteCommand extends Command { diff --git a/src/Console/PruneAuditCommand.php b/src/Console/PruneAuditCommand.php index 02be5aa..65ab8e4 100644 --- a/src/Console/PruneAuditCommand.php +++ b/src/Console/PruneAuditCommand.php @@ -12,7 +12,7 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.prune-audit`: delete audit rows older than `audit.keep_days` (or `--days`). + * Delete audit rows older than `audit.keep_days` (or `--days`). */ final class PruneAuditCommand extends Command { diff --git a/src/Console/PruneChangesCommand.php b/src/Console/PruneChangesCommand.php index db6e63a..084254f 100644 --- a/src/Console/PruneChangesCommand.php +++ b/src/Console/PruneChangesCommand.php @@ -11,9 +11,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.prune-changes`: mark open change requests past `approvals.expire_after` as - * expired, and delete decided ones older than `approvals.keep_days`. Runs as the system actor and - * is audited. + * Expire open change requests past `approvals.expire_after` and delete decided ones older than + * `approvals.keep_days`. */ final class PruneChangesCommand extends Command { diff --git a/src/Console/PruneHistoryCommand.php b/src/Console/PruneHistoryCommand.php index 32ce7a6..ca79e2b 100644 --- a/src/Console/PruneHistoryCommand.php +++ b/src/Console/PruneHistoryCommand.php @@ -12,9 +12,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.prune-history`: apply the history retention policy, `history.keep_days` - * and `history.keep_versions` (or `--days` / `--versions`). Runs as the system actor and is - * audited. + * Apply the history retention policy, `history.keep_days` and `history.keep_versions` (or + * `--days` and `--versions`). */ final class PruneHistoryCommand extends Command { diff --git a/src/Console/PruneOrphansCommand.php b/src/Console/PruneOrphansCommand.php index f39680f..b416e4a 100644 --- a/src/Console/PruneOrphansCommand.php +++ b/src/Console/PruneOrphansCommand.php @@ -12,8 +12,7 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.prune-orphans`: remove the settings of owners that no longer exist, which - * bulk deletes leave behind because they fire no model events. + * Remove the settings of owners that no longer exist, which bulk deletes leave behind. */ final class PruneOrphansCommand extends Command { diff --git a/src/Console/ReencryptCommand.php b/src/Console/ReencryptCommand.php index 3c5e938..f5f2ad2 100644 --- a/src/Console/ReencryptCommand.php +++ b/src/Console/ReencryptCommand.php @@ -11,9 +11,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.reencrypt`: after rotating APP_KEY (with the old key in APP_PREVIOUS_KEYS), - * encrypt every stored secret again under the new key: live values, history and change requests. - * Exits 1 when a value could be read with no key (it is left as it was). + * Encrypt every stored secret again under the current APP_KEY, reading with APP_PREVIOUS_KEYS. + * Exits 1 when a value cannot be read with any key. */ final class ReencryptCommand extends Command { diff --git a/src/Console/RescopeCommand.php b/src/Console/RescopeCommand.php index 937b6a5..a75f000 100644 --- a/src/Console/RescopeCommand.php +++ b/src/Console/RescopeCommand.php @@ -11,8 +11,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.rescope {from} {to}`: rename an owner alias in stored settings, history and - * change requests (G-30), after renaming it in the morph map. `from` may be a class name. + * Rename an owner alias in stored values, history and change requests, after renaming it in the + * morph map. `from` may be a class name. */ final class RescopeCommand extends Command { diff --git a/src/Console/ShowCommand.php b/src/Console/ShowCommand.php new file mode 100644 index 0000000..0ec6d08 --- /dev/null +++ b/src/Console/ShowCommand.php @@ -0,0 +1,166 @@ +address($config->string('laranail.settings.default', 'settings')); + $actor = Actor::system('laranail::settings.show', Channel::Console); + $store = $targets->store($address->store); + $definition = $definitions->find($store, new Key($address->key)); + $audit = $this->latestAudit($settings, $address, $actor); + $explanation = $explain->handle($address, $actor); + $record = $this->record($store, $explanation, $address); + } catch (SettingsException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $lookup = $explanation->lookup; + $sensitive = $definition?->isSensitive() === true || $record?->encrypted === true; + + $this->table(['Field', 'Value'], [ + ['Key', $address->key], + ['Store', $address->store], + ['Scope', Scope::of($address->ownerRef())->value], + ['Locale', $address->locale === '' ? '-' : $address->locale], + ['Value', $this->value($explanation, $sensitive)], + ['Layer', $lookup->layer() ?? '-'], + ['From scope', $lookup->scope()->value ?? '-'], + ['Type', $record->type ?? $definition->type ?? '-'], + ['Version', $record instanceof Record ? (string) $record->version : '-'], + ['Locked', $this->flag($record instanceof Record ? $record->locked : $definition?->locked)], + ['Encrypted', $this->flag($record instanceof Record ? $record->encrypted : $definition?->encrypted)], + ['Sensitive', $this->flag($definition?->isSensitive())], + ['Defined', $this->flag($definition instanceof Definition)], + ['Last audit', $audit instanceof AuditEntry ? $this->describe($audit) : '-'], + ]); + + foreach ($explanation->steps as $step) { + $this->line(' ' . $step); + } + + return self::SUCCESS; + } + + private function address(string $default): SettingAddress + { + $key = $this->argument('key'); + $store = $this->option('store'); + $owner = $this->option('owner'); + $locale = $this->option('locale'); + + return new SettingAddress( + is_string($store) && $store !== '' ? $store : $default, + is_string($key) ? $key : '', + is_string($owner) && $owner !== '' + ? Scope::fromString($owner)?->owner() ?? throw new InvalidIdentifier(sprintf('--owner: [%s] is not alias:id.', $owner)) + : null, + is_string($locale) ? $locale : '', + ); + } + + /** The newest audit entry for this key and scope, or null when the audit trail cannot be queried. */ + private function latestAudit(Settings $settings, SettingAddress $address, Actor $actor): ?AuditEntry + { + try { + $query = $settings->as($actor)->store($address->store)->audit()->key($address->key); + $owner = $address->ownerRef(); + $query = $owner instanceof OwnerRef ? $query->for($owner) : $query->global(); + + return $query->get(1)[0] ?? null; + } catch (SettingsException) { + return null; + } + } + + /** The row behind the answer, from the layer that gave it; null for a default or a miss. */ + private function record(Store $store, Explanation $explanation, SettingAddress $address): ?Record + { + $scope = $explanation->lookup->scope(); + + foreach ($store->layers as $layer) { + if ($scope instanceof Scope && $layer->name === $explanation->lookup->layer()) { + return $layer->driver->load($store->name, [$scope])->find($scope, new Key($address->key), new Locale($address->locale)); + } + } + + return null; + } + + private function value(Explanation $explanation, bool $sensitive): string + { + $lookup = $explanation->lookup; + + return match (true) { + ! $lookup->isFound() => '(not set)', + $lookup->isRedacted(), $sensitive && $this->option('reveal') !== true => '[protected]', + default => (string) json_encode($lookup->value(), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), + }; + } + + private function flag(?bool $value): string + { + return match ($value) { + true => 'yes', + false => 'no', + null => '-', + }; + } + + private function describe(AuditEntry $entry): string + { + return sprintf( + '%s %s by %s%s via %s at %s', + $entry->action->value, + $entry->outcome->value, + $entry->actorType->value, + $entry->actorId === null ? '' : ':' . $entry->actorAlias . ':' . $entry->actorId, + $entry->channel->value, + $entry->occurredAt->toIso8601String(), + ); + } +} diff --git a/src/Console/SyncDefinitionsCommand.php b/src/Console/SyncDefinitionsCommand.php index e47fd01..131c0c1 100644 --- a/src/Console/SyncDefinitionsCommand.php +++ b/src/Console/SyncDefinitionsCommand.php @@ -11,9 +11,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.sync-definitions`: copy code and config definitions into the optional - * definitions table as read-only system rows (D-6), and remove system rows nothing defines any - * more. Rows edited at runtime are left alone. + * Copy code and config definitions into the definitions table as read-only system rows, and remove + * system rows nothing defines any more. Rows edited at runtime are left alone. */ final class SyncDefinitionsCommand extends Command { diff --git a/src/Console/WarmCacheCommand.php b/src/Console/WarmCacheCommand.php index 17e9109..0d7c60b 100644 --- a/src/Console/WarmCacheCommand.php +++ b/src/Console/WarmCacheCommand.php @@ -14,8 +14,8 @@ use Simtabi\Laranail\Console\Tools\Commands\Concerns\SupportsNamespacedNames; /** - * `laranail::settings.warm`: load each cached store's global scope into the cache (one query per - * store on a miss), so the first request after a deploy or a cache reset does not pay for it. + * Load each cached store's global scope into the cache, so the first request after a deploy does + * not pay for it. */ final class WarmCacheCommand extends Command { diff --git a/src/Contracts/ActorResolver.php b/src/Contracts/ActorResolver.php index 829d9d7..cd84e04 100644 --- a/src/Contracts/ActorResolver.php +++ b/src/Contracts/ActorResolver.php @@ -7,10 +7,7 @@ use Illuminate\Http\Request; use Simtabi\Laranail\Settings\Data\Actor; -/** - * Turns the current request (or context) into an {@see Actor}. The host's own middleware does - * the authenticating; a resolver only reads its result. - */ +/** Turns the current request into an {@see Actor}; authentication itself is the host's. */ interface ActorResolver { /** The authenticated actor, or null when nobody is authenticated. */ diff --git a/src/Contracts/AuditSink.php b/src/Contracts/AuditSink.php index 7d79142..23f5379 100644 --- a/src/Contracts/AuditSink.php +++ b/src/Contracts/AuditSink.php @@ -6,9 +6,7 @@ use Simtabi\Laranail\Settings\Data\AuditEntry; -/** - * Where audit entries go. Several sinks can run together (`audit.sinks`). - */ +/** A destination for audit entries. */ interface AuditSink { public function record(AuditEntry $entry): void; diff --git a/src/Contracts/Authorizer.php b/src/Contracts/Authorizer.php index d969f6d..1fe6e93 100644 --- a/src/Contracts/Authorizer.php +++ b/src/Contracts/Authorizer.php @@ -9,12 +9,9 @@ use Simtabi\Laranail\Settings\Data\Decision; use Simtabi\Laranail\Settings\Enums\Ability; -/** - * The single authorization seam. Called only for a handle that carries a non-system actor; - * trusted code without an actor never reaches it. - */ +/** Decides abilities for a handle with a non-system actor. */ interface Authorizer { - /** Allow, deny, require verification or approval, or abstain to let the next authorizer decide. */ + /** Allow, deny, require verification or approval, or abstain for the next authorizer. */ public function authorize(Actor $actor, Ability $ability, Subject $subject): Decision; } diff --git a/src/Contracts/Caster.php b/src/Contracts/Caster.php index ba7848d..c701e5b 100644 --- a/src/Contracts/Caster.php +++ b/src/Contracts/Caster.php @@ -7,9 +7,7 @@ use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; -/** - * Converts a setting value to a JSON-encodable form for storage, and back. - */ +/** Converts a setting value to a JSON-encodable form and back. */ interface Caster { /** @throws InvalidSettingValue when the value cannot be represented as this type */ diff --git a/src/Contracts/DatabaseBacked.php b/src/Contracts/DatabaseBacked.php index 1cff7f6..1ec2cc7 100644 --- a/src/Contracts/DatabaseBacked.php +++ b/src/Contracts/DatabaseBacked.php @@ -6,16 +6,12 @@ use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -/** - * A layer driver backed by the database: the database driver itself, or the bootstrap gate in - * front of it. Lets a store find its database layer (for transactions, the audit table and the - * maintenance commands) without knowing which wrapper is in place. - */ +/** A layer driver backed by the database, whatever wrapper is in front of it. */ interface DatabaseBacked extends Driver { /** The database driver behind this layer. */ public function database(): DatabaseDriver; - /** False while bootstrap mode skips the layer; the store then behaves as if it had none. */ + /** False while bootstrap mode skips the layer. */ public function isActive(): bool; } diff --git a/src/Contracts/Driver.php b/src/Contracts/Driver.php index b5acb2b..bb09099 100644 --- a/src/Contracts/Driver.php +++ b/src/Contracts/Driver.php @@ -12,10 +12,7 @@ use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; -/** - * A storage layer. Bulk reads only: the resolver loads every scope it needs in one call, so a - * request costs one read per layer rather than one per key. - */ +/** A storage layer. Reads load every requested scope in one call. */ interface Driver { /** diff --git a/src/Contracts/Importer.php b/src/Contracts/Importer.php index 37be780..38f64fc 100644 --- a/src/Contracts/Importer.php +++ b/src/Contracts/Importer.php @@ -9,10 +9,8 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; /** - * Reads another package's settings into an export document (G-43), which the normal import then - * writes through the write pipeline. An importer only reads; it never writes, and it needs none of - * the package it reads from. `$source` is what that package keeps (a connection, a table, a - * file), in the form the importer documents. + * Reads another package's settings into an export document for the normal import to write. + * `$source` is a connection, table or file, as the importer documents. */ interface Importer { diff --git a/src/Contracts/Settable.php b/src/Contracts/Settable.php index ace321a..0d24e6e 100644 --- a/src/Contracts/Settable.php +++ b/src/Contracts/Settable.php @@ -6,16 +6,14 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; -/** - * A model (or anything) that can own settings. - */ +/** Anything that can own settings. */ interface Settable { /** This owner, by morph alias and id. */ public function settingsOwner(): OwnerRef; /** - * Owners this one may inherit from, nearest first (for example team, then tenant). + * Owners this one inherits from, nearest first. * * @return list */ diff --git a/src/Contracts/Settings.php b/src/Contracts/Settings.php index f53acd3..51dd7bc 100644 --- a/src/Contracts/Settings.php +++ b/src/Contracts/Settings.php @@ -40,35 +40,31 @@ use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** - * Read and write settings. `store()`, `for()`, `locale()`, `as()`, `asSystem()` and `because()` - * return a new handle; the shared instance never changes, so a scoped handle cannot leak into - * another request. + * Read and write settings. * - * A handle with an actor checks every operation, reads included, through the configured - * authorizer. A handle without one runs as trusted code and is audited as `system`, unless - * `authorization.require_actor` is on. + * The scoping methods (`store()`, `for()`, `locale()`, `as()`, `asSystem()`, `because()`) return a + * new handle, so a scoped handle never leaks into another request. A handle with an actor + * authorizes every operation; one without runs as trusted code, audited as `system`. */ interface Settings { /** A handle on another store. */ public function store(string $name): static; - /** A handle for an owner; without an explicit store it routes to the store that accepts the owner's alias. */ + /** A handle for an owner, routed to the store that accepts its alias unless a store was named. */ public function for(Settable|OwnerRef $owner): static; /** A handle reading and writing one locale. */ public function locale(string $locale): static; - /** - * A handle acting as this user or actor: every operation is authorized and audited. - */ + /** A handle acting as this user or actor; every operation is authorized and audited. */ public function as(Authenticatable|Actor $actor): static; - /** A handle acting as trusted system code, explicitly; allowed even when an actor is required. */ + /** A handle acting as trusted system code, allowed even when an actor is required. */ public function asSystem(?string $reason = null): static; /** - * A handle acting as whoever the configured actor resolver finds for the request. + * A handle acting as the actor the configured resolver finds for the request. * * @throws ActorRequired when nobody is authenticated */ @@ -80,11 +76,11 @@ public function because(string $reason): static; /** The actor this handle acts as, or null for trusted code. */ public function actor(): ?Actor; - /** Configuration changed in code for the current request only. */ + /** Configuration overrides that last for the current request. */ public function configuration(): RuntimeConfiguration; /** - * Apply configuration changes for the duration of `$run` only, then restore them. + * Apply configuration changes while `$run` runs, then restore them. * * @template TResult * @@ -99,7 +95,7 @@ public function withConfiguration(callable $change, callable $run): mixed; public function get(string $key, mixed $default = null): mixed; /** - * Presence-aware read: found (value possibly null) or missing. + * Read a value, telling a stored null apart from a missing key. * * @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 @@ -108,13 +104,12 @@ 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. */ + /** Whether 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. + * Several values, keyed as asked: a list of keys, `key => default` pairs, or both. Each key is + * read as {@see get()} reads it. * * @param array $keys * @@ -126,18 +121,15 @@ public function missing(string $key): bool; 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. + * Every value this handle can see, in key order. Keys the actor may not read are left out, not + * masked. `$prefix` keeps that key 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. + * The definitions of this handle's store, in key order. Needs `view`. * * @return list * @@ -164,7 +156,7 @@ public function boolean(string $key): bool; */ public function array(string $key): array; - /** How a read resolves: every step tried, and the answer, redacted when the actor may not view it. */ + /** Every step a read tries and the answer, redacted when the actor may not view it. */ public function explain(string $key): Explanation; /** @@ -180,28 +172,27 @@ public function explain(string $key): Explanation; */ public function set(string $key, mixed $value): void; - /** Remove this handle's own value, so reads fall through again. */ + /** Remove this handle's own value, so reads fall through to the next layer. */ 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). + * Write several values with {@see set()}, in order. Not atomic: the first refusal stops the + * rest, and 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. + * Remove several of this handle's own values with {@see forget()}, in order. * * @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. + * The stored value, or `$value()` written with {@see set()} and read back when nothing is + * stored. When the write opens a change request instead, the computed value is returned. * * @param callable(): mixed $value */ @@ -212,7 +203,7 @@ public function lock(string $key): void; public function unlock(string $key): void; /** - * Remove every value this handle's owner holds in its store (an owner being deleted). + * Remove every value this handle's owner holds in its store. * * @throws AccessDenied * @throws StoreNotWritable @@ -220,28 +211,24 @@ public function unlock(string $key): void; public function flush(): void; /** - * Reset the cached settings this handle names (design §7.5): with `for($owner)`, that owner's - * cached values in its store; otherwise every cached value of the handle's store, for every - * tenant. Stored values are untouched. Needs `manage_stores` when the handle carries an actor. - * Does nothing when caching is off. + * Clear the cached values of this handle's owner, or of the whole store when it has no owner. + * Stored values are untouched. Needs `manage_stores`. * * @throws AccessDenied */ public function clearCache(): void; /** - * Load this handle's scope (its owner's, or the global scope) into the cache now, so the - * first read costs no query. Needs `manage_stores` when the handle carries an actor. Returns - * how many records were cached (0 when the store is not cached). + * Load this handle's scope into the cache and return how many records were cached (0 when + * the store is not cached). Needs `manage_stores`. * * @throws AccessDenied */ public function warmCache(): int; /** - * Load the settings of many owners now, one read per store, so reading each of them later in - * the request costs no further query (eager loading, G-9). Includes the global scope and the - * owners' parents. + * Eager-load the settings of many owners, their parents and the global scope, one read per + * store. * * @param iterable $owners */ @@ -251,8 +238,8 @@ public function preload(iterable $owners): void; public function categories(): CategoryManager; /** - * Copy the values written to the store's runtime file before the database existed into its - * database layer; shipped defaults are never copied. Idempotent. + * Copy values from the store's runtime file into its database layer; shipped defaults are + * never copied. Idempotent. * * @throws AccessDenied * @throws PromotionLocked @@ -261,25 +248,19 @@ public function categories(): CategoryManager; public function promote(?PromotionRequest $request = null): PromotionReport; /** - * Query the audit trail (§16.8): `->for($owner)`, `->store()`, `->key()`, `->action()`, - * `->outcome()`, `->since()`, `->until()`, then `->get()`, `->cursor()` or `->paginate()`. - * Needs `view_audit` when the handle carries an actor. Entries never hold values. + * Query the audit trail. Needs `view_audit`. Entries never hold values. */ public function audit(): AuditQuery; /** - * Query the value history (§4.3) of this handle's store (and owner and locale, when set): - * `->key()`, `->for($owner)`, `->global()`, `->since()`, `->until()`, `->versions()`, then - * `->get()`, `->cursor()` or `->paginate()`. Needs `view_history` when the handle carries an - * actor. Payloads stay as stored (encrypted values encrypted), and are removed for an actor - * who may not view the setting's sensitive values. + * Query the value history of this handle's store. Needs `view_history`. Payloads stay as + * stored, and are removed for an actor who may not view sensitive values. */ public function history(): HistoryQuery; /** - * Return a setting to the value it held at `$toVersion`, written as a new version through - * the normal write pipeline; returns that new version. Needs `rollback` (and step-up - * verification when `verification.abilities` lists it, as it does by default). + * Write the value a setting held at `$toVersion` as a new version, and return that version. + * Needs `rollback`, and step-up verification by default. * * @throws HistoryUnavailable when the store keeps no history or has no value at that version * @throws AccessDenied @@ -289,8 +270,7 @@ public function history(): HistoryQuery; public function rollback(string $key, int $toVersion): int; /** - * Open a change request for this value instead of writing it (§16.7), whether or not the - * setting needs approval; returns the request. Needs `update`. + * Open a change request for this value instead of writing it. Needs `update`. * * @throws ApprovalUnavailable when the store cannot hold change requests * @throws InvalidSettingValue @@ -298,25 +278,21 @@ public function rollback(string $key, int $toVersion): int; public function propose(string $key, mixed $value): ChangeRequest; /** - * The change requests of this handle's store (§16.7), decided as this handle's actor: list - * them, approve, reject or cancel one. A write to a setting that needs approval opens one - * automatically; `set()` still returns nothing. + * The change requests of this handle's store, decided as this handle's actor. */ public function approvals(): Approvals; /** - * This handle's store as a portable document (G-42): categories by slug, settings by scope, - * key and locale. Encrypted values are left out unless the mode asks for their ciphertext or - * (with `view_sensitive`) their plaintext. Needs `export`. + * This handle's store as a portable document. Encrypted values are left out unless the mode + * asks for their ciphertext or, with `view_sensitive`, their plaintext. Needs `export`. * * @throws AccessDenied */ public function export(ExportMode $mode = ExportMode::Redacted): ExportDocument; /** - * Write a document into this handle's store through the write pipeline, categories first, in - * one transaction (G-42). Locks and system categories in the document are ignored here; a - * trusted import is the console's `--trusted`. Needs `import`. + * Write a document into this handle's store in one transaction. Locks and system categories + * in the document are ignored; the console's `--trusted` applies them. Needs `import`. * * @throws AccessDenied * @throws VerificationRequired @@ -330,16 +306,14 @@ public function previewImport(ExportDocument $document): ImportReport; public function compare(ExportDocument $document): StoreDiff; /** - * Persisted configuration (§16.11): stores and layers kept in the database, and definitions - * kept in this handle's store's definitions table, edited as this handle's actor. Needs - * `manage_stores` or `manage_definitions`; on only with `configuration.persisted`. + * Edit the stores, layers and definitions kept in the database, as this handle's actor. + * Requires `configuration.persisted`. */ public function persistedConfiguration(): PersistedConfigurationEditor; /** - * The value at two versions of a setting. Needs `view_history`; an encrypted or sensitive - * value is decrypted only for an actor holding `view_sensitive` (or a trusted call), and is - * otherwise redacted to "changed or not". + * Compare a setting at two versions. Needs `view_history`; sensitive values are shown only + * with `view_sensitive`, otherwise only whether they changed. * * @throws HistoryUnavailable when the store keeps no history or lacks either version */ diff --git a/src/Contracts/TenantDiscriminator.php b/src/Contracts/TenantDiscriminator.php index fc6cfd1..21754f9 100644 --- a/src/Contracts/TenantDiscriminator.php +++ b/src/Contracts/TenantDiscriminator.php @@ -5,10 +5,8 @@ namespace Simtabi\Laranail\Settings\Contracts; /** - * The current tenant, as a string of at most 64 characters, or null outside any tenant (the - * central application). In column-mode tenancy it is written to and filtered on every row; in - * every mode it keys what is held in memory, so one tenant's settings are never answered from - * another tenant's reads. + * The current tenant (at most 64 characters), or null outside any tenant. It also keys in-memory + * state, so one tenant never reads another's settings. */ interface TenantDiscriminator { diff --git a/src/Contracts/Verifier.php b/src/Contracts/Verifier.php index 9158ebf..0e52f13 100644 --- a/src/Contracts/Verifier.php +++ b/src/Contracts/Verifier.php @@ -7,9 +7,7 @@ use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; -/** - * Decides whether an actor has recently proven their identity (step-up verification). - */ +/** Decides whether an actor has recently verified their identity. */ interface Verifier { public function isVerified(Actor $actor, Subject $subject): bool; diff --git a/src/Data/Actor.php b/src/Data/Actor.php index bf65305..cb6405a 100644 --- a/src/Data/Actor.php +++ b/src/Data/Actor.php @@ -11,11 +11,8 @@ use Simtabi\Laranail\Settings\Enums\ActorType; /** - * Who is acting and how: the authentication object every checked operation runs as. - * - * The authenticatable itself is held for authorizers that need it (gates, `can()`), and is - * never serialised: a queued actor keeps its type, alias and id, and the receiving job - * rehydrates the user if it needs one. + * Who is acting and through which channel. The authenticatable is kept for authorizers but never + * serialised; a queued actor keeps only its type, alias and id. */ final readonly class Actor { @@ -33,11 +30,7 @@ public function __construct( public ActorContext $context = new ActorContext, ) {} - /** - * Serialise without the authenticatable, so a queued payload never carries a model. - * - * @return array - */ + /** @return array */ public function __serialize(): array { return [ @@ -75,8 +68,7 @@ public function __unserialize(array $data): void } /** - * An actor for an authenticated user. Passing token abilities makes it a token actor, whose - * token must also grant each ability (an extra ceiling, never a grant by itself). + * An actor for a user; passing token abilities makes it a token actor. * * @param list|null $abilities */ @@ -143,7 +135,7 @@ public function withVerifiedAt(CarbonImmutable $verifiedAt): self } /** - * Identifiers only: what the audit trail and logs record about the actor. + * The identifiers the audit trail and logs record. * * @return array{type: string, alias: string|null, id: string|null, channel: string} */ @@ -154,7 +146,7 @@ public function toArray(): array private static function aliasOf(Authenticatable $user): string { - // A morph alias when the host maps one; never trusted as a class to instantiate. + // The alias is recorded, never instantiated as a class. if (method_exists($user, 'getMorphClass')) { $alias = $user->getMorphClass(); diff --git a/src/Data/ActorContext.php b/src/Data/ActorContext.php index 0e445e0..a5bb9b7 100644 --- a/src/Data/ActorContext.php +++ b/src/Data/ActorContext.php @@ -6,10 +6,7 @@ use Illuminate\Http\Request; -/** - * Where an actor's call came from: client address, user agent, request id and the reason given. - * Recorded in the audit trail; never carries a setting's value. - */ +/** Where an actor's call came from: client address, user agent, request id and reason. */ final readonly class ActorContext { /** User agents are cut to this length, matching the audit column. */ diff --git a/src/Data/AlertContext.php b/src/Data/AlertContext.php index 84968f3..bab23d9 100644 --- a/src/Data/AlertContext.php +++ b/src/Data/AlertContext.php @@ -11,12 +11,8 @@ use Simtabi\Laranail\Settings\Events\VerificationWasRequired; /** - * What an alert says about one event (§4 of the alerts plan): the event, where it happened, who - * caused it, how it ended and when. It is built from the event's identifiers only, so it never - * holds a setting's value, and neither does any channel rendered from it. - * - * `outcome` is `denied` for a refusal (AccessWasDenied, VerificationWasRequired) and `allowed` - * for everything else, matching the audit's outcomes. + * What an alert says about one event: what happened, where, by whom, how it ended and when. + * Built from identifiers only, never a value. */ final readonly class AlertContext { diff --git a/src/Data/AlertRule.php b/src/Data/AlertRule.php index cb00b75..244a955 100644 --- a/src/Data/AlertRule.php +++ b/src/Data/AlertRule.php @@ -8,13 +8,7 @@ use Illuminate\Database\Eloquent\Model; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -/** - * One entry of `laranail.settings.alerts.rules`: which events it answers (by short class name, - * `SettingSaved`, or FQCN), narrowed by key globs (`mail.*`), stores, sensitive keys only and - * outcomes (`allowed`, `denied`); and where it sends: mail addresses, a Slack webhook (when - * laravel/slack-notification-channel is installed), and a database notifiable model. `queue` - * names the queue to send on; null sends at once. - */ +/** One entry of `alerts.rules`: which events it answers, and where it sends them. */ final readonly class AlertRule { /** diff --git a/src/Data/ApprovalPolicy.php b/src/Data/ApprovalPolicy.php index 92f9671..fc458d4 100644 --- a/src/Data/ApprovalPolicy.php +++ b/src/Data/ApprovalPolicy.php @@ -6,11 +6,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -/** - * The approval rules (§16.7, `approvals.*`): how many approvals apply a change, whether the - * requester may approve their own request, after how many days an open request expires (null: - * never), and how many days decided requests are kept (null: for ever). - */ +/** The approval rules from `approvals.*`. Null days mean never expire, or keep for ever. */ final readonly class ApprovalPolicy { public function __construct( @@ -31,8 +27,6 @@ public function __construct( } /** - * The policy `approvals.*` describes. - * * @param array $approvals `laranail.settings.approvals` */ public static function fromConfig(array $approvals): self diff --git a/src/Data/AuditEntry.php b/src/Data/AuditEntry.php index 5abdbf9..2d3603d 100644 --- a/src/Data/AuditEntry.php +++ b/src/Data/AuditEntry.php @@ -11,8 +11,8 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; /** - * One audited action. It records who did what to which key and how it ended, and has no field - * for a value: an audit trail must never become a second copy of the secrets it watches. + * One audited action: who did what to which key, and how it ended. It has no value field, so the + * trail never becomes a copy of the secrets it watches. */ final readonly class AuditEntry { diff --git a/src/Data/AuditFilter.php b/src/Data/AuditFilter.php index 69e24e5..7f241bc 100644 --- a/src/Data/AuditFilter.php +++ b/src/Data/AuditFilter.php @@ -8,10 +8,7 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; -/** - * What an audit query selects: every condition is optional and they combine with AND. `store` - * also picks the connection whose audit table is read (the default store's when null). - */ +/** Audit query conditions, combined with AND. `store` also picks the connection that is read. */ final readonly class AuditFilter { public function __construct( @@ -24,7 +21,7 @@ public function __construct( public ?CarbonImmutable $until = null, ) {} - /** A copy with some conditions replaced (named arguments; the rest are kept). */ + /** A copy with the named conditions replaced. */ public function with( ?StoreName $store = null, ?Scope $scope = null, diff --git a/src/Data/AuditPage.php b/src/Data/AuditPage.php index bc2e81f..ae81c7d 100644 --- a/src/Data/AuditPage.php +++ b/src/Data/AuditPage.php @@ -4,10 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * One page of the audit trail, newest first. `nextCursor` / `previousCursor` are opaque strings - * to pass back to `paginate()`; null at either end. - */ +/** One page of the audit trail, newest first, with opaque cursors for `paginate()`. */ final readonly class AuditPage { /** @param list $entries */ diff --git a/src/Data/CacheTarget.php b/src/Data/CacheTarget.php index 771e198..ba7704e 100644 --- a/src/Data/CacheTarget.php +++ b/src/Data/CacheTarget.php @@ -5,10 +5,8 @@ namespace Simtabi\Laranail\Settings\Data; /** - * Where a cached bag's rows live: the connection name, the database that connection points at, - * the store and its table. Every one of them is in every cache key (G-37), because the `global` - * scope is spelled the same in every database and a shared cache would otherwise answer one - * database's read from another's rows. The tenant is added by the cache itself, per call. + * Where a cached bag's rows live: connection, database, store and table. All of them go into the + * cache key so a shared cache never answers one database's read with another's rows. */ final readonly class CacheTarget { diff --git a/src/Data/Category.php b/src/Data/Category.php index 732c00e..66efab6 100644 --- a/src/Data/Category.php +++ b/src/Data/Category.php @@ -5,9 +5,8 @@ namespace Simtabi\Laranail\Settings\Data; /** - * One category of one store, as stored. `parent` is the parent's slug (categories nest, D-11). - * `titles` holds the title per locale under `translations.mode = json` (D-8), with `''` for the - * title that applies to any locale; under `lang` it holds only that entry. + * One stored category. `parent` is the parent's slug; `titles` maps locale to title, with `''` + * for the title that applies to any locale. */ final readonly class Category { diff --git a/src/Data/CategorySlug.php b/src/Data/CategorySlug.php index e27f43d..aa26f40 100644 --- a/src/Data/CategorySlug.php +++ b/src/Data/CategorySlug.php @@ -7,10 +7,7 @@ use Stringable; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -/** - * A category slug: lower-case letters, digits and hyphens, at most 128 characters, unique within - * its store. - */ +/** A category slug: lower-case letters, digits and hyphens, at most 128 characters. */ final readonly class CategorySlug implements Stringable { public string $value; diff --git a/src/Data/ChangeDecision.php b/src/Data/ChangeDecision.php index 3e64240..0f12d8a 100644 --- a/src/Data/ChangeDecision.php +++ b/src/Data/ChangeDecision.php @@ -6,7 +6,7 @@ use Simtabi\Laranail\Settings\Stores\Store; -/** The input of approving, rejecting or cancelling a change request: which one, and why. */ +/** Which change request to approve, reject or cancel, and why. */ final readonly class ChangeDecision { public function __construct( diff --git a/src/Data/ChangeFilter.php b/src/Data/ChangeFilter.php index 71960a1..a3ad9ed 100644 --- a/src/Data/ChangeFilter.php +++ b/src/Data/ChangeFilter.php @@ -17,7 +17,7 @@ public function __construct( public ?string $id = null, ) {} - /** A copy with some conditions replaced (named arguments; the rest are kept). */ + /** A copy with the named conditions replaced. */ public function with(?ChangeStatus $status = null, ?Scope $scope = null, ?Key $key = null, ?string $id = null): self { return new self($this->store, $status ?? $this->status, $scope ?? $this->scope, $key ?? $this->key, $id ?? $this->id); diff --git a/src/Data/ChangeProposal.php b/src/Data/ChangeProposal.php index 6464211..e906c86 100644 --- a/src/Data/ChangeProposal.php +++ b/src/Data/ChangeProposal.php @@ -6,10 +6,7 @@ use Simtabi\Laranail\Settings\Enums\ChangeOperation; -/** - * The input of {@see \Simtabi\Laranail\Settings\Actions\Approvals\ProposeChange}: the write a - * change request will apply once approved. `value` matters for a set only. - */ +/** The write a change request applies once approved; `value` is used by a set only. */ final readonly class ChangeProposal { public function __construct( diff --git a/src/Data/ChangeRequest.php b/src/Data/ChangeRequest.php index 54f750c..a579725 100644 --- a/src/Data/ChangeRequest.php +++ b/src/Data/ChangeRequest.php @@ -10,10 +10,8 @@ use Simtabi\Laranail\Settings\Enums\ChangeOperation; /** - * A write waiting for approval (§16.7). `payload` is the proposed value exactly as the values - * table would store it (ciphertext for an encrypted definition), so it is never exposed by - * {@see toArray()}; `baseVersion` is the version the setting was at when the request was opened. - * `approvals` lists who approved so far, as `type:alias:id` strings. + * A write waiting for approval. `payload` is stored as the values table would store it and is + * left out of {@see toArray()}; `baseVersion` is the setting's version when the request opened. */ final readonly class ChangeRequest { @@ -72,7 +70,7 @@ public function owner(): ?OwnerRef } /** - * Everything but the payload: a change request is safe to list and render. + * Everything but the payload. * * @return array */ diff --git a/src/Data/ConfigurationEntry.php b/src/Data/ConfigurationEntry.php index 288851e..6afe884 100644 --- a/src/Data/ConfigurationEntry.php +++ b/src/Data/ConfigurationEntry.php @@ -6,10 +6,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -/** - * A persisted store or layer entry (§16.11): its kind, name and configuration, exactly as the - * configuration file would hold it under `stores.` or `layers.`. - */ +/** A persisted store or layer entry, shaped as the configuration file holds it. */ final readonly class ConfigurationEntry { public const string STORE = 'store'; diff --git a/src/Data/Decision.php b/src/Data/Decision.php index bcdfaa9..c69ff87 100644 --- a/src/Data/Decision.php +++ b/src/Data/Decision.php @@ -6,10 +6,7 @@ use Simtabi\Laranail\Settings\Enums\Verdict; -/** - * An authorizer's answer for one ability on one subject: allow, deny with a reason, allow once - * the actor has verified, allow through approval, or abstain (no opinion). - */ +/** An authorizer's answer: allow, deny, require verification, require approval, or abstain. */ final readonly class Decision { private function __construct( @@ -37,7 +34,7 @@ public static function requiresApproval(?string $reason = null): self return new self(Verdict::RequiresApproval, $reason); } - /** No opinion: the next authorizer decides, then `authorization.undefined`. */ + /** No opinion; the next authorizer decides. */ public static function abstain(?string $reason = null): self { return new self(Verdict::Abstain, $reason); diff --git a/src/Data/Definition.php b/src/Data/Definition.php index 26f2acf..2174d76 100644 --- a/src/Data/Definition.php +++ b/src/Data/Definition.php @@ -7,10 +7,7 @@ use Simtabi\Laranail\Settings\Enums\Precedence; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; -/** - * What a key is: its type, default, rules, flags and who may override it. Immutable; build one - * with {@see \Simtabi\Laranail\Settings\Definitions\DefinitionBuilder}. - */ +/** A key's type, default, rules and flags; build one with {@see \Simtabi\Laranail\Settings\Definitions\DefinitionBuilder}. */ final readonly class Definition { /** diff --git a/src/Data/GeneratedStore.php b/src/Data/GeneratedStore.php index f22e8c3..e8f1e55 100644 --- a/src/Data/GeneratedStore.php +++ b/src/Data/GeneratedStore.php @@ -4,11 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * What `make-store` produced: the migration files it wrote and the configuration entry to add to - * `config/laranail/settings.php` (printed, never written, because that file is the - * application's). - */ +/** The migrations `make-store` wrote and the configuration entry to add by hand. */ final readonly class GeneratedStore { /** @param list $migrations */ diff --git a/src/Data/HistoryDiff.php b/src/Data/HistoryDiff.php index dbec2ef..10ce66c 100644 --- a/src/Data/HistoryDiff.php +++ b/src/Data/HistoryDiff.php @@ -5,12 +5,8 @@ namespace Simtabi\Laranail\Settings\Data; /** - * The value of one setting at two versions. `redacted` is true when the setting is encrypted and - * the actor may not view sensitive values: both values are then null and only `changed` (whether - * the stored payloads differ) is reported. A version that holds no value (a tombstone, or a lock - * row without one) reads as null with `fromFound` / `toFound` false. `encrypted` says the value is - * protected (encrypted at rest, or its definition is sensitive), so a caller printing it, such as - * the history command, can hold it back unless asked. + * One setting at two versions. When `redacted`, both values are null and only `changed` is known. + * `encrypted` marks a protected value that callers should not print unless asked. */ final readonly class HistoryDiff { diff --git a/src/Data/HistoryEntry.php b/src/Data/HistoryEntry.php index 90e6490..f3de3c4 100644 --- a/src/Data/HistoryEntry.php +++ b/src/Data/HistoryEntry.php @@ -9,10 +9,8 @@ use Simtabi\Laranail\Settings\Enums\HistoryOperation; /** - * One version of one setting (§4.3). `oldValue` and `newValue` are the stored payloads exactly as - * the values table held them: encoded, and still encrypted when `oldEncrypted` / `newEncrypted` - * say so. Nothing here is decrypted; {@see HistoryDiff} is where a value is shown, and only to an - * actor allowed to see it. A null payload is "no value" (a tombstone, or a lock row without one). + * One version of one setting. The payloads are stored exactly as the values table held them, still + * encrypted where flagged; a null payload means no value. */ final readonly class HistoryEntry { @@ -45,8 +43,7 @@ public function redacted(): self } /** - * The entry without its payloads where they are encrypted: what may be shown to anyone who - * may read the history (`view_history`) but not the values (`view_sensitive`). + * The entry with encrypted payloads left out. * * @return array */ diff --git a/src/Data/HistoryFilter.php b/src/Data/HistoryFilter.php index 5b35382..9e7e584 100644 --- a/src/Data/HistoryFilter.php +++ b/src/Data/HistoryFilter.php @@ -6,10 +6,7 @@ use Carbon\CarbonImmutable; -/** - * Which history entries to read: one store, optionally narrowed to a scope, key and locale, a - * time window and a version range (inclusive). - */ +/** History query conditions: a store, optionally narrowed by scope, key, locale, time and version. */ final readonly class HistoryFilter { public function __construct( @@ -23,7 +20,7 @@ public function __construct( public ?int $toVersion = null, ) {} - /** A copy with some conditions replaced (named arguments; the rest are kept). */ + /** A copy with the named conditions replaced. */ public function with( ?StoreName $store = null, ?Scope $scope = null, diff --git a/src/Data/HistoryPage.php b/src/Data/HistoryPage.php index 76a8f10..ed592d3 100644 --- a/src/Data/HistoryPage.php +++ b/src/Data/HistoryPage.php @@ -4,10 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * One page of history, newest version first. `nextCursor` / `previousCursor` are opaque strings - * to pass back to `paginate()`; null at either end. - */ +/** One page of history, newest version first, with opaque cursors for `paginate()`. */ final readonly class HistoryPage { /** @param list $entries */ diff --git a/src/Data/Http/WriteInput.php b/src/Data/Http/WriteInput.php index 96899c1..a886b6c 100644 --- a/src/Data/Http/WriteInput.php +++ b/src/Data/Http/WriteInput.php @@ -4,10 +4,7 @@ namespace Simtabi\Laranail\Settings\Data\Http; -/** - * A REST write: where, the value (for a set), the reason, the `If-Match` ETag the client read - * (null: unconditional) and, for a rollback, the version to return to. - */ +/** A REST write: address, value, reason, optional `If-Match` ETag and rollback version. */ final readonly class WriteInput { public function __construct( diff --git a/src/Data/Key.php b/src/Data/Key.php index ced64ab..6bf36e4 100644 --- a/src/Data/Key.php +++ b/src/Data/Key.php @@ -8,10 +8,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidKey; /** - * A setting key: lower-case dot notation of [a-z0-9_] segments, at most 191 characters. - * - * Keys are lower-cased on construction so `Theme` and `theme` are one key on every database. - * A hyphen is not allowed, which keeps the key → slug mapping (`.` → `-`) one-to-one. + * A setting key: lower-case dot notation of [a-z0-9_] segments, at most 191 characters. Hyphens + * are not allowed so the key to slug mapping (`.` to `-`) stays one-to-one. */ final readonly class Key implements Stringable { diff --git a/src/Data/LayerConfig.php b/src/Data/LayerConfig.php index 115cb4d..84c595f 100644 --- a/src/Data/LayerConfig.php +++ b/src/Data/LayerConfig.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * One configured layer: its name, driver name and options. - */ +/** One configured layer: its name, driver and options. */ final readonly class LayerConfig { /** @param array $options */ diff --git a/src/Data/Locale.php b/src/Data/Locale.php index de3da9f..54d4fed 100644 --- a/src/Data/Locale.php +++ b/src/Data/Locale.php @@ -7,10 +7,7 @@ use Stringable; use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -/** - * A setting's locale. The empty locale means "not localised". Others are normalised to - * `ll` or `ll_CC` (`pt-br`, `PT_BR` → `pt_BR`) so two spellings never become two rows. - */ +/** A setting's locale, normalised to `ll` or `ll_CC`; empty means not localised. */ final readonly class Locale implements Stringable { public string $value; diff --git a/src/Data/Lookup.php b/src/Data/Lookup.php index 1194312..10a3850 100644 --- a/src/Data/Lookup.php +++ b/src/Data/Lookup.php @@ -6,10 +6,7 @@ use LogicException; -/** - * The presence-aware result of reading a setting: found (with a value that may be null) or - * missing. Used instead of a nullable return, so "stored null" and "absent" stay distinct. - */ +/** The result of a read: found (the value may be null) or missing. */ final readonly class Lookup { private function __construct( @@ -35,10 +32,7 @@ public static function missing(): self return new self(false, null, null, null); } - /** - * The same answer with its value withheld, for an actor not allowed to see it: presence, - * layer and scope stay visible; {@see value()} throws and {@see valueOr()} returns the default. - */ + /** The same answer with its value withheld; presence, layer and scope stay visible. */ public function redacted(): self { return new self($this->found, null, $this->layer, $this->scope, redacted: true); diff --git a/src/Data/NewCategory.php b/src/Data/NewCategory.php index c98cf2a..1ee3949 100644 --- a/src/Data/NewCategory.php +++ b/src/Data/NewCategory.php @@ -7,11 +7,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; /** - * The input for creating a category: slug and title, optionally a parent (by slug), a - * description, an icon name, a sort position and, for `translations.mode = json` (D-8), the - * title per locale. Under `lang` the translations are ignored: the title is plain text or a - * translation key. `system` marks a category shipped by code or the default seeder - * (`is_system`), which UIs do not let anyone delete. + * The input for creating a category. `translations` apply only in json translations mode; + * `system` marks a category shipped by code. */ final readonly class NewCategory { diff --git a/src/Data/OwnerRef.php b/src/Data/OwnerRef.php index ad3f0c0..d3f3f29 100644 --- a/src/Data/OwnerRef.php +++ b/src/Data/OwnerRef.php @@ -6,10 +6,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -/** - * An owner of settings by morph alias and id, never by class name, so renaming a model class - * does not orphan its settings and resolving parents needs no model loading. - */ +/** An owner of settings by morph alias and id, so renaming a model class orphans nothing. */ final readonly class OwnerRef { public string $alias; diff --git a/src/Data/PromotionReport.php b/src/Data/PromotionReport.php index 0566d8f..929fd6f 100644 --- a/src/Data/PromotionReport.php +++ b/src/Data/PromotionReport.php @@ -4,11 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * What a promotion did, per (scope | key | locale): promoted, or skipped with a reason - * (`exists`: a database row was already there; `undefined`: a strict store no longer defines - * the key). Never carries a value. - */ +/** What a promotion did per identity: promoted, or skipped as `exists` or `undefined`. */ final readonly class PromotionReport { /** diff --git a/src/Data/PromotionRequest.php b/src/Data/PromotionRequest.php index 22ad132..05f881b 100644 --- a/src/Data/PromotionRequest.php +++ b/src/Data/PromotionRequest.php @@ -6,11 +6,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; -/** - * How to promote a store: overwrite keys that already have a database row (`force`), and/or - * replay an archived runtime file (`from`, a path on the runtime layer's disk) instead of the - * live one, for a database restored from a backup taken before the original promotion. - */ +/** Promotion options: `force` overwrites existing rows; `from` replays an archived runtime file. */ final readonly class PromotionRequest { public function __construct( diff --git a/src/Data/Record.php b/src/Data/Record.php index 9324776..f523bb7 100644 --- a/src/Data/Record.php +++ b/src/Data/Record.php @@ -7,14 +7,8 @@ use Carbon\CarbonImmutable; /** - * One stored value as a layer holds it. - * - * `payload` is the encoded value (JSON, or ciphertext of the JSON when `encrypted`). A null - * payload means "no value on this row"; a stored null is the JSON string `null`, so the two - * never collapse into one. - * - * `group`, `category` (a category slug) and `public` are metadata copied from the definition - * when the record is written; file layers ignore them, the database layer stores them. + * One stored value as a layer holds it. `payload` is JSON, or its ciphertext when `encrypted`; + * a null payload means no value, while a stored null is the JSON string `null`. */ final readonly class Record { diff --git a/src/Data/RecordSet.php b/src/Data/RecordSet.php index cb64343..d603d15 100644 --- a/src/Data/RecordSet.php +++ b/src/Data/RecordSet.php @@ -6,9 +6,7 @@ use Countable; -/** - * The records one layer returned for a set of scopes, indexed by (scope, key, locale). - */ +/** The records one layer returned, indexed by scope, key and locale. */ final readonly class RecordSet implements Countable { /** @var array */ diff --git a/src/Data/Scope.php b/src/Data/Scope.php index 29f0fe6..81cf7e2 100644 --- a/src/Data/Scope.php +++ b/src/Data/Scope.php @@ -6,10 +6,7 @@ use Stringable; -/** - * Who a value belongs to: `global` (the application) or `:` for an owner. - * Built only from {@see OwnerRef} or {@see self::global()}, so it is always well formed. - */ +/** Who a value belongs to: `global` or `:`. */ final readonly class Scope implements Stringable { public const string GLOBAL = 'global'; @@ -37,11 +34,7 @@ public static function of(?OwnerRef $owner): self return $owner instanceof OwnerRef ? self::forOwner($owner) : self::global(); } - /** - * Read a stored scope (`global` or `:`). Null when it has no `:`, so the caller - * reports the malformed row in its own words; an invalid alias or id still raises - * InvalidIdentifier through {@see OwnerRef}. - */ + /** Parse a stored scope; null when it has no `:`. */ public static function fromString(string $value): ?self { if ($value === self::GLOBAL) { diff --git a/src/Data/SettingAddress.php b/src/Data/SettingAddress.php index 729d374..c67a107 100644 --- a/src/Data/SettingAddress.php +++ b/src/Data/SettingAddress.php @@ -6,10 +6,7 @@ use Simtabi\Laranail\Settings\Contracts\Settable; -/** - * Where a setting is, as a caller outside PHP names it: a store, a key, an owner (or the global - * value) and a locale ('' for none). - */ +/** A setting's address: store, key, owner or global, and locale. */ final readonly class SettingAddress { public function __construct( @@ -24,7 +21,7 @@ public function ownerRef(): ?OwnerRef return $this->owner instanceof Settable ? $this->owner->settingsOwner() : $this->owner; } - /** `store|scope|key|locale@version`, hashed: the ETag of the setting at that version (§16.10). */ + /** The ETag of the setting at a version. */ public function etag(int $version): string { return '"' . sha1($this->store . '|' . Scope::of($this->ownerRef())->value . '|' . $this->key . '|' . new Locale($this->locale)->value . '@' . $version) . '"'; diff --git a/src/Data/SettingTarget.php b/src/Data/SettingTarget.php index 80ba896..62a37c8 100644 --- a/src/Data/SettingTarget.php +++ b/src/Data/SettingTarget.php @@ -6,10 +6,7 @@ use Simtabi\Laranail\Settings\Stores\Store; -/** - * The input of every write action: one key in one resolved store, for one owner (or global) - * and locale, with its definition and the reason given for the change. - */ +/** The target of a write: store, key, owner, locale, definition and reason. */ final readonly class SettingTarget { public function __construct( @@ -21,10 +18,7 @@ public function __construct( public ?string $reason = null, ) {} - /** - * The subject abilities are checked against. A key matched by the store's `approvals.keys` - * needs approval as if its definition said so (§16.7). - */ + /** The subject abilities are checked against; a key in `approvals.keys` needs approval. */ public function subject(): Subject { $subject = Subject::of($this->store->name, $this->key, $this->locale, $this->owner, $this->definition); diff --git a/src/Data/SettingView.php b/src/Data/SettingView.php index 4fd659e..010fef9 100644 --- a/src/Data/SettingView.php +++ b/src/Data/SettingView.php @@ -4,10 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * A setting as an API answers it: where it was found and at which version of the handle's own - * row (0: no row of its own), and its value unless the actor may not see it (`redacted`). - */ +/** A setting as the API returns it; `version` is 0 when the scope has no row of its own. */ final readonly class SettingView { public function __construct( diff --git a/src/Data/SettingWrite.php b/src/Data/SettingWrite.php index 142737e..2c0c9b8 100644 --- a/src/Data/SettingWrite.php +++ b/src/Data/SettingWrite.php @@ -4,11 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * The input of {@see \Simtabi\Laranail\Settings\Actions\SetSetting}: a target and the value to - * store there. `expectedVersion`, when set, makes the write conditional on the row still being - * at that version (0: no row yet), as a REST `If-Match` will; such a write is never retried. - */ +/** A value to write; `expectedVersion` (0 for no row yet) makes the write conditional. */ final readonly class SettingWrite { public function __construct( diff --git a/src/Data/SettingsMigrationStep.php b/src/Data/SettingsMigrationStep.php index aeaf567..f3a11d1 100644 --- a/src/Data/SettingsMigrationStep.php +++ b/src/Data/SettingsMigrationStep.php @@ -4,12 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * One step of a settings migration (G-17): copy every value of `fromKey` in `fromStore` (every - * owner and locale) to `toKey` in `toStore` and remove the original (a rename or a move); or, with - * no destination, remove the key everywhere (`delete`); or, with a value and no source rows, - * store it as the global value unless one exists (`add`). - */ +/** One settings migration step: a rename or move, a delete, or adding a global value. */ final readonly class SettingsMigrationStep { public const string RENAME = 'rename'; diff --git a/src/Data/StoreName.php b/src/Data/StoreName.php index c926c9b..c4d2feb 100644 --- a/src/Data/StoreName.php +++ b/src/Data/StoreName.php @@ -8,9 +8,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidIdentifier; /** - * A store's logical name: lower-case letters, digits and underscores, starting with a letter, - * at most 64 characters. It is interpolated into file paths and cache keys, so it is validated - * here rather than trusted. + * A store name: lower-case letters, digits and underscores, starting with a letter, at most 64 + * characters. Validated because it ends up in file paths and cache keys. */ final readonly class StoreName implements Stringable { diff --git a/src/Data/Subject.php b/src/Data/Subject.php index 61a4122..724764b 100644 --- a/src/Data/Subject.php +++ b/src/Data/Subject.php @@ -4,10 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -/** - * What an ability is checked against: the store, key, owner and locale, plus the flags of the - * key's definition. Never carries a value. Gates receive it as their argument. - */ +/** What an ability is checked against; gates receive it as their argument. */ final readonly class Subject { public function __construct( diff --git a/src/Data/Transfer/ExportDocument.php b/src/Data/Transfer/ExportDocument.php index ec5024a..e37ce52 100644 --- a/src/Data/Transfer/ExportDocument.php +++ b/src/Data/Transfer/ExportDocument.php @@ -8,10 +8,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidImport; /** - * A store's settings and categories as portable JSON (G-18, G-42): categories by slug, settings by - * scope, key and locale, never a numeric id, so a document moves between databases whatever their - * `ids.type`. Encrypted values follow the {@see ExportMode}. `source` names an importer when the - * document was read from another package (G-43). + * A store's settings and categories as portable JSON, identified without numeric ids. `source` + * names the importer that produced the document, if any. */ final readonly class ExportDocument { diff --git a/src/Data/Transfer/ExportRequest.php b/src/Data/Transfer/ExportRequest.php index 2790f25..17debbd 100644 --- a/src/Data/Transfer/ExportRequest.php +++ b/src/Data/Transfer/ExportRequest.php @@ -7,7 +7,7 @@ use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Enums\ExportMode; -/** The input of an export: the store, and how to write its encrypted values (G-10). */ +/** An export request: the store and how to write its encrypted values. */ final readonly class ExportRequest { public function __construct( diff --git a/src/Data/Transfer/ExportedCategory.php b/src/Data/Transfer/ExportedCategory.php index 96c5eb0..3194f56 100644 --- a/src/Data/Transfer/ExportedCategory.php +++ b/src/Data/Transfer/ExportedCategory.php @@ -10,7 +10,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidImport; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -/** One category in an export, identified by slug; its parent by slug too (G-42). */ +/** One category in an export, with its parent by slug. */ final readonly class ExportedCategory { /** @param array $titles locale => title (json translations mode) */ @@ -55,7 +55,7 @@ public static function fromArray(array $data, int|string $index): self } } - /** The category to create on import; `system` only when the import is trusted (G-10). */ + /** The category to create on import; `system` only when the import is trusted. */ public function toNewCategory(bool $trusted): NewCategory { return new NewCategory($this->slug->value, $this->title === '' ? $this->slug->value : $this->title, $this->parent?->value, $this->description, $this->icon, $this->sortOrder, $this->titles, $trusted && $this->system); diff --git a/src/Data/Transfer/ExportedSetting.php b/src/Data/Transfer/ExportedSetting.php index 1722371..3c5a781 100644 --- a/src/Data/Transfer/ExportedSetting.php +++ b/src/Data/Transfer/ExportedSetting.php @@ -10,11 +10,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidImport; use Simtabi\Laranail\Settings\Exceptions\SettingsException; -/** - * One setting in an export (G-42), identified by scope, key and locale, never by a numeric id. A - * plain value is the stored JSON value as it is; an encrypted value is `redacted` (left out), its - * `ciphertext`, or its decrypted `value`, by the export mode. - */ +/** One setting in an export; an encrypted value is redacted, ciphertext or plaintext by export mode. */ final readonly class ExportedSetting { public function __construct( diff --git a/src/Data/Transfer/ImportReport.php b/src/Data/Transfer/ImportReport.php index ffae349..78eeca2 100644 --- a/src/Data/Transfer/ImportReport.php +++ b/src/Data/Transfer/ImportReport.php @@ -4,11 +4,7 @@ namespace Simtabi\Laranail\Settings\Data\Transfer; -/** - * What an import did, or (dry run) would do: settings created, updated and unchanged by identity - * (`scope|key|locale`), the ones skipped with the reason, the categories created, and the change - * requests opened for settings that need approval. - */ +/** What an import did, or would do in a dry run. */ final readonly class ImportReport { /** diff --git a/src/Data/Transfer/ImportRequest.php b/src/Data/Transfer/ImportRequest.php index 75b3df9..9e46934 100644 --- a/src/Data/Transfer/ImportRequest.php +++ b/src/Data/Transfer/ImportRequest.php @@ -6,11 +6,7 @@ use Simtabi\Laranail\Settings\Stores\Store; -/** - * The input of an import: the store, the document, and how to apply it. Nothing is written - * unless `apply` is set (the default is a dry run). `trusted` lets the document set locks and - * system categories (G-10); otherwise both are ignored. - */ +/** An import request; a dry run unless `apply`, and `trusted` lets the document set locks. */ final readonly class ImportRequest { public function __construct( diff --git a/src/Data/Transfer/StoreDiff.php b/src/Data/Transfer/StoreDiff.php index 061dd2a..4a46b0c 100644 --- a/src/Data/Transfer/StoreDiff.php +++ b/src/Data/Transfer/StoreDiff.php @@ -4,12 +4,7 @@ namespace Simtabi\Laranail\Settings\Data\Transfer; -/** - * A store compared with an export (G-42): identities (`scope|key|locale`) only in the document - * (`added`, as an import would create them), only in the store (`removed`), in both with - * different values (`changed`) or equal ones (`unchanged`), and those that cannot be compared - * because a side is redacted or encrypted (`unknown`). Never carries a value. - */ +/** A store compared with an export, by identity; `unknown` holds those a redacted side hides. */ final readonly class StoreDiff { /** diff --git a/src/Database/SchemaNames.php b/src/Database/SchemaNames.php index b49f8c3..cba41c0 100644 --- a/src/Database/SchemaNames.php +++ b/src/Database/SchemaNames.php @@ -8,10 +8,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The package's table names: `tables.prefix` (D-4) prepended to `tables.categories`, - * `tables.audit`, `tables.definitions`, `tables.history`, `tables.change_requests`, - * `tables.stores` and each store's values table (`stores..table`, default the store name). - * Every name is validated, because it is interpolated into SQL identifiers. + * The package's table names, prefixed and validated for use as SQL identifiers. */ final readonly class SchemaNames { @@ -67,25 +64,25 @@ public function audit(): string return $this->prefix . $this->audit; } - /** The optional definitions table (D-6). */ + /** The optional definitions table. */ public function definitions(): string { return $this->prefix . $this->definitions; } - /** The value history table (§4.3), one per connection like the audit table. */ + /** The value history table, one per connection. */ public function history(): string { return $this->prefix . $this->history; } - /** The change requests table (§16.7), one per connection like the history table. */ + /** The change requests table, one per connection. */ public function changeRequests(): string { return $this->prefix . $this->changeRequests; } - /** The persisted configuration table (§16.11), on the default store's connection. */ + /** The persisted configuration table, on the default store's connection. */ public function stores(): string { return $this->prefix . $this->storesTable; @@ -97,7 +94,7 @@ public function toArray(): array return ['prefix' => $this->prefix, 'categories' => $this->categories, 'audit' => $this->audit, 'definitions' => $this->definitions, 'history' => $this->history, 'change_requests' => $this->changeRequests, 'stores' => $this->storesTable]; } - /** A store's values table: its configured table, or its name, after the prefix. */ + /** A store's values table: its configured table or its name, prefixed. */ public function store(StoreName $store, ?string $configured = null): string { return $this->prefix . ($configured ?? $store->value); diff --git a/src/Database/SchemaShape.php b/src/Database/SchemaShape.php index 18a1822..867cf7b 100644 --- a/src/Database/SchemaShape.php +++ b/src/Database/SchemaShape.php @@ -16,15 +16,10 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The schema the migrations produced (§4.0): every schema switch, the table names and one entry - * per database store. `install` and `make-store` record it in `database/settings-schema.php`, - * and the runtime reads that record rather than live configuration, so changing configuration - * after migrating can never make a query name a column that does not exist. Without a recorded - * file (an application installed before the file existed) the shape is derived from - * configuration, which is what those migrations used. + * The schema the migrations produced: every schema switch, the table names and each database store. * - * `VERSION` is this release's shape version. A recorded file with a lower version means a - * release added columns whose upgrade migration was never published; `doctor` reports it. + * Recorded in `database/settings-schema.php` by `install` and `make-store`; without that file it + * is derived from configuration. `VERSION` is this release's shape version. */ final readonly class SchemaShape { @@ -162,7 +157,7 @@ public static function fromArray(array $data): self TenancyMode::tryFrom(self::text($switches, 'tenancy', 'none')) ?? throw $invalid('tenancy'), // A file recorded before the history table existed describes a schema without it. ($switches['history_table'] ?? false) === true, - // Likewise for the change requests and persisted configuration tables (Phase 4b). + // Likewise for the change requests and persisted configuration tables. ($switches['change_requests_table'] ?? false) === true, ($switches['stores_table'] ?? false) === true, ); @@ -210,7 +205,7 @@ public function hasStore(StoreName $name): bool return isset($this->stores[$name->value]); } - /** A copy with one more store entry (an existing entry is kept: it describes a table already created). */ + /** A copy with one more store; an existing entry is kept, since its table already exists. */ public function withStore(StoreSchema $store): self { if ($this->hasStore($store->name)) { @@ -221,7 +216,7 @@ public function withStore(StoreSchema $store): self } /** - * Every difference from another shape, one line each (`identity: slug_uid → uid_only`). + * Every difference from another shape, one line each. * * @return list */ diff --git a/src/Database/StoreSchema.php b/src/Database/StoreSchema.php index 4925fca..9c5bfb5 100644 --- a/src/Database/StoreSchema.php +++ b/src/Database/StoreSchema.php @@ -11,9 +11,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The recorded shape of one store's values table (§4.0): its mode (D-3), soft deletes (D-9), - * configured table and connection, and, for a dedicated store, the owner table its `owner_id` - * points at and the store that holds its global values. + * The recorded shape of one store's values table. */ final readonly class StoreSchema { @@ -47,9 +45,7 @@ public function __construct( } /** - * Read one `laranail.settings.stores.` entry. `$connection` is the store's database - * layer connection (resolved by the caller from its layers); `$ownerKeyType` is the owner - * key type when the entry does not set one (laranail.db-tools.id_type). + * Read one `laranail.settings.stores.` entry. * * @param array $config */ diff --git a/src/Definitions/DefinitionBuilder.php b/src/Definitions/DefinitionBuilder.php index aa94d56..d8555b1 100644 --- a/src/Definitions/DefinitionBuilder.php +++ b/src/Definitions/DefinitionBuilder.php @@ -10,11 +10,7 @@ use Simtabi\Laranail\Settings\Enums\Precedence; use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; -/** - * A mutable builder for one definition; {@see register()} builds the immutable - * {@see Definition} and adds it to the registry. Flags have paired methods - * (`public()` / `private()`) rather than boolean parameters. - */ +/** Builds one {@see Definition}; {@see register()} adds it to the registry. */ final class DefinitionBuilder { private ?string $store = null; @@ -157,10 +153,7 @@ public function requiresVerification(): self return $this; } - /** - * Writes need a second person's approval. Approvals arrive with the database layer; until - * then every write to such a setting raises ApprovalUnavailable. - */ + /** Writes need a second person's approval; without a change requests table they raise ApprovalUnavailable. */ public function requiresApproval(): self { $this->requiresApproval = true; diff --git a/src/Drivers/ArrayDriver.php b/src/Drivers/ArrayDriver.php index 59a7168..f88fd8c 100644 --- a/src/Drivers/ArrayDriver.php +++ b/src/Drivers/ArrayDriver.php @@ -13,7 +13,7 @@ use Simtabi\Laranail\Settings\Contracts\Driver; /** - * Holds records for the lifetime of this instance only. Used by tests and by the fake. + * Holds records in memory for the lifetime of the instance. */ final class ArrayDriver implements Driver { diff --git a/src/Drivers/BootstrapGatedDriver.php b/src/Drivers/BootstrapGatedDriver.php index 6d1a72e..c70f2cc 100644 --- a/src/Drivers/BootstrapGatedDriver.php +++ b/src/Drivers/BootstrapGatedDriver.php @@ -17,19 +17,16 @@ use Simtabi\Laranail\Settings\Stores\InstallationEvidence; /** - * The database layer of a store in bootstrap mode (`stores..bootstrap`). The layer is - * skipped only while there is positive evidence that the application is being installed AND the - * database is not ready; a skipped layer reads nothing and accepts no writes, so writes go to - * the next writable layer (the runtime file). Without evidence it is exactly the database layer: - * an outage then raises DriverUnavailable, never a silent fallback (G-36). + * The database layer of a store in bootstrap mode, skipped while the application is being installed. * - * Nothing is checked at construction; the first read or write decides. + * Without evidence of an install it behaves as the database layer, so an outage still raises + * DriverUnavailable. */ final class BootstrapGatedDriver implements DatabaseBacked { private bool $reported = false; - /** @param ?Dispatcher $events told ({@see LayerSkipped}) the first time the layer named `$layer` is skipped */ + /** @param ?Dispatcher $events receives {@see LayerSkipped} the first time the layer is skipped */ public function __construct( private readonly DatabaseDriver $inner, private readonly StoreName $store, diff --git a/src/Drivers/CachingDriver.php b/src/Drivers/CachingDriver.php index 7c58112..f5749f6 100644 --- a/src/Drivers/CachingDriver.php +++ b/src/Drivers/CachingDriver.php @@ -15,19 +15,10 @@ use Simtabi\Laranail\Settings\Services\Cache\SettingsCache; /** - * A database layer behind the settings cache (design §7.3, §7.5): reads come from cached per-scope - * bags, and every write through it replaces the written scope's generation token once the write - * has committed. + * A database layer read through the settings cache, invalidated after each write commits. * - * The cache is bypassed, read and write, whenever it could disagree with the database: - * - * - while the layer is inactive (bootstrap mode skipping it), so an empty pre-install read is - * never cached and served after the install; - * - while a transaction is open on the layer's connection, so a write's own transaction reads - * its uncommitted rows and nothing uncommitted (or later rolled back) ever reaches the cache. - * - * Writes that reach the database without passing through here (flushing a scope, promotion) ask - * the store to forget the affected bags; see {@see forgetScope()} and {@see forgetStore()}. + * The cache is bypassed while the layer is inactive or a transaction is open, so nothing + * uncommitted or pre-install is ever cached. */ final readonly class CachingDriver implements DatabaseBacked { @@ -36,7 +27,7 @@ public function __construct( private SettingsCache $cache, ) {} - /** The layer this one caches, for callers that must read the database itself. */ + /** The uncached database layer. */ public function uncached(): DatabaseBacked { return $this->inner; @@ -78,21 +69,20 @@ public function forget(StoreName $store, Scope $scope, Key $key, Locale $locale) $this->forgetScope($store, $scope); } - /** Invalidate one scope's bag, once the surrounding transaction (if any) commits. */ + /** Invalidate one scope's bag once the surrounding transaction commits. */ public function forgetScope(StoreName $store, Scope $scope): void { $this->afterCommit(fn () => $this->cache->forgetScope($this->target($store), $scope)); } - /** Invalidate every bag of the store, once the surrounding transaction (if any) commits. */ + /** Invalidate every bag of the store once the surrounding transaction commits. */ public function forgetStore(StoreName $store): void { $this->afterCommit(fn () => $this->cache->forgetStore($this->target($store))); } /** - * Run an invalidation when the layer's connection commits: straight away outside a - * transaction, never for a transaction that rolls back (nothing changed). + * Run an invalidation when the connection commits, or now outside a transaction. * * @param callable(): void $invalidate */ diff --git a/src/Drivers/ConfigDriver.php b/src/Drivers/ConfigDriver.php index 2eddf78..0bc29ef 100644 --- a/src/Drivers/ConfigDriver.php +++ b/src/Drivers/ConfigDriver.php @@ -15,8 +15,7 @@ use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; /** - * A read-only view over one Laravel config prefix. Nested associative arrays become dotted - * keys; a list (`[a, b]`) stays one value. + * A read-only view over one Laravel config prefix; nested arrays become dotted keys, lists stay values. */ final readonly class ConfigDriver implements Driver { diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index 81c4cd2..010665c 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -39,20 +39,11 @@ use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; /** - * Records in a database table, through the query builder (no Eloquent on the hot path). + * Stores records in a database table through the query builder. * - * Reads take every scope in one `whereIn('scope', …)` query, so the owner key type never meets - * the column type (G-26). Writes are version-checked: an update succeeds only against the - * version the writer read, and an insert runs in a savepoint so a unique violation (a concurrent - * first write) does not abort the surrounding transaction on Postgres. Either conflict raises - * {@see ConcurrentModification}. Database errors surface as {@see DriverUnavailable} when the - * connection or table is gone, {@see DriverFailure} otherwise, never as PDO exceptions. - * - * The table's shape (identity columns, key type, owner columns, soft deletes) is read from the - * recorded {@see SchemaShape}, never from live configuration (§4.0). With soft deletes a forget - * trashes the row, reads skip trashed rows, and the next write to that identity restores the - * row through the same version check (so a restore is never read as a conflict and the unique - * index never collides). + * Writes are version-checked and raise {@see ConcurrentModification} on a conflict. Database + * errors surface as {@see DriverUnavailable} or {@see DriverFailure}, never as PDO exceptions. + * The table's shape comes from the recorded {@see SchemaShape}, not from live configuration. */ final readonly class DatabaseDriver implements DatabaseBacked { @@ -76,8 +67,7 @@ public function __construct( ) {} /** - * A new primary key for a table keyed by this type: none for bigint (the database assigns - * it), a time-ordered UUID or a ULID otherwise. + * A new primary key for this key type; empty for bigint, which the database assigns. * * @return array{id?: string} */ @@ -98,7 +88,7 @@ public function shape(): SchemaShape return $shape instanceof SchemaShape ? $shape : new SchemaShape(names: $this->names); } - /** One store's recorded entry: mode, soft deletes, owner table. */ + /** The recorded schema of one store. */ public function schemaOf(StoreName $store): StoreSchema { return $this->shape()->store($store); @@ -119,7 +109,7 @@ public function isWritable(): bool return $this->writable; } - /** The connection name this layer uses (the default connection when none is configured). */ + /** The connection this layer uses, or the default connection. */ public function connectionName(): string { return $this->connection ?? $this->db->getDefaultConnection(); @@ -132,10 +122,7 @@ public function tableFor(StoreName $store): string return $shape->names->store($store, $shape->hasStore($store) ? $shape->store($store)->table : $this->table); } - /** - * The tenant the rows of this call belong to, in column-mode tenancy: the discriminator's - * key, or '' (the central rows) outside any tenant. Always '' in the other modes. - */ + /** The current tenant in column-mode tenancy; '' for central rows and in other modes. */ public function tenant(): string { if (! $this->shape()->tenancy->hasColumn() || ! $this->tenant instanceof Closure) { @@ -147,10 +134,7 @@ public function tenant(): string return is_string($tenant) ? $tenant : ''; } - /** - * Limit a query on a values, categories or audit table to the current tenant (column-mode - * tenancy); any other mode leaves it as it is. - */ + /** Limit a query to the current tenant in column-mode tenancy. */ public function scoped(Builder $query): Builder { return $this->shape()->tenancy->hasColumn() ? $query->where('tenant', $this->tenant()) : $query; @@ -206,10 +190,10 @@ public function load(StoreName $store, array $scopes): RecordSet } /** - * Store a record whose version is one above the version the writer read: an update checked - * against that version; with soft deletes, failing that, a restore of the trashed row at that - * version; failing that, an insert. A row at any other version makes the insert hit the - * unique index, which is a concurrent change. + * Store a record one version above the version the writer read. + * + * Tries an update at that version, then a restore of a trashed row, then an insert; a row at + * any other version makes the insert hit the unique index. * * @throws ConcurrentModification */ @@ -229,8 +213,7 @@ public function put(StoreName $store, Record $record): void return; } - // A trashed row at the expected version: restore it as a fresh write, so no flag, - // label or category of the forgotten row comes back with it. + // Restore as a fresh write so nothing from the forgotten row comes back. if ($expected > 0 && $softDeletes && $this->trashed($store)->where('scope', $record->scope->value)->where('key', $record->key->value)->where('locale', $record->locale->value)->where('version', $expected)->update($columns + [ 'deleted_at' => null, 'label' => null, @@ -242,11 +225,8 @@ public function put(StoreName $store, Record $record): void return; } - // No row at the expected version: insert. If a row exists at another version - // (a concurrent writer), the unique index refuses the insert. try { - // A savepoint: on Postgres a unique violation would otherwise abort the - // whole surrounding transaction, not just this statement. + // A savepoint: on Postgres a unique violation would abort the whole transaction. $this->connection()->transaction(fn (): bool => $this->table($store)->insert($columns + $this->identityColumns($record) + $this->tenantColumns() + [ 'scope' => $record->scope->value, 'key' => $record->key->value, @@ -262,10 +242,7 @@ public function put(StoreName $store, Record $record): void }); } - /** - * The version of the trashed row of this identity (0 when there is none, or the store keeps - * no trashed rows), so a write over it continues its version rather than colliding. - */ + /** The version of this identity's trashed row, or 0 when there is none. */ public function trashedVersion(StoreName $store, Scope $scope, Key $key, Locale $locale): int { if (! $this->schemaOf($store)->softDeletes) { @@ -278,9 +255,9 @@ public function trashedVersion(StoreName $store, Scope $scope, Key $key, Locale } /** - * The live row of one identity read under a row lock (`SELECT … FOR UPDATE` where the - * database has one), for retrying a write after a conflict: a plain re-read under MySQL's - * REPEATABLE READ would see the old snapshot. + * Read one live row under a row lock, for retrying a write after a conflict. + * + * A plain re-read under MySQL's REPEATABLE READ would see the old snapshot. */ public function lockedFind(StoreName $store, Scope $scope, Key $key, Locale $locale): ?Record { @@ -291,11 +268,7 @@ public function lockedFind(StoreName $store, Scope $scope, Key $key, Locale $loc }); } - /** - * The stable reference of one identity's row (live or trashed) for the history table: its - * `uid` when the identity mode has one, else its primary key, as a string. Null when there is - * no row. - */ + /** The row's `uid`, or its primary key, as the history table references it. */ public function reference(StoreName $store, Scope $scope, Key $key, Locale $locale): ?string { $column = $this->shape()->identity->hasUid() ? 'uid' : 'id'; @@ -314,7 +287,7 @@ public function forget(StoreName $store, Scope $scope, Key $key, Locale $locale) : $this->identity($this->table($store), $scope, $key, $locale)->delete()); } - /** Remove every row of one scope; returns how many went. */ + /** Delete every row of one scope and return how many were deleted. */ public function flushScope(StoreName $store, Scope $scope): int { $this->assertWritable($store); @@ -325,9 +298,9 @@ public function flushScope(StoreName $store, Scope $scope): int } /** - * Every distinct owner scope of one alias in this store (`alias:`) with live rows, for - * orphan pruning. A range on the binary-collated column rather than LIKE, whose `_` would - * match any character. + * Every distinct live owner scope of one alias. + * + * Uses a range on the binary-collated column, since `_` in a LIKE pattern matches anything. * * @return list */ @@ -345,11 +318,7 @@ public function scopesOf(StoreName $store, string $alias): array ))); } - /** - * Every distinct scope in the store, for diagnostics. - * - * @return list - */ + /** @return list */ public function scopes(StoreName $store): array { return $this->attempt($store, fn (): array => array_values(array_filter( @@ -359,14 +328,11 @@ public function scopes(StoreName $store): array } /** - * Rewrite every encrypted payload of the store, every tenant's and trashed rows included - * (re-encryption after a key rotation), in chunks by primary key. `$rewrite` returns the new - * payload, or null when it could not read the old one (counted as failed, left as it was). - * Returns [rewritten, failed]. + * Rewrite every encrypted payload in the store, across tenants and trashed rows. * - * @param Closure(string): ?string $rewrite + * @param Closure(string): ?string $rewrite returns the new payload, or null when the old one cannot be read * - * @return array{int, int} + * @return array{int, int} rewritten and failed counts */ public function rewriteEncrypted(StoreName $store, Closure $rewrite): array { @@ -400,10 +366,9 @@ public function rewriteEncrypted(StoreName $store, Closure $rewrite): array } /** - * Rename an owner alias in the store (G-30): every scope `:` becomes `:`, - * with `settable_type` in a polymorphic store and the per-row slug of `slug_per_row`, for - * every tenant and trashed rows too, in chunks. Returns how many rows changed. A row whose new - * identity already exists makes the database refuse the rename (DriverFailure). + * Rename an owner alias across every tenant and trashed row, and return how many rows changed. + * + * @throws DriverFailure when a renamed row collides with an existing one */ public function rescope(StoreName $store, string $from, string $to): int { @@ -441,8 +406,7 @@ public function rescope(StoreName $store, string $from, string $to): int } /** - * Run a callback in one transaction on this layer's connection. The store only names the - * store in an outage message. + * Run a callback in one transaction on this layer's connection. * * @template T * @@ -452,8 +416,7 @@ public function rescope(StoreName $store, string $from, string $to): int */ public function transaction(Closure $callback, StoreName $store = new StoreName('settings')): mixed { - // Connect first, so an unreachable database is reported like any other outage rather - // than escaping from BEGIN as a framework exception. + // Connect first, so an unreachable database is reported as an outage. $connection = $this->attempt($store, function (): Connection { $connection = $this->connection(); $connection->getPdo(); @@ -465,8 +428,7 @@ public function transaction(Closure $callback, StoreName $store = new StoreName( } /** - * Run a database operation, translating whatever the database throws into this package's - * exceptions. The package's own exceptions pass through untouched. + * Run a database operation, translating database errors into this package's exceptions. * * @template T * @@ -489,13 +451,11 @@ public function attempt(StoreName $store, Closure $operation): mixed } } - /** Asked after a failure, so the answer is fresh; a probe that itself fails means not ready. */ /** - * Whether the layer is still there after a failure. Outside a transaction the readiness probe - * asks the database. Inside one it cannot: PostgreSQL refuses every statement in an aborted - * transaction, so the probe would report a healthy table as missing. There the SQLSTATE - * decides instead: a missing table (42S02, 42P01, SQLite's "no such table") or a connection - * failure (class 08) means unavailable; anything else is a failure of a live layer. + * Whether the layer is still there after a failure. + * + * Inside a transaction the SQLSTATE decides, because PostgreSQL refuses every statement in an + * aborted transaction and a probe would report a healthy table as missing. */ private function readyAfterFailure(StoreName $store, Exception $exception): bool { @@ -527,13 +487,13 @@ private function signalsUnavailable(Exception $exception): bool || str_contains($exception->getMessage(), 'no such table'); } - /** The store's values table, limited to the current tenant (column-mode tenancy). */ + /** The store's values table, limited to the current tenant. */ private function table(StoreName $store): Builder { return $this->scoped($this->connection()->table($this->tableFor($store))); } - /** Rows that are not trashed (every row, without soft deletes). */ + /** Rows that are not trashed. */ private function live(StoreName $store): Builder { $query = $this->table($store); @@ -575,9 +535,7 @@ private function columns(StoreName $store, Record $record): array } /** - * The owner columns of a row, per the store's mode: `settable_type` / `settable_id` (typed per - * `ids.owner_key`) in a polymorphic store, `owner_id` in a dedicated one, which holds owner - * rows only. + * The owner columns of a row for the store's mode. * * @return array * @@ -609,7 +567,7 @@ private function ownerColumns(StoreName $store, Scope $scope): array return ['owner_id' => $this->typedKey($store, $id, $schema->ownerKeyType)]; } - /** An owner id as the typed column holds it: an integer for bigint keys. */ + /** An owner id cast to the column's type. */ private function typedKey(StoreName $store, string $id, IdType $type): int|string { return match ($type) { @@ -620,8 +578,7 @@ private function typedKey(StoreName $store, string $id, IdType $type): int|strin } /** - * The columns only an insert sets: a generated primary key (uuid, ulid) and the identity - * columns of the identity mode (D-1). + * The columns only an insert sets: a generated key and the identity columns. * * @return array */ @@ -638,10 +595,9 @@ private function identityColumns(Record $record): array } /** - * The id of the record's category in this store (G-33). A category of that slug existing only - * in another store is refused; a slug no store has is left unlinked. + * The id of the record's category in this store, or null when no store has the slug. * - * @throws CategoryStoreMismatch + * @throws CategoryStoreMismatch when the slug belongs to another store only */ private function categoryId(StoreName $store, Record $record): int|string|null { diff --git a/src/Drivers/JsonDriver.php b/src/Drivers/JsonDriver.php index 446e786..5a397e4 100644 --- a/src/Drivers/JsonDriver.php +++ b/src/Drivers/JsonDriver.php @@ -19,11 +19,10 @@ use Simtabi\Laranail\Settings\Support\RecordSerializer; /** - * Records in a JSON file on a filesystem disk, one file per store (`{store}` in the path). + * Stores records in a JSON file on a filesystem disk, one file per store. * - * Writes go to a temporary file that is then moved over the real one, which is an atomic rename - * on local disks. There is no cross-process lock: concurrent writers can lose an update, which - * is acceptable for the install-time runtime layer this driver exists for, and is documented. + * Writes replace the file through an atomic rename. There is no cross-process lock, so concurrent + * writers can lose an update. */ final readonly class JsonDriver implements Driver { @@ -64,7 +63,7 @@ public function isWritable(): bool } /** - * Every record in the store's file, for promotion to the database. + * Every record in the store's file. * * @return list */ @@ -74,8 +73,7 @@ public function all(StoreName $store): array } /** - * Every record in another file on the same disk: a promoted archive being replayed. The path - * comes from an operator, so it may not climb out of the disk. + * Every record in another file on the same disk; the path may not leave the disk. * * @return list */ @@ -94,10 +92,7 @@ public function recordsIn(string $path): array return $exists ? array_values($this->readPath($path)) : throw new DriverFailure(sprintf('Settings file [%s] does not exist.', $path)); } - /** - * Move the store's file aside as `.promoted-.json` once its records are in - * the database. Returns the archive's path, or null when there was no file. - */ + /** Move the store's file aside after promotion and return the archive's path, if any. */ public function archive(StoreName $store, CarbonImmutable $at): ?string { $path = $this->path($store); diff --git a/src/Drivers/PhpDriver.php b/src/Drivers/PhpDriver.php index 678f3ad..b2eaff1 100644 --- a/src/Drivers/PhpDriver.php +++ b/src/Drivers/PhpDriver.php @@ -15,9 +15,7 @@ use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; /** - * A read-only PHP file returning `['dotted.key' => value]`: the shipped-defaults layer. - * Keys are flat and dotted at the top level, so a value may itself be an array. A missing file - * is an empty layer. Opcache keeps the file cheap to read on every request. + * A read-only PHP file returning `['dotted.key' => value]`; a missing file is an empty layer. */ final class PhpDriver implements Driver { diff --git a/src/Drivers/ReadOnlyValues.php b/src/Drivers/ReadOnlyValues.php index e227525..4931f9b 100644 --- a/src/Drivers/ReadOnlyValues.php +++ b/src/Drivers/ReadOnlyValues.php @@ -15,8 +15,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidSettingValue; /** - * Turns a flat `key => raw value` map (a shipped file, a config prefix) into global, - * non-localised records. Shared by the read-only drivers. + * Turns a flat `key => value` map into global, unlocalised records for the read-only drivers. */ final readonly class ReadOnlyValues { diff --git a/src/Enums/Ability.php b/src/Enums/Ability.php index 8f2a29d..8559088 100644 --- a/src/Enums/Ability.php +++ b/src/Enums/Ability.php @@ -9,9 +9,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * Everything an actor can be authorized to do. Each case is checked as the gate - * `laranail-settings.` by the gate authorizer and, for a token-bearing actor, must also be - * among the token's abilities as `settings:` (or `settings:*`). + * Everything an actor can be authorized to do: the gate `laranail-settings.`, and for a + * token-bearing actor the token ability `settings:`. */ enum Ability: string implements Enumerator { diff --git a/src/Enums/ActorType.php b/src/Enums/ActorType.php index c45de8a..e0e1f4c 100644 --- a/src/Enums/ActorType.php +++ b/src/Enums/ActorType.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Enumerator\Contracts\Enumerator; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * Who an actor is: a user, trusted system code, an API token or a named service. - */ +/** Who an actor is: a user, trusted system code, an API token or a named service. */ enum ActorType: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/AuditAction.php b/src/Enums/AuditAction.php index 38a35ca..c552b0f 100644 --- a/src/Enums/AuditAction.php +++ b/src/Enums/AuditAction.php @@ -8,10 +8,7 @@ use Simtabi\Laranail\Enumerator\Contracts\Enumerator; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * What an audit entry records: every {@see Ability}, plus configuration changes and the - * governance operations (proposals and their decisions, re-encryption, rescoping, settings migrations). - */ +/** What an audit entry records: every {@see Ability}, plus configuration and maintenance operations. */ enum AuditAction: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/AuditOutcome.php b/src/Enums/AuditOutcome.php index 3a68827..9f8746b 100644 --- a/src/Enums/AuditOutcome.php +++ b/src/Enums/AuditOutcome.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Enumerator\Contracts\Enumerator; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * How an audited action ended. Values are never part of an audit entry. - */ +/** How an audited action ended. */ enum AuditOutcome: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/ChangeOperation.php b/src/Enums/ChangeOperation.php index c4f63c4..3d86d30 100644 --- a/src/Enums/ChangeOperation.php +++ b/src/Enums/ChangeOperation.php @@ -8,7 +8,7 @@ use Simtabi\Laranail\Enumerator\Contracts\Enumerator; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** The write a change request (§16.7) applies once it is approved. */ +/** The write a change request applies once it is approved. */ enum ChangeOperation: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/ChangeStatus.php b/src/Enums/ChangeStatus.php index 567ba47..abab010 100644 --- a/src/Enums/ChangeStatus.php +++ b/src/Enums/ChangeStatus.php @@ -9,8 +9,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * Where a change request (§16.7) stands. Only `pending` can still be decided; `approved` is a - * request that has some approvals but needs more; the others are final. + * Where a change request stands. `pending` and `approved` (some approvals, more needed) are + * open; the others are final. */ enum ChangeStatus: string implements Enumerator { diff --git a/src/Enums/Channel.php b/src/Enums/Channel.php index 473b01c..c63432a 100644 --- a/src/Enums/Channel.php +++ b/src/Enums/Channel.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Enumerator\Contracts\Enumerator; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * The surface a call arrived through. Recorded in the audit trail. - */ +/** The surface a call arrived through, recorded in the audit trail. */ enum Channel: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/DriverType.php b/src/Enums/DriverType.php index 04ca406..1647c7c 100644 --- a/src/Enums/DriverType.php +++ b/src/Enums/DriverType.php @@ -10,11 +10,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * The closed set of built-in layer drivers. - * - * Driver names come from configuration an operator edits, so they resolve through this enum - * and an exhaustive match, never by interpolating the name into a method or class name. - * Custom drivers are registered with closures on the DriverFactory. + * The built-in layer drivers. Names from configuration resolve through this enum, never by + * interpolating a method name; custom drivers register on the DriverFactory. */ enum DriverType: string implements Enumerator { diff --git a/src/Enums/ExportMode.php b/src/Enums/ExportMode.php index d5bc49c..24098e0 100644 --- a/src/Enums/ExportMode.php +++ b/src/Enums/ExportMode.php @@ -9,10 +9,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * How an export (G-10) writes encrypted values: left out (`redacted`, the default), as the - * ciphertext stored (`ciphertext`, importable under the same `APP_KEY` or one in - * `APP_PREVIOUS_KEYS`), or decrypted (`plaintext`, which needs `view_sensitive` and, on the - * console, typing the store name). + * How an export writes encrypted values: left out (`redacted`, the default), as stored + * ciphertext, or decrypted (`plaintext`, which needs `view_sensitive`). */ enum ExportMode: string implements Enumerator { diff --git a/src/Enums/HistoryOperation.php b/src/Enums/HistoryOperation.php index b55607e..89e77d0 100644 --- a/src/Enums/HistoryOperation.php +++ b/src/Enums/HistoryOperation.php @@ -9,8 +9,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * What produced a history entry (§4.3). A `forget` entry is a tombstone: it records the version - * that was removed and has no new value; the next write continues the version after it. + * What produced a history entry. A `forget` entry is a tombstone with no new value; the next + * write continues from its version. */ enum HistoryOperation: string implements Enumerator { diff --git a/src/Enums/IdType.php b/src/Enums/IdType.php index b75dab9..adafdba 100644 --- a/src/Enums/IdType.php +++ b/src/Enums/IdType.php @@ -9,10 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * The key type of the package's tables and of every foreign key to them (D-5, `ids.type`). - * Unset, it follows `laranail.db-tools.id_type`. - */ +/** The key type of the package's tables (`ids.type`); unset, it follows `laranail.db-tools.id_type`. */ enum IdType: string implements Enumerator { use HasEnumeratorBehavior; @@ -29,9 +26,7 @@ enum IdType: string implements Enumerator #[Description('A ULID generated by the package (26 characters).')] case Ulid = 'ulid'; - /** - * Read a configured value: these names, or laranail/db-tools' upper-case BIGINT / UUID / ULID. - */ + /** Read a configured value, accepting db-tools' upper-case names too. */ public static function parse(string $value): ?self { return self::tryFrom(strtolower(trim($value))); diff --git a/src/Enums/IdentityMode.php b/src/Enums/IdentityMode.php index ca1c303..d0d8a68 100644 --- a/src/Enums/IdentityMode.php +++ b/src/Enums/IdentityMode.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * How a values row is identified besides (scope, key, locale) (D-1, `identity.mode`). - */ +/** How a values row is identified besides scope, key and locale (`identity.mode`). */ enum IdentityMode: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/OwnerKeyType.php b/src/Enums/OwnerKeyType.php index 9c7871b..6873148 100644 --- a/src/Enums/OwnerKeyType.php +++ b/src/Enums/OwnerKeyType.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * How a polymorphic store types `settable_id` (D-5, `ids.owner_key`). - */ +/** How a polymorphic store types `settable_id` (`ids.owner_key`). */ enum OwnerKeyType: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/Precedence.php b/src/Enums/Precedence.php index a6ef054..85a811b 100644 --- a/src/Enums/Precedence.php +++ b/src/Enums/Precedence.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * Which source wins for a setting, declared on its definition. - */ +/** Which source wins for a setting, declared on its definition. */ enum Precedence: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/StoreMode.php b/src/Enums/StoreMode.php index 87af322..ed980e5 100644 --- a/src/Enums/StoreMode.php +++ b/src/Enums/StoreMode.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * How a store's values table records owners (D-3, `stores..mode`). - */ +/** How a store's values table records owners (`stores..mode`). */ enum StoreMode: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/TenancyMode.php b/src/Enums/TenancyMode.php index c03d105..20759b3 100644 --- a/src/Enums/TenancyMode.php +++ b/src/Enums/TenancyMode.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * How settings are kept apart per tenant (Amendment B, `tenancy.mode`). - */ +/** How settings are kept apart per tenant (`tenancy.mode`). */ enum TenancyMode: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/TranslationsMode.php b/src/Enums/TranslationsMode.php index 2aa038c..14e0d94 100644 --- a/src/Enums/TranslationsMode.php +++ b/src/Enums/TranslationsMode.php @@ -9,10 +9,7 @@ use Simtabi\Laranail\Enumerator\Attributes\Description; use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; -/** - * How categories and definitions store their titles, labels and descriptions (D-8, - * `translations.mode`). - */ +/** How titles, labels and descriptions are stored (`translations.mode`). */ enum TranslationsMode: string implements Enumerator { use HasEnumeratorBehavior; diff --git a/src/Enums/Verdict.php b/src/Enums/Verdict.php index a98188a..0e73635 100644 --- a/src/Enums/Verdict.php +++ b/src/Enums/Verdict.php @@ -9,9 +9,8 @@ use Simtabi\Laranail\Enumerator\Concerns\HasEnumeratorBehavior; /** - * The kind of {@see \Simtabi\Laranail\Settings\Data\Decision} an authorizer returns. `abstain` - * means "no opinion": the next authorizer in a chain decides, and if none does, - * `authorization.undefined` applies. + * The kind of {@see \Simtabi\Laranail\Settings\Data\Decision} an authorizer returns. When every + * authorizer abstains, `authorization.undefined` decides. */ enum Verdict: string implements Enumerator { diff --git a/src/Events/AccessWasDenied.php b/src/Events/AccessWasDenied.php index 0eb8acc..d9c97ab 100644 --- a/src/Events/AccessWasDenied.php +++ b/src/Events/AccessWasDenied.php @@ -9,12 +9,10 @@ use Simtabi\Laranail\Settings\Enums\Ability; /** - * An actor was refused an ability (or a call without an actor was refused because one is - * required). Dispatched at once, not after commit: the refusal throws, so a transaction around - * it usually rolls back, and a security listener must still hear of it. Never carries a value. + * An actor was refused an ability. Dispatched at once rather than after commit, because the + * refusal usually rolls the surrounding transaction back and a listener must still hear of it. * - * `$refusal` is the audit's refusal code: `access_denied`, `approval_unavailable` or - * `actor_required`; `$reason` the authorizer's explanation, when it gave one. + * `$refusal` is `access_denied`, `approval_unavailable` or `actor_required`. */ final readonly class AccessWasDenied { diff --git a/src/Events/AuditPruned.php b/src/Events/AuditPruned.php index a969a42..97b3700 100644 --- a/src/Events/AuditPruned.php +++ b/src/Events/AuditPruned.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Audit entries older than the retention period were deleted: how many, and the period. - */ +/** Audit entries older than the retention period were deleted. */ final readonly class AuditPruned implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/CategoryDeleted.php b/src/Events/CategoryDeleted.php index d279746..d2b266a 100644 --- a/src/Events/CategoryDeleted.php +++ b/src/Events/CategoryDeleted.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A category was deleted (after the transaction commits). - */ +/** A category was deleted. */ final readonly class CategoryDeleted implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/CategoryDeleting.php b/src/Events/CategoryDeleting.php index 8ae5bc4..4addfd6 100644 --- a/src/Events/CategoryDeleting.php +++ b/src/Events/CategoryDeleting.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A category is about to be deleted; its children and settings are unlinked from it. - */ +/** A category is about to be deleted; its children and settings are unlinked from it. */ final readonly class CategoryDeleting implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/CategoryMoved.php b/src/Events/CategoryMoved.php index a6cb975..16694eb 100644 --- a/src/Events/CategoryMoved.php +++ b/src/Events/CategoryMoved.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A category was moved under another parent (null: to the top level). Dispatched after - * commit, besides CategorySaved, which cannot say what changed. - */ +/** A category was moved under another parent, or to the top level when the parent is null. */ final readonly class CategoryMoved implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/CategoryRenamed.php b/src/Events/CategoryRenamed.php index 07c85c6..872eaf2 100644 --- a/src/Events/CategoryRenamed.php +++ b/src/Events/CategoryRenamed.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A category's title changed (its slug, the identifier, did not). Dispatched after commit, - * besides CategorySaved. - */ +/** A category's title changed. */ final readonly class CategoryRenamed implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/CategorySaved.php b/src/Events/CategorySaved.php index efb2052..5518768 100644 --- a/src/Events/CategorySaved.php +++ b/src/Events/CategorySaved.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A category was created, renamed or moved (after the transaction commits). - */ +/** A category was created, renamed or moved. */ final readonly class CategorySaved implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/CategorySaving.php b/src/Events/CategorySaving.php index eecb6b4..2e5575d 100644 --- a/src/Events/CategorySaving.php +++ b/src/Events/CategorySaving.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A category is about to be created, renamed or moved. - */ +/** A category is about to be created, renamed or moved. */ final readonly class CategorySaving implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ChangeApplied.php b/src/Events/ChangeApplied.php index ba59816..5b83794 100644 --- a/src/Events/ChangeApplied.php +++ b/src/Events/ChangeApplied.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * An approved change request was written through the normal write pipeline as `$version`. Dispatched after commit; identifiers only, never the proposed value. - */ +/** An approved change request was written as `$version`. */ final readonly class ChangeApplied implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ChangeApproved.php b/src/Events/ChangeApproved.php index 5bd65f7..817b05c 100644 --- a/src/Events/ChangeApproved.php +++ b/src/Events/ChangeApproved.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A change request received an approval (`$remaining` more are needed before it applies). Dispatched after commit; identifiers only, never the proposed value. - */ +/** A change request received an approval; `$remaining` more are needed. */ final readonly class ChangeApproved implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ChangeCancelled.php b/src/Events/ChangeCancelled.php index 97e61d2..96146b9 100644 --- a/src/Events/ChangeCancelled.php +++ b/src/Events/ChangeCancelled.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A change request was cancelled by its requester; nothing was written. Dispatched after commit; identifiers only, never the proposed value. - */ +/** A change request was cancelled by its requester. */ final readonly class ChangeCancelled implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ChangeRejected.php b/src/Events/ChangeRejected.php index 188f22b..84f5f67 100644 --- a/src/Events/ChangeRejected.php +++ b/src/Events/ChangeRejected.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A change request was rejected; nothing was written. Dispatched after commit; identifiers only, never the proposed value. - */ +/** A change request was rejected. */ final readonly class ChangeRejected implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ChangeRequested.php b/src/Events/ChangeRequested.php index 0431b79..1447795 100644 --- a/src/Events/ChangeRequested.php +++ b/src/Events/ChangeRequested.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A change request was opened: the write waits for approval. Dispatched after commit; identifiers only, never the proposed value. - */ +/** A change request was opened. */ final readonly class ChangeRequested implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ChangeStale.php b/src/Events/ChangeStale.php index bf9c52d..30a3b88 100644 --- a/src/Events/ChangeStale.php +++ b/src/Events/ChangeStale.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * An approved change request was not applied: its setting changed after the request was opened, so it is stale. Dispatched after commit; identifiers only, never the proposed value. - */ +/** An approved change request was not applied because its setting changed since it was opened. */ final readonly class ChangeStale implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/DefinitionsSynced.php b/src/Events/DefinitionsSynced.php index f4f02f9..3342d32 100644 --- a/src/Events/DefinitionsSynced.php +++ b/src/Events/DefinitionsSynced.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Code and config definitions were copied into the definitions table: counts only. - */ +/** Code and config definitions were copied into the definitions table. */ final readonly class DefinitionsSynced implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/HistoryPruned.php b/src/Events/HistoryPruned.php index 0a152f9..35fc410 100644 --- a/src/Events/HistoryPruned.php +++ b/src/Events/HistoryPruned.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * History entries were deleted by retention: how many, and the policy that removed them - * (`keep_days` and/or `keep_versions`; null where that rule was not applied). - */ +/** History entries were deleted by retention; a null rule was not applied. */ final readonly class HistoryPruned implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/LayerSkipped.php b/src/Events/LayerSkipped.php index 6cb3a35..57f949d 100644 --- a/src/Events/LayerSkipped.php +++ b/src/Events/LayerSkipped.php @@ -4,11 +4,7 @@ namespace Simtabi\Laranail\Settings\Events; -/** - * A store in bootstrap mode skipped its database layer, because the application is being - * installed and the database is not ready yet. Dispatched once per layer per request, so a - * skip is reported rather than hidden. - */ +/** A store in bootstrap mode skipped its database layer. Dispatched once per layer per request. */ final readonly class LayerSkipped { public function __construct( diff --git a/src/Events/OrphansPruned.php b/src/Events/OrphansPruned.php index f56e740..d5f2f63 100644 --- a/src/Events/OrphansPruned.php +++ b/src/Events/OrphansPruned.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * The settings of owners that no longer exist were removed: how many owners, how many rows. - */ +/** The settings of owners that no longer exist were removed. */ final readonly class OrphansPruned implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ScopeFlushed.php b/src/Events/ScopeFlushed.php index 75ccf10..ad6ee60 100644 --- a/src/Events/ScopeFlushed.php +++ b/src/Events/ScopeFlushed.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Every value of one scope in a store was removed. - */ +/** Every value of one scope in a store was removed. */ final readonly class ScopeFlushed implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/ScopeFlushing.php b/src/Events/ScopeFlushing.php index e2f2c46..fcaaccc 100644 --- a/src/Events/ScopeFlushing.php +++ b/src/Events/ScopeFlushing.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Every value of one scope in a store is about to be removed (an owner was deleted). - */ +/** Every value of one scope in a store is about to be removed. */ final readonly class ScopeFlushing implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingForgetting.php b/src/Events/SettingForgetting.php index eba115b..92fa6b3 100644 --- a/src/Events/SettingForgetting.php +++ b/src/Events/SettingForgetting.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Dispatched after the surrounding database transaction commits, if any. Carries identifiers - * only, never the value, so a queued listener cannot leak a secret into the jobs table. - */ +/** A setting is about to be forgotten. */ final readonly class SettingForgetting implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingForgotten.php b/src/Events/SettingForgotten.php index cbf2e46..ab72558 100644 --- a/src/Events/SettingForgotten.php +++ b/src/Events/SettingForgotten.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Dispatched after the surrounding database transaction commits, if any. Carries identifiers - * only, never the value, so a queued listener cannot leak a secret into the jobs table. - */ +/** A setting was forgotten. */ final readonly class SettingForgotten implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingLocked.php b/src/Events/SettingLocked.php index 340f3a9..2a1d040 100644 --- a/src/Events/SettingLocked.php +++ b/src/Events/SettingLocked.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * One scope's row was locked against writes. Dispatched after the surrounding transaction - * commits; identifiers only, never the value. - */ +/** A setting was locked against writes. */ final readonly class SettingLocked implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingRolledBack.php b/src/Events/SettingRolledBack.php index d9cf13e..2d61671 100644 --- a/src/Events/SettingRolledBack.php +++ b/src/Events/SettingRolledBack.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A setting was rolled back to the value it held at `$toVersion`, written as the new version - * `$version` through the normal write pipeline. Dispatched after commit; identifiers only. - */ +/** A setting was rolled back to its value at `$toVersion`, written as `$version`. */ final readonly class SettingRolledBack implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingSaved.php b/src/Events/SettingSaved.php index 232faca..816d375 100644 --- a/src/Events/SettingSaved.php +++ b/src/Events/SettingSaved.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Dispatched after the surrounding database transaction commits, if any. Carries identifiers - * only, never the value, so a queued listener cannot leak a secret into the jobs table. - */ +/** A setting was saved. */ final readonly class SettingSaved implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingSaving.php b/src/Events/SettingSaving.php index 0940829..e6f65b8 100644 --- a/src/Events/SettingSaving.php +++ b/src/Events/SettingSaving.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * Dispatched after the surrounding database transaction commits, if any. Carries identifiers - * only, never the value, so a queued listener cannot leak a secret into the jobs table. - */ +/** A setting is about to be saved. */ final readonly class SettingSaving implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/SettingUnlocked.php b/src/Events/SettingUnlocked.php index b3e002d..e5f3551 100644 --- a/src/Events/SettingUnlocked.php +++ b/src/Events/SettingUnlocked.php @@ -6,10 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * One scope's row was unlocked. Dispatched after the surrounding transaction commits; - * identifiers only, never the value. - */ +/** A setting was unlocked. */ final readonly class SettingUnlocked implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/StorePromoted.php b/src/Events/StorePromoted.php index b9de5a3..c9f8ece 100644 --- a/src/Events/StorePromoted.php +++ b/src/Events/StorePromoted.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A store's runtime file was promoted: counts only, never values. - */ +/** A store's runtime file was promoted into its database layer. */ final readonly class StorePromoted implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/StorePromoting.php b/src/Events/StorePromoting.php index fa6ff28..3eda067 100644 --- a/src/Events/StorePromoting.php +++ b/src/Events/StorePromoting.php @@ -6,9 +6,7 @@ use Illuminate\Contracts\Events\ShouldDispatchAfterCommit; -/** - * A store's runtime file is about to be promoted into its database layer. - */ +/** A store's runtime file is about to be promoted into its database layer. */ final readonly class StorePromoting implements ShouldDispatchAfterCommit { public function __construct( diff --git a/src/Events/VerificationWasRequired.php b/src/Events/VerificationWasRequired.php index b8363eb..0931c52 100644 --- a/src/Events/VerificationWasRequired.php +++ b/src/Events/VerificationWasRequired.php @@ -8,10 +8,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; -/** - * An actor holding an ability was refused because it needs step-up verification and the actor - * has not verified recently. Dispatched at once, like AccessWasDenied. Never carries a value. - */ +/** An actor was refused because the ability needs step-up verification. Dispatched at once. */ final readonly class VerificationWasRequired { public function __construct( diff --git a/src/Exceptions/AccessDenied.php b/src/Exceptions/AccessDenied.php index 8e7809f..aa94f53 100644 --- a/src/Exceptions/AccessDenied.php +++ b/src/Exceptions/AccessDenied.php @@ -7,10 +7,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; -/** - * The actor may not perform this ability on this subject. Carries the ability, store and key so - * a caller can report it, and never a value. - */ +/** The actor may not perform this ability on this subject. */ final class AccessDenied extends SettingsException { public const int STATUS = 403; diff --git a/src/Exceptions/ActorRequired.php b/src/Exceptions/ActorRequired.php index 1098d64..2b48ba2 100644 --- a/src/Exceptions/ActorRequired.php +++ b/src/Exceptions/ActorRequired.php @@ -5,8 +5,8 @@ namespace Simtabi\Laranail\Settings\Exceptions; /** - * 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()`. + * The call has no actor while one is required. Pass one with `as()`, or mark trusted code with + * `asSystem()`. */ final class ActorRequired extends SettingsException { diff --git a/src/Exceptions/ApprovalUnavailable.php b/src/Exceptions/ApprovalUnavailable.php index 8f517e9..b476588 100644 --- a/src/Exceptions/ApprovalUnavailable.php +++ b/src/Exceptions/ApprovalUnavailable.php @@ -5,10 +5,8 @@ namespace Simtabi\Laranail\Settings\Exceptions; /** - * The write needs a second person's approval, and this store cannot hold change requests: it has - * no active database layer (a file-only store, or one skipped during bootstrap), or its schema was - * 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). + * The write needs approval, but the store cannot hold change requests: it has no active database + * layer or no change requests table. */ final class ApprovalUnavailable extends SettingsException { diff --git a/src/Exceptions/CategoryCycle.php b/src/Exceptions/CategoryCycle.php index 74ecdc3..137a3ad 100644 --- a/src/Exceptions/CategoryCycle.php +++ b/src/Exceptions/CategoryCycle.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * Moving a category under itself or one of its descendants would create a cycle. - */ +/** Moving a category under itself or a descendant would create a cycle. */ final class CategoryCycle extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/CategoryStoreMismatch.php b/src/Exceptions/CategoryStoreMismatch.php index 0190a47..ef69ed2 100644 --- a/src/Exceptions/CategoryStoreMismatch.php +++ b/src/Exceptions/CategoryStoreMismatch.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A category belongs to another store than the setting or category referring to it. - */ +/** A category belongs to a different store than the setting or category referring to it. */ final class CategoryStoreMismatch extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/ChangeRequestClosed.php b/src/Exceptions/ChangeRequestClosed.php index f77f698..0b7529a 100644 --- a/src/Exceptions/ChangeRequestClosed.php +++ b/src/Exceptions/ChangeRequestClosed.php @@ -4,10 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * The change request can no longer be decided: it was applied, rejected, cancelled, went stale or - * expired (or another approver decided it first). - */ +/** The change request was already applied, rejected, cancelled, expired or went stale. */ final class ChangeRequestClosed extends SettingsException { public const int STATUS = 409; diff --git a/src/Exceptions/ConcurrentModification.php b/src/Exceptions/ConcurrentModification.php index 2a14a8d..28902a4 100644 --- a/src/Exceptions/ConcurrentModification.php +++ b/src/Exceptions/ConcurrentModification.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * 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. - */ +/** Another writer changed the row first. Re-read and retry. */ final class ConcurrentModification extends SettingsException { public const int STATUS = 412; diff --git a/src/Exceptions/DriverFailure.php b/src/Exceptions/DriverFailure.php index 6f60bd1..b1fb7f4 100644 --- a/src/Exceptions/DriverFailure.php +++ b/src/Exceptions/DriverFailure.php @@ -4,7 +4,5 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A storage layer failed; the underlying exception is attached as the previous one. - */ +/** A storage layer failed; the cause is attached as the previous exception. */ final class DriverFailure extends SettingsException {} diff --git a/src/Exceptions/DriverUnavailable.php b/src/Exceptions/DriverUnavailable.php index 1372e3d..f6729e8 100644 --- a/src/Exceptions/DriverUnavailable.php +++ b/src/Exceptions/DriverUnavailable.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * 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. - */ +/** A required layer is unreachable. Never a fallback to defaults. */ final class DriverUnavailable extends SettingsException { public const int STATUS = 503; diff --git a/src/Exceptions/EncryptionUnavailable.php b/src/Exceptions/EncryptionUnavailable.php index 450ba48..cf3ca57 100644 --- a/src/Exceptions/EncryptionUnavailable.php +++ b/src/Exceptions/EncryptionUnavailable.php @@ -4,7 +4,5 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * An encrypted setting was written or read before an encryption key exists. - */ +/** An encrypted setting was used before an encryption key exists. */ final class EncryptionUnavailable extends SettingsException {} diff --git a/src/Exceptions/HistoryUnavailable.php b/src/Exceptions/HistoryUnavailable.php index 6a72ac2..c59f4d4 100644 --- a/src/Exceptions/HistoryUnavailable.php +++ b/src/Exceptions/HistoryUnavailable.php @@ -4,11 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * The store keeps no history: it has no active database layer, or the recorded schema has no - * history table (`history.enabled` was off when it was migrated), or the version asked for is - * not in it. - */ +/** The store keeps no history, or the requested version is not in it. */ final class HistoryUnavailable extends SettingsException { public const int STATUS = 409; diff --git a/src/Exceptions/InvalidConfiguration.php b/src/Exceptions/InvalidConfiguration.php index 861e05d..ecc7571 100644 --- a/src/Exceptions/InvalidConfiguration.php +++ b/src/Exceptions/InvalidConfiguration.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * The package configuration is invalid; the message names the offending config path. - */ +/** The package configuration is invalid; the message names the config path. */ final class InvalidConfiguration extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/InvalidDefinition.php b/src/Exceptions/InvalidDefinition.php index 349c035..b80ba22 100644 --- a/src/Exceptions/InvalidDefinition.php +++ b/src/Exceptions/InvalidDefinition.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A setting definition is internally inconsistent (for example encrypted and public). - */ +/** A setting definition is inconsistent, for example encrypted and public. */ final class InvalidDefinition extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/InvalidIdentifier.php b/src/Exceptions/InvalidIdentifier.php index db77746..a72d12d 100644 --- a/src/Exceptions/InvalidIdentifier.php +++ b/src/Exceptions/InvalidIdentifier.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A store name, key, locale or owner alias failed its value object's validation. - */ +/** A store name, key, locale or owner alias is invalid. */ class InvalidIdentifier extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/InvalidKey.php b/src/Exceptions/InvalidKey.php index 598233f..e561532 100644 --- a/src/Exceptions/InvalidKey.php +++ b/src/Exceptions/InvalidKey.php @@ -4,7 +4,5 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A setting key is not lower-case dot notation of [a-z0-9_] segments, at most 191 characters. - */ +/** A key is not lower-case dot notation of [a-z0-9_] segments, at most 191 characters. */ final class InvalidKey extends InvalidIdentifier {} diff --git a/src/Exceptions/InvalidSettingValue.php b/src/Exceptions/InvalidSettingValue.php index 7925fd7..19ca655 100644 --- a/src/Exceptions/InvalidSettingValue.php +++ b/src/Exceptions/InvalidSettingValue.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A value failed its definition's rules, cast or locale constraints. - */ +/** A value failed its definition's rules, cast or locale constraints. */ final class InvalidSettingValue extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/LockedSetting.php b/src/Exceptions/LockedSetting.php index 4d6f63b..de7a55a 100644 --- a/src/Exceptions/LockedSetting.php +++ b/src/Exceptions/LockedSetting.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A write was refused because the setting is locked or its precedence forbids store writes. - */ +/** The setting is locked, or its precedence forbids store writes. */ final class LockedSetting extends SettingsException { public const int STATUS = 423; diff --git a/src/Exceptions/OwnerNotAllowed.php b/src/Exceptions/OwnerNotAllowed.php index 5f9254d..4d00940 100644 --- a/src/Exceptions/OwnerNotAllowed.php +++ b/src/Exceptions/OwnerNotAllowed.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * The owner's morph alias is not allowed in the store, or no store accepts it. - */ +/** No store accepts the owner's morph alias. */ final class OwnerNotAllowed extends SettingsException { public const int STATUS = 409; diff --git a/src/Exceptions/PromotionLocked.php b/src/Exceptions/PromotionLocked.php index 6345549..ef0a821 100644 --- a/src/Exceptions/PromotionLocked.php +++ b/src/Exceptions/PromotionLocked.php @@ -4,7 +4,5 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * Another promotion of the same store holds the promotion lock; try again when it finishes. - */ +/** Another promotion of the same store is running. */ final class PromotionLocked extends SettingsException {} diff --git a/src/Exceptions/SettingsException.php b/src/Exceptions/SettingsException.php index fdde405..39f5481 100644 --- a/src/Exceptions/SettingsException.php +++ b/src/Exceptions/SettingsException.php @@ -7,16 +7,14 @@ use RuntimeException; /** - * 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. Each subtype the REST API answers names its HTTP status and problem - * type ({@see STATUS}, {@see TYPE}); the rest are a 500 `settings-error`. + * Base of every exception this package throws. Messages name the store, key and scope, never a + * value. */ abstract class SettingsException extends RuntimeException { - /** The HTTP status the REST API answers this exception with; a subtype names its own. */ + /** The HTTP status the REST API answers with. */ public const int STATUS = 500; - /** The problem type (RFC 9457) the REST API names, under Problems::TYPE_BASE. */ + /** The RFC 9457 problem type, under Problems::TYPE_BASE. */ public const string TYPE = 'settings-error'; } diff --git a/src/Exceptions/StoreNotWritable.php b/src/Exceptions/StoreNotWritable.php index 3372811..e95e34d 100644 --- a/src/Exceptions/StoreNotWritable.php +++ b/src/Exceptions/StoreNotWritable.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * No layer of the store can accept the write. - */ +/** No layer of the store can accept the write. */ final class StoreNotWritable extends SettingsException { public const int STATUS = 409; diff --git a/src/Exceptions/TypeMismatch.php b/src/Exceptions/TypeMismatch.php index 3bda91f..14758b2 100644 --- a/src/Exceptions/TypeMismatch.php +++ b/src/Exceptions/TypeMismatch.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A typed getter found a value of a different type. - */ +/** A typed getter found a value of a different type. */ final class TypeMismatch extends SettingsException { public const int STATUS = 422; diff --git a/src/Exceptions/UndecryptableValue.php b/src/Exceptions/UndecryptableValue.php index 7d5ad0c..acd7901 100644 --- a/src/Exceptions/UndecryptableValue.php +++ b/src/Exceptions/UndecryptableValue.php @@ -4,7 +4,5 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * An encrypted value could not be decrypted with the current or previous keys. - */ +/** An encrypted value could not be decrypted with the current or previous keys. */ final class UndecryptableValue extends SettingsException {} diff --git a/src/Exceptions/UnknownCategory.php b/src/Exceptions/UnknownCategory.php index 370b1f7..a226d0a 100644 --- a/src/Exceptions/UnknownCategory.php +++ b/src/Exceptions/UnknownCategory.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * No category with this slug exists in the store. - */ +/** No category with this slug exists in the store. */ final class UnknownCategory extends SettingsException { public const int STATUS = 404; diff --git a/src/Exceptions/UnknownChangeRequest.php b/src/Exceptions/UnknownChangeRequest.php index b98460c..cfb56d8 100644 --- a/src/Exceptions/UnknownChangeRequest.php +++ b/src/Exceptions/UnknownChangeRequest.php @@ -4,7 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** No change request with this id exists in the store (for the current tenant). */ +/** No change request with this id exists in the store. */ final class UnknownChangeRequest extends SettingsException { public const int STATUS = 404; diff --git a/src/Exceptions/UnknownOwner.php b/src/Exceptions/UnknownOwner.php index 91dae85..715e624 100644 --- a/src/Exceptions/UnknownOwner.php +++ b/src/Exceptions/UnknownOwner.php @@ -4,7 +4,7 @@ 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. */ +/** No owner exists for this alias and id. */ final class UnknownOwner extends SettingsException { public const int STATUS = 404; diff --git a/src/Exceptions/UnknownSetting.php b/src/Exceptions/UnknownSetting.php index cef5773..cf23b59 100644 --- a/src/Exceptions/UnknownSetting.php +++ b/src/Exceptions/UnknownSetting.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A strict store was asked for a key that has no definition. - */ +/** A strict store has no definition for this key. */ final class UnknownSetting extends SettingsException { public const int STATUS = 404; diff --git a/src/Exceptions/UnknownStore.php b/src/Exceptions/UnknownStore.php index b21ee6b..640b287 100644 --- a/src/Exceptions/UnknownStore.php +++ b/src/Exceptions/UnknownStore.php @@ -4,9 +4,7 @@ namespace Simtabi\Laranail\Settings\Exceptions; -/** - * A store was requested that is not configured. - */ +/** The store is not configured. */ final class UnknownStore extends SettingsException { public const int STATUS = 404; diff --git a/src/Exceptions/VerificationRequired.php b/src/Exceptions/VerificationRequired.php index 32cd1b1..632e61c 100644 --- a/src/Exceptions/VerificationRequired.php +++ b/src/Exceptions/VerificationRequired.php @@ -7,10 +7,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; -/** - * The actor is allowed, but must prove their identity again first (step-up verification), for - * example by confirming their password. Retry once verified. - */ +/** The actor must verify their identity again before this ability. */ final class VerificationRequired extends SettingsException { public const int STATUS = 428; diff --git a/src/Facades/Settings.php b/src/Facades/Settings.php index b055f15..beb07dd 100644 --- a/src/Facades/Settings.php +++ b/src/Facades/Settings.php @@ -49,8 +49,7 @@ use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** - * An application convenience over the {@see SettingsContract} binding. The package's own - * classes never use it; they take the contract through their constructors. + * Static access to the {@see SettingsContract} binding. * * @method static SettingsContract store(string $name) * @method static SettingsContract for(Settable|OwnerRef $owner) @@ -105,8 +104,8 @@ final class Settings extends Facade { /** - * Replace the binding with the real engine over in-memory layers, recording writes and audit - * entries. Install it before resolving the code under test. + * Swap the binding for the real engine over in-memory layers, recording writes and audit + * entries. Call it before resolving the code under test. */ public static function fake(): SettingsFake { @@ -122,8 +121,6 @@ public static function fake(): SettingsFake $access = $access->withAuditor($access->auditor()->alsoTo($log->audit)); $guard = new WriteGuard($access, $app->make(SettingWriter::class), $app->make(ProposeChange::class)); - // 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'))), diff --git a/src/History/HistoryQuery.php b/src/History/HistoryQuery.php index 005c7d4..612ad2e 100644 --- a/src/History/HistoryQuery.php +++ b/src/History/HistoryQuery.php @@ -23,13 +23,9 @@ use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** - * `$settings->history()`: an immutable query over the value history (§4.3), newest version first. - * Narrow it with `for()`, `global()`, `store()`, `key()`, `locale()`, `since()`, `until()` and - * `versions()`, then read it with `get()`, `cursor()` or `paginate()`. - * - * Entries carry the payloads as stored: encrypted values stay encrypted. For an actor who may not - * view a sensitive or encrypted setting, the entry's payloads are removed entirely - * ({@see HistoryEntry::redacted()}); `historyDiff()` is the way to read a past value. + * An immutable query over the value history, newest version first, returned by + * `$settings->history()`. Payloads are as stored, so encrypted values stay encrypted, and they + * are removed for an actor who may not view the setting. */ final readonly class HistoryQuery { diff --git a/src/Http/Controllers/AuditController.php b/src/Http/Controllers/AuditController.php index 3d8cc95..8f6b43c 100644 --- a/src/Http/Controllers/AuditController.php +++ b/src/Http/Controllers/AuditController.php @@ -19,7 +19,7 @@ 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`. */ +/** `/audit`: the audit trail, filtered, newest first. */ final readonly class AuditController { public function index(PageRequest $request, QueryAudit $audit, ApiActor $actors): AnonymousResourceCollection diff --git a/src/Http/Controllers/CategoriesController.php b/src/Http/Controllers/CategoriesController.php index 062bae6..a4bf685 100644 --- a/src/Http/Controllers/CategoriesController.php +++ b/src/Http/Controllers/CategoriesController.php @@ -21,7 +21,7 @@ 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. */ +/** `/stores/{store}/categories`: list, create, rename or move, delete. */ final readonly class CategoriesController { public function index(PageRequest $request, ListCategories $list, SettingTargets $targets, ApiActor $actors): AnonymousResourceCollection @@ -54,7 +54,7 @@ public function update(UpdateCategoryRequest $request, RenameCategory $rename, M $found = array_values(array_filter($list->handle($store, $actor), static fn (Category $category): bool => $category->slug->value === $slug)); - // The category is gone from the actor's view (moved out of reach): answered as no data. + // The category moved out of the actor's view, so there is nothing to return. return $found === [] ? new JsonResponse(['data' => null]) : CategoryResource::make($found[0])->response(); } diff --git a/src/Http/Controllers/ChangesController.php b/src/Http/Controllers/ChangesController.php index 762f8fd..5864087 100644 --- a/src/Http/Controllers/ChangesController.php +++ b/src/Http/Controllers/ChangesController.php @@ -27,8 +27,7 @@ use Simtabi\Laranail\Settings\Http\Resources\ChangeRequestResource; /** - * `/stores/{store}/changes` (§16.7): list, read, propose, approve, reject and cancel change - * requests, as the PHP API does. A proposal answers 202. + * `/stores/{store}/changes`: list, read, propose, approve, reject and cancel change requests. */ final readonly class ChangesController { diff --git a/src/Http/Controllers/ConfigurationController.php b/src/Http/Controllers/ConfigurationController.php index 8bb0473..de6f4a8 100644 --- a/src/Http/Controllers/ConfigurationController.php +++ b/src/Http/Controllers/ConfigurationController.php @@ -22,8 +22,8 @@ use Simtabi\Laranail\Settings\Actions\Configuration\ListConfigurationEntries; /** - * `/configuration/{stores|layers}/{name}` and `/stores/{store}/definitions/{key}` (§16.11): - * persisted configuration, edited as the actor, validated like the configuration file. + * `/configuration/{stores|layers}/{name}` and `/stores/{store}/definitions/{key}`: persisted + * configuration, edited as the actor. */ final readonly class ConfigurationController { diff --git a/src/Http/Controllers/HistoryController.php b/src/Http/Controllers/HistoryController.php index faad4e1..08f8da9 100644 --- a/src/Http/Controllers/HistoryController.php +++ b/src/Http/Controllers/HistoryController.php @@ -17,7 +17,7 @@ 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. */ +/** `…/settings/{key}/history` and `…/rollback`. */ final readonly class HistoryController { public function index(PageRequest $request, ReadHistory $history, Addresses $addresses, ApiActor $actors): AnonymousResourceCollection diff --git a/src/Http/Controllers/SettingsController.php b/src/Http/Controllers/SettingsController.php index 1a29384..4b651b2 100644 --- a/src/Http/Controllers/SettingsController.php +++ b/src/Http/Controllers/SettingsController.php @@ -30,9 +30,8 @@ use Simtabi\Laranail\Settings\Http\Resources\ChangeRequestResource; /** - * `/stores/{store}/settings` and `/stores/{store}/owners/{alias}/{id}/settings` (§16.10): resolve - * the actor and the address, delegate to the action the PHP API uses, render. A write needing - * approval answers 202 with the change request; `If-Match` makes a write conditional on the ETag. + * `/stores/{store}/settings` and `/stores/{store}/owners/{alias}/{id}/settings`. A write that + * needs approval answers 202 with the change request. */ final readonly class SettingsController { @@ -99,8 +98,8 @@ public function unlock(WriteSettingRequest $request, UnlockSetting $unlock, Read } /** - * `If-Match` against the address's current ETag: a mismatch is 412, a match makes the write - * conditional on that version (the version-checked update, §6). `*` matches any version. + * Check `If-Match` against the current ETag: a mismatch is 412, a match makes the write + * conditional on that version. `*` matches any version. * * @throws ConcurrentModification */ diff --git a/src/Http/Controllers/StoresController.php b/src/Http/Controllers/StoresController.php index ec6c384..0872cee 100644 --- a/src/Http/Controllers/StoresController.php +++ b/src/Http/Controllers/StoresController.php @@ -13,7 +13,7 @@ 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. */ +/** `/stores` and `/stores/{store}/definitions`. */ final readonly class StoresController { public function index(PageRequest $request, ListStores $stores, ApiActor $actors): AnonymousResourceCollection diff --git a/src/Http/Controllers/TransferController.php b/src/Http/Controllers/TransferController.php index 173aa68..60cd143 100644 --- a/src/Http/Controllers/TransferController.php +++ b/src/Http/Controllers/TransferController.php @@ -19,9 +19,8 @@ use Simtabi\Laranail\Settings\Http\Resources\ExportDocumentResource; /** - * `/stores/{store}/export`, `/import` and `/diff` (G-42): the same document the console writes. - * An import is a dry run unless `apply` is true, and is never trusted over HTTP (locks and system - * categories in the document are ignored; that is the console's `--trusted`). + * `/stores/{store}/export`, `/import` and `/diff`. An import is a dry run unless `apply` is true, + * and is never trusted over HTTP. */ final readonly class TransferController { diff --git a/src/Http/Middleware/IdempotentWrites.php b/src/Http/Middleware/IdempotentWrites.php index 6a414f3..ade42f3 100644 --- a/src/Http/Middleware/IdempotentWrites.php +++ b/src/Http/Middleware/IdempotentWrites.php @@ -11,10 +11,8 @@ use Illuminate\Http\Response as IlluminateResponse; /** - * `Idempotency-Key` on REST writes (§16.12): the first response to a key is kept for - * `http.idempotency.ttl` seconds (24 hours by default), and a retry with the same key, from the - * same user, to the same method and path, gets that response again (`Idempotent-Replayed: true`) - * instead of applying twice. Server errors are not kept, so they can be retried. + * Replays the stored response to a REST write retried with the same `Idempotency-Key`, user, + * method and path. Server errors are not stored, so they can be retried. */ final readonly class IdempotentWrites { diff --git a/src/Http/Requests/Concerns/ReadsAddress.php b/src/Http/Requests/Concerns/ReadsAddress.php index 619319a..7b40ae6 100644 --- a/src/Http/Requests/Concerns/ReadsAddress.php +++ b/src/Http/Requests/Concerns/ReadsAddress.php @@ -6,7 +6,7 @@ use Simtabi\Laranail\Settings\Data\Http\AddressInput; -/** What every setting request reads from its URL: store, key, owner alias and id, `?locale=`. */ +/** Reads the store, key, owner and `?locale=` a setting request addresses. */ trait ReadsAddress { /** @return array> */ diff --git a/src/Http/Requests/DiffStoreRequest.php b/src/Http/Requests/DiffStoreRequest.php index ef883d6..3312cce 100644 --- a/src/Http/Requests/DiffStoreRequest.php +++ b/src/Http/Requests/DiffStoreRequest.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidImport; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; -/** - * `POST /stores/{store}/diff`: an export document to compare the store with. - */ +/** `POST /stores/{store}/diff`. */ final class DiffStoreRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/ExportStoreRequest.php b/src/Http/Requests/ExportStoreRequest.php index a73edc5..40d66d3 100644 --- a/src/Http/Requests/ExportStoreRequest.php +++ b/src/Http/Requests/ExportStoreRequest.php @@ -7,9 +7,7 @@ use Illuminate\Foundation\Http\FormRequest; use Simtabi\Laranail\Settings\Enums\ExportMode; -/** - * `POST /stores/{store}/export`: how secrets are written (`mode`), redacted by default. - */ +/** `POST /stores/{store}/export`. */ final class ExportStoreRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/ImportStoreRequest.php b/src/Http/Requests/ImportStoreRequest.php index 3f432a8..479064a 100644 --- a/src/Http/Requests/ImportStoreRequest.php +++ b/src/Http/Requests/ImportStoreRequest.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidImport; use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; -/** - * `POST /stores/{store}/import`: an export document, applied only when `apply` is true. - */ +/** `POST /stores/{store}/import`: applied only when `apply` is true. */ final class ImportStoreRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/PageRequest.php b/src/Http/Requests/PageRequest.php index 6fcec2e..5320019 100644 --- a/src/Http/Requests/PageRequest.php +++ b/src/Http/Requests/PageRequest.php @@ -9,11 +9,7 @@ use Simtabi\Laranail\Settings\Data\Http\AddressInput; use Simtabi\Laranail\Settings\Http\Requests\Concerns\ReadsAddress; -/** - * A list request: `?limit=` (1-200), `?cursor=` (from the previous page's `meta.next_cursor`) and - * the list's filters (`store`, `key`, `scope`, `status`, `action`, `outcome`, `locale`, `since`, - * `until`). Route parameters (store, key, owner) come through `address()`. - */ +/** A list request: `?limit=`, `?cursor=` and the list's filters. */ final class PageRequest extends FormRequest { use ReadsAddress; diff --git a/src/Http/Requests/ProposeChangeRequest.php b/src/Http/Requests/ProposeChangeRequest.php index 63c5901..ee93488 100644 --- a/src/Http/Requests/ProposeChangeRequest.php +++ b/src/Http/Requests/ProposeChangeRequest.php @@ -9,8 +9,7 @@ use Simtabi\Laranail\Settings\Data\Http\AddressInput; /** - * `POST /stores/{store}/changes`: propose a change to one setting, for the global value or an - * owner (`owner.alias`, `owner.id`), as a `set` (the default), `forget`, `lock` or `unlock`. + * `POST /stores/{store}/changes`: propose a `set`, `forget`, `lock` or `unlock` of one setting. */ final class ProposeChangeRequest extends FormRequest { @@ -35,7 +34,7 @@ public function rules(): array ]; } - /** The setting the change is for, as the URL and the body name it. */ + /** The setting the change is for. */ public function toData(): AddressInput { $alias = $this->input('owner.alias'); diff --git a/src/Http/Requests/ReasonRequest.php b/src/Http/Requests/ReasonRequest.php index ae05087..ab5a0ec 100644 --- a/src/Http/Requests/ReasonRequest.php +++ b/src/Http/Requests/ReasonRequest.php @@ -6,10 +6,7 @@ use Illuminate\Foundation\Http\FormRequest; -/** - * A request whose body carries at most a `reason`: reading a change request, deciding one - * (approve, reject, cancel), and deleting a category, a persisted entry or a definition. - */ +/** A request whose body carries at most a `reason`. */ final class ReasonRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/RollbackSettingRequest.php b/src/Http/Requests/RollbackSettingRequest.php index c84b9cd..06d5e72 100644 --- a/src/Http/Requests/RollbackSettingRequest.php +++ b/src/Http/Requests/RollbackSettingRequest.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Settings\Data\Http\WriteInput; use Simtabi\Laranail\Settings\Http\Requests\Concerns\ReadsAddress; -/** - * `POST …/settings/{key}/rollback`: the version to return to, and an optional `reason`. - */ +/** `POST …/settings/{key}/rollback`. */ final class RollbackSettingRequest extends FormRequest { use ReadsAddress; diff --git a/src/Http/Requests/SaveConfigurationRequest.php b/src/Http/Requests/SaveConfigurationRequest.php index 95c5f44..29397e3 100644 --- a/src/Http/Requests/SaveConfigurationRequest.php +++ b/src/Http/Requests/SaveConfigurationRequest.php @@ -7,10 +7,7 @@ use Illuminate\Foundation\Http\FormRequest; use Simtabi\Laranail\Settings\Data\ConfigurationEntry; -/** - * `PUT /configuration/{stores|layers}/{name}`: a persisted store or layer entry, as the - * configuration file would hold it. - */ +/** `PUT /configuration/{stores|layers}/{name}`. */ final class SaveConfigurationRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/SaveDefinitionRequest.php b/src/Http/Requests/SaveDefinitionRequest.php index d4884e1..cc48026 100644 --- a/src/Http/Requests/SaveDefinitionRequest.php +++ b/src/Http/Requests/SaveDefinitionRequest.php @@ -6,10 +6,7 @@ use Illuminate\Foundation\Http\FormRequest; -/** - * `PUT /stores/{store}/definitions/{key}`: a definition's attributes, as `definitions.` - * would hold them. - */ +/** `PUT /stores/{store}/definitions/{key}`. */ final class SaveDefinitionRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/SettingRequest.php b/src/Http/Requests/SettingRequest.php index 8a79317..c7df1ac 100644 --- a/src/Http/Requests/SettingRequest.php +++ b/src/Http/Requests/SettingRequest.php @@ -8,7 +8,7 @@ use Simtabi\Laranail\Settings\Data\Http\AddressInput; use Simtabi\Laranail\Settings\Http\Requests\Concerns\ReadsAddress; -/** A read of one setting (show, explain). Authorization happens in the action, not here. */ +/** A read of one setting. Authorization happens in the action. */ final class SettingRequest extends FormRequest { use ReadsAddress; diff --git a/src/Http/Requests/StoreCategoryRequest.php b/src/Http/Requests/StoreCategoryRequest.php index 04d1905..8b81e79 100644 --- a/src/Http/Requests/StoreCategoryRequest.php +++ b/src/Http/Requests/StoreCategoryRequest.php @@ -7,9 +7,7 @@ use Illuminate\Foundation\Http\FormRequest; use Simtabi\Laranail\Settings\Data\NewCategory; -/** - * `POST /stores/{store}/categories`: a new category, optionally under a parent. - */ +/** `POST /stores/{store}/categories`. */ final class StoreCategoryRequest extends FormRequest { public function authorize(): bool diff --git a/src/Http/Requests/UpdateCategoryRequest.php b/src/Http/Requests/UpdateCategoryRequest.php index cad8acb..a29ba9a 100644 --- a/src/Http/Requests/UpdateCategoryRequest.php +++ b/src/Http/Requests/UpdateCategoryRequest.php @@ -7,8 +7,8 @@ use Illuminate\Foundation\Http\FormRequest; /** - * `PATCH /stores/{store}/categories/{slug}`: a new title, a new parent, or both. Naming - * `parent` as null moves the category to the top level; leaving it out leaves it where it is. + * `PATCH /stores/{store}/categories/{slug}`. A null `parent` moves the category to the top level; + * omitting it leaves the parent unchanged. */ final class UpdateCategoryRequest extends FormRequest { diff --git a/src/Http/Requests/WriteSettingRequest.php b/src/Http/Requests/WriteSettingRequest.php index c7cfd7d..744a24d 100644 --- a/src/Http/Requests/WriteSettingRequest.php +++ b/src/Http/Requests/WriteSettingRequest.php @@ -8,10 +8,7 @@ use Simtabi\Laranail\Settings\Data\Http\WriteInput; use Simtabi\Laranail\Settings\Http\Requests\Concerns\ReadsAddress; -/** - * 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. - */ +/** A write of one setting: update, forget, lock or unlock. */ final class WriteSettingRequest extends FormRequest { use ReadsAddress; diff --git a/src/Http/Resources/AuditEntryResource.php b/src/Http/Resources/AuditEntryResource.php index 037cdf2..95fa155 100644 --- a/src/Http/Resources/AuditEntryResource.php +++ b/src/Http/Resources/AuditEntryResource.php @@ -11,14 +11,14 @@ use Illuminate\Http\Resources\Attributes\PreserveKeys; /** - * An audit entry (§16.8): identifiers, the outcome and the channel, never a value. + * An audit entry: identifiers, the outcome and the channel, never a value. * * @property AuditEntry $resource */ #[PreserveKeys] final class AuditEntryResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/CategoryResource.php b/src/Http/Resources/CategoryResource.php index d678118..959e8c7 100644 --- a/src/Http/Resources/CategoryResource.php +++ b/src/Http/Resources/CategoryResource.php @@ -11,14 +11,14 @@ use Illuminate\Http\Resources\Attributes\PreserveKeys; /** - * A category as the API returns it, by slug (its numeric id is internal, G-42). + * A category as the API returns it, identified by slug. * * @property Category $resource */ #[PreserveKeys] final class CategoryResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/ChangeRequestResource.php b/src/Http/Resources/ChangeRequestResource.php index 26ebcc3..c71aef9 100644 --- a/src/Http/Resources/ChangeRequestResource.php +++ b/src/Http/Resources/ChangeRequestResource.php @@ -11,14 +11,14 @@ use Illuminate\Http\Resources\Attributes\PreserveKeys; /** - * A change request (§16.7) without its proposed payload, which may be a secret. + * A change request without its proposed payload, which may be a secret. * * @property ChangeRequest $resource */ #[PreserveKeys] final class ChangeRequestResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/ConfigurationEntryResource.php b/src/Http/Resources/ConfigurationEntryResource.php index 4956bc1..1517c76 100644 --- a/src/Http/Resources/ConfigurationEntryResource.php +++ b/src/Http/Resources/ConfigurationEntryResource.php @@ -11,14 +11,14 @@ use Simtabi\Laranail\Settings\Data\ConfigurationEntry; /** - * A persisted store or layer entry (§16.11), as the configuration file would hold it. + * A persisted store or layer entry, as the configuration file would hold it. * * @property ConfigurationEntry $resource */ #[PreserveKeys] final class ConfigurationEntryResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/DefinitionResource.php b/src/Http/Resources/DefinitionResource.php index b2504e5..71e4d73 100644 --- a/src/Http/Resources/DefinitionResource.php +++ b/src/Http/Resources/DefinitionResource.php @@ -18,7 +18,7 @@ #[PreserveKeys] final class DefinitionResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/ExplanationResource.php b/src/Http/Resources/ExplanationResource.php index 7809572..45b701e 100644 --- a/src/Http/Resources/ExplanationResource.php +++ b/src/Http/Resources/ExplanationResource.php @@ -18,7 +18,7 @@ #[PreserveKeys] final class ExplanationResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/ExportDocumentResource.php b/src/Http/Resources/ExportDocumentResource.php index 364771b..b90c14d 100644 --- a/src/Http/Resources/ExportDocumentResource.php +++ b/src/Http/Resources/ExportDocumentResource.php @@ -11,14 +11,14 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; /** - * A store export (G-42), the same document the console writes. + * A store export, the same document the console writes. * * @property ExportDocument $resource */ #[PreserveKeys] final class ExportDocumentResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/HistoryEntryResource.php b/src/Http/Resources/HistoryEntryResource.php index 0a6fca5..3d9e8ab 100644 --- a/src/Http/Resources/HistoryEntryResource.php +++ b/src/Http/Resources/HistoryEntryResource.php @@ -11,14 +11,14 @@ use Illuminate\Http\Resources\Attributes\PreserveKeys; /** - * A history entry (§4.3), its payloads as stored (encrypted values stay encrypted). + * A history entry, its payloads as stored (encrypted values stay encrypted). * * @property HistoryEntry $resource */ #[PreserveKeys] final class HistoryEntryResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/ImportReportResource.php b/src/Http/Resources/ImportReportResource.php index a81f2db..6be13b4 100644 --- a/src/Http/Resources/ImportReportResource.php +++ b/src/Http/Resources/ImportReportResource.php @@ -11,14 +11,14 @@ use Simtabi\Laranail\Settings\Data\Transfer\ImportReport; /** - * What an import created, updated, left alone and skipped (G-42). + * What an import created, updated, left alone and skipped. * * @property ImportReport $resource */ #[PreserveKeys] final class ImportReportResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/SettingResource.php b/src/Http/Resources/SettingResource.php index b254835..7ae0378 100644 --- a/src/Http/Resources/SettingResource.php +++ b/src/Http/Resources/SettingResource.php @@ -13,15 +13,15 @@ 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), - * never masked; `version` is the version of the addressed row (0: it has none) and backs the ETag. + * A setting as the API returns it. A value the actor may not see is left out and `redacted` set; + * `version` (0 when no row exists) backs the ETag. * * @property SettingView $resource */ #[PreserveKeys] final class SettingResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/StoreDiffResource.php b/src/Http/Resources/StoreDiffResource.php index 097e4a5..d322b8c 100644 --- a/src/Http/Resources/StoreDiffResource.php +++ b/src/Http/Resources/StoreDiffResource.php @@ -11,14 +11,14 @@ use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff; /** - * How a store differs from an export (G-42), by setting identity. + * How a store differs from an export, by setting identity. * * @property StoreDiff $resource */ #[PreserveKeys] final class StoreDiffResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Resources/StoreResource.php b/src/Http/Resources/StoreResource.php index 2976693..780c58a 100644 --- a/src/Http/Resources/StoreResource.php +++ b/src/Http/Resources/StoreResource.php @@ -19,7 +19,7 @@ #[PreserveKeys] final class StoreResource extends JsonResource { - /** Always wrapped in `data`, whatever the application sets for its own resources. */ + /** Always wrapped in `data`, whatever the application sets. */ public static $wrap = 'data'; /** @return array */ diff --git a/src/Http/Support/ApiActor.php b/src/Http/Support/ApiActor.php index 1e7bf28..982477e 100644 --- a/src/Http/Support/ApiActor.php +++ b/src/Http/Support/ApiActor.php @@ -11,9 +11,7 @@ use Simtabi\Laranail\Settings\Services\Access\AccessGuard; /** - * Who a REST request acts as: the configured actor resolver (the guard, or Sanctum with its - * token abilities as a ceiling), on the `rest` channel. A request nobody is authenticated for is - * refused; the API never runs as trusted code. + * Resolves the actor of a REST request on the `rest` channel. The API never runs as trusted code. */ final readonly class ApiActor { diff --git a/src/Http/Support/Problems.php b/src/Http/Support/Problems.php index 097b747..5f228d0 100644 --- a/src/Http/Support/Problems.php +++ b/src/Http/Support/Problems.php @@ -15,15 +15,8 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; /** - * 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. + * Renders package exceptions as RFC 9457 problem details. Other exceptions are left to the + * application's handler. */ final readonly class Problems { diff --git a/src/Importers/AkauntingSettingsImporter.php b/src/Importers/AkauntingSettingsImporter.php index 835630b..f1e16a1 100644 --- a/src/Importers/AkauntingSettingsImporter.php +++ b/src/Importers/AkauntingSettingsImporter.php @@ -12,12 +12,9 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; /** - * akaunting/laravel-setting's database driver (G-43; the key-value packages of research.md §2): - * reads its table of `key` / `value` rows, where nested values are already flattened to dot - * keys and every value is a string. Each row becomes a global key with that string value; define - * a typed definition here before importing to have it cast. `$source` is `` or - * `:` (default table `settings`). Rows its extra columns scope to a model or - * team are skipped, because that scoping is the application's own. + * Imports akaunting/laravel-setting's database table. Every value arrives as a string, so define + * typed keys before importing. Rows scoped by extra columns are skipped. `$source` is + * `` or `:
` (default table `settings`). */ final readonly class AkauntingSettingsImporter implements Importer { @@ -45,7 +42,7 @@ public function read(string $source, StoreName $store): ExportDocument throw new InvalidImport(sprintf('akaunting: table [%s] has no key and value columns.', $table)); } - // Extra columns (user_id, company_id, …) scope a row to something of the host's own. + // Extra columns (user_id, company_id, ...) scope a row to the host's own models. if (array_filter(array_diff_key($row, array_flip(['id', 'key', 'value', 'created_at', 'updated_at'])), static fn (mixed $value): bool => $value !== null) !== []) { continue; } diff --git a/src/Importers/ImportedKeys.php b/src/Importers/ImportedKeys.php index ab39260..8d96435 100644 --- a/src/Importers/ImportedKeys.php +++ b/src/Importers/ImportedKeys.php @@ -15,8 +15,7 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportedSetting; /** - * What the importers share: another package's key made into a valid key (lower case, `-` and - * spaces to `_`), and global values gathered into a document. + * Normalises another package's keys and gathers global values into an export document. */ final readonly class ImportedKeys { @@ -31,7 +30,7 @@ public static function key(string $key, string $source): Key } /** - * Global values as a document of the store. + * Global values as an export document. * * @param array $values key => [value, locked] */ diff --git a/src/Importers/SpatieSettingsImporter.php b/src/Importers/SpatieSettingsImporter.php index 131c229..5c684ba 100644 --- a/src/Importers/SpatieSettingsImporter.php +++ b/src/Importers/SpatieSettingsImporter.php @@ -12,12 +12,9 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; /** - * spatie/laravel-settings (G-43): reads its `settings` table (`group`, `name`, `payload`, - * `locked`) on a connection; each row becomes the global key `.` with its JSON - * payload decoded, and `locked` kept (applied only by a trusted import). `$source` is - * `` or `:
` (default table `settings`; an empty connection is the - * default one). Values spatie stored encrypted arrive as the ciphertext spatie wrote: define those - * keys encrypted here and set them again. + * Imports spatie/laravel-settings' table: each row becomes the global key `.`. + * Encrypted values arrive as spatie's ciphertext and must be set again. `$source` is + * `` or `:
` (default table `settings`). */ final readonly class SpatieSettingsImporter implements Importer { diff --git a/src/Importers/ToolkitJsonImporter.php b/src/Importers/ToolkitJsonImporter.php index 6f0cbe6..49eaae8 100644 --- a/src/Importers/ToolkitJsonImporter.php +++ b/src/Importers/ToolkitJsonImporter.php @@ -11,10 +11,8 @@ use Simtabi\Laranail\Settings\Data\Transfer\ExportDocument; /** - * laranail/toolkit's JSON `SettingsStore` (G-43, D-13): reads its file (nested by dot-notation - * keys) and flattens it, so `{"mail": {"host": "x"}}` becomes the global key `mail.host`. A list - * (an array with keys 0, 1, …) is one value, not more keys. `$source` is the file's absolute path - * (on the default `local` disk that is `storage/app/laranail/settings.json`). + * Imports laranail/toolkit's JSON settings file, flattening nested objects to dot keys. A list is + * one value. `$source` is the file's absolute path. */ final readonly class ToolkitJsonImporter implements Importer { diff --git a/src/Listeners/LogSettingsEvent.php b/src/Listeners/LogSettingsEvent.php index 6f851fe..e9443b8 100644 --- a/src/Listeners/LogSettingsEvent.php +++ b/src/Listeners/LogSettingsEvent.php @@ -12,13 +12,11 @@ use Simtabi\Laranail\Settings\Events\VerificationWasRequired; /** - * Writes every package event to the operational log (`logging.channel`), identifiers only: - * refusals at `warning`, everything else at `info`. Off by default - * (`listeners.log`), because the audit trail already records the actions these events announce. + * Writes every package event to the operational log: refusals at `warning`, the rest at `info`. */ final readonly class LogSettingsEvent { - /** What is logged: every event an alert can name, plus a skipped bootstrap layer. */ + /** Every event an alert can name, plus a skipped bootstrap layer. */ public const array EVENTS = [...SendSettingsAlert::EVENTS, LayerSkipped::class]; public function __construct( diff --git a/src/Listeners/SendSettingsAlert.php b/src/Listeners/SendSettingsAlert.php index 0c5431b..d0e404a 100644 --- a/src/Listeners/SendSettingsAlert.php +++ b/src/Listeners/SendSettingsAlert.php @@ -16,6 +16,7 @@ use Illuminate\Notifications\AnonymousNotifiable; use Simtabi\Laranail\Settings\Events\AuditPruned; use Simtabi\Laranail\Settings\Events\ChangeStale; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Events\ScopeFlushed; use Simtabi\Laranail\Settings\Events\SettingSaved; use Illuminate\Contracts\Cache\Repository as Cache; @@ -42,20 +43,13 @@ use Illuminate\Contracts\Notifications\Dispatcher as Notifications; /** - * Sends `laranail.settings.alerts`: for each rule an event matches, one {@see SettingsAlert} to - * the rule's mail addresses and Slack webhook, and one to its database notifiable. Alerts carry - * identifiers only, never a value. - * - * Throttled per rule and per setting: after a rule alerts about one key (or one store, for - * events without a key) it stays quiet about it for `alerts.throttle` seconds, so a storm of - * writes produces one alert. The throttle is an atomic cache `add()`; when the cache fails the - * alert is sent anyway (a missed alert is worse than a repeated one) and the failure is logged. - * An alert that cannot be sent (a mail transport down, a notifiable's table missing) is logged, - * never thrown: the change it reports has already committed. + * Sends a {@see SettingsAlert} for each configured rule an event matches, throttled per rule and + * key. Send failures are logged, never thrown, because the change has already committed; a cache + * failure sends the alert anyway, since a missed alert is worse than a repeated one. */ final readonly class SendSettingsAlert { - /** The events an alert rule can name: everything that happened, none of the `-ing` events. */ + /** The events an alert rule can name: the past-tense events only. */ public const array EVENTS = [ SettingSaved::class, SettingForgotten::class, @@ -82,7 +76,7 @@ /** * @param list $rules - * @param Definitions $definitions whether a store's key is sensitive or encrypted (code and runtime definitions only) + * @param Definitions $definitions used to tell whether a key is sensitive */ public function __construct( private Notifications $notifications, @@ -114,7 +108,7 @@ public function handle(object $event): void $this->send($rule, $context); } catch (Throwable $exception) { // The change has committed; a failing alert must not turn it into an error. - $this->logger->error(sprintf('laranail/settings: alert rule %d could not be sent: %s', $index, $exception->getMessage()), ['event' => $context->event, 'store' => $context->store, 'key' => $context->key]); + $this->logger->error(sprintf('laranail/settings: alert rule %d could not be sent: %s', $index, $exception->getMessage()), LogContext::of($context->store, $context->key, $context->scope, extra: ['event' => $context->event])); } } } @@ -147,17 +141,13 @@ private function send(AlertRule $rule, AlertContext $context): void } } - /** - * The alert's labels and footer in the current locale. - * - * @return array - */ + /** @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. */ + /** Whether the event's key is sensitive or encrypted. */ private function sensitive(?string $store, ?string $key): bool { if ($store === null || $key === null) { @@ -188,7 +178,7 @@ private function notifiable(array $target): ?Model $model = $target['type']::query()->find($target['id']); if (! $model instanceof Model) { - $this->logger->warning(sprintf('laranail/settings: the alert notifiable [%s:%s] does not exist; the database alert was not sent.', $target['type'], $target['id'])); + $this->logger->warning(sprintf('laranail/settings: the alert notifiable [%s:%s] does not exist; the database alert was not sent.', $target['type'], $target['id']), LogContext::of()); return null; } @@ -207,7 +197,7 @@ private function throttled(int $index, AlertContext $context): bool try { return ! $this->cache->add($key, true, $this->throttle); } catch (Throwable $exception) { - $this->logger->warning(sprintf('laranail/settings: the alert throttle could not reach the cache (%s); sending the alert anyway.', $exception->getMessage())); + $this->logger->warning(sprintf('laranail/settings: the alert throttle could not reach the cache (%s); sending the alert anyway.', $exception->getMessage()), LogContext::of($context->store, $context->key, $context->scope, extra: ['event' => $context->event])); return false; } diff --git a/src/Logging/LogContext.php b/src/Logging/LogContext.php new file mode 100644 index 0000000..74248d8 --- /dev/null +++ b/src/Logging/LogContext.php @@ -0,0 +1,52 @@ + */ + public const array KEYS = ['store', 'key', 'scope', 'actor', 'channel']; + + /** + * @param array $extra + * + * @return array + */ + public static function of( + ?string $store = null, + ?string $key = null, + ?string $scope = null, + ?Actor $actor = null, + ?string $channel = null, + array $extra = [], + ): array { + return [ + 'store' => $store, + 'key' => $key, + 'scope' => $scope, + 'actor' => $actor?->toArray(), + 'channel' => $channel ?? $actor?->channel->value, + ...$extra, + ]; + } + + /** + * The given context with the five standard keys first, null where the entry has none. + * + * @param array $context + * + * @return array + */ + public static function normalise(array $context): array + { + return [...array_fill_keys(self::KEYS, null), ...$context]; + } +} diff --git a/src/Logging/OperationalLogger.php b/src/Logging/OperationalLogger.php index a66e658..58b29d4 100644 --- a/src/Logging/OperationalLogger.php +++ b/src/Logging/OperationalLogger.php @@ -14,7 +14,8 @@ /** * The package's operational log: denials, verification failures and configuration changes, * written to `logging.channel` (or a logger set at runtime with `logTo()`) at or above - * `logging.level`. Messages carry store, key, scope and actor identifiers, never a value. + * `logging.level`. Every entry's context starts with store, key, scope, actor and channel + * ({@see LogContext}), and never holds a value. */ final readonly class OperationalLogger implements LoggerInterface { @@ -54,6 +55,6 @@ public function log($level, string|Stringable $message, array $context = []): vo return; } - ($this->runtime?->logger() ?? $this->logger)->log($level, $message, $context); + ($this->runtime?->logger() ?? $this->logger)->log($level, $message, LogContext::normalise($context)); } } diff --git a/src/Models/Concerns/UsesSettingsSchema.php b/src/Models/Concerns/UsesSettingsSchema.php index dcbc735..dbfa3bf 100644 --- a/src/Models/Concerns/UsesSettingsSchema.php +++ b/src/Models/Concerns/UsesSettingsSchema.php @@ -11,9 +11,8 @@ use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; /** - * The shared shape of the settings models: the primary key follows `ids.type` (bigint keys are - * assigned by the database, uuid and ulid keys are generated on create), and in column-mode - * tenancy every query is limited to the current tenant and every new row is stamped with it. + * Keys the model per `ids.type` and, in column-mode tenancy, scopes queries and new rows to the + * current tenant. * * @phpstan-require-extends Model */ diff --git a/src/Models/ModelContext.php b/src/Models/ModelContext.php index a94eb2a..09d9080 100644 --- a/src/Models/ModelContext.php +++ b/src/Models/ModelContext.php @@ -10,14 +10,10 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * What the Eloquent models need to know and cannot ask for themselves (Eloquent builds models - * with `new static`, so nothing is injected): the recorded schema shape (table names, key type, - * soft deletes, tenancy mode), the current tenant and the default store. The service provider - * sets it once with closures that resolve the scoped services on every call, so nothing derived - * from one request or tenant is held here. + * The schema shape, current tenant and default store the Eloquent models read. * - * The models are for factories, seeders, admin screens and tests. The settings engine never uses - * them: reads and writes go through the drivers on the query builder. + * Eloquent builds models with `new static`, so nothing can be injected. The provider sets closures + * here that resolve the scoped services on each call, so no request or tenant state is held. */ final class ModelContext { @@ -31,9 +27,9 @@ final class ModelContext private static ?Closure $defaultStore = null; /** - * @param Closure(): SchemaShape $shape the recorded shape (tables, keys, tenancy mode) - * @param Closure(): ?string $tenant the current tenant - * @param Closure(): string $defaultStore `laranail.settings.default` + * @param Closure(): SchemaShape $shape + * @param Closure(): ?string $tenant + * @param Closure(): string $defaultStore */ public static function use(Closure $shape, Closure $tenant, Closure $defaultStore): void { @@ -49,7 +45,7 @@ public static function shape(): SchemaShape : throw new InvalidConfiguration('The settings models are used before SettingsServiceProvider registered them.'); } - /** The tenant column value: '' outside any tenant, or when tenancy is not column mode. */ + /** The tenant column value; '' outside a tenant or when tenancy is not column mode. */ public static function tenant(): string { return self::hasTenantColumn() && self::$tenant instanceof Closure ? ((self::$tenant)() ?? '') : ''; diff --git a/src/Models/Setting.php b/src/Models/Setting.php index 921d5f8..77d57e0 100644 --- a/src/Models/Setting.php +++ b/src/Models/Setting.php @@ -14,13 +14,11 @@ use Simtabi\Laranail\Settings\Models\Concerns\UsesSettingsSchema; /** - * A row of one store's values table (§4.2), for factories, admin screens and tests. Each store - * has its own table, so a model instance belongs to one store: the default store unless - * {@see inStore()} or {@see forStore()} names another. + * A row of a store's values table, for factories, admin screens and tests. Belongs to the default + * store unless {@see inStore()} or {@see forStore()} names another. * - * `value` is the **encoded payload** (the value pipeline's JSON, encrypted when `is_encrypted`). - * Writing it here bypasses validation, casting, encryption, locks, authorization and audit, so - * application code sets values with `Settings::set()`; the engine never reads through this model. + * `value` is the encoded payload. Writing it here bypasses validation, encryption, locks, + * authorization and audit; application code uses `Settings::set()`. * * @property int|string $id * @property string $scope @@ -40,7 +38,7 @@ final class Setting extends Model private ?string $store = null; - /** @return Builder a query on a store's values table */ + /** @return Builder */ public static function forStore(string $store): Builder { return new self()->inStore($store)->newQuery(); @@ -74,7 +72,7 @@ public function getConnectionName(): ?string } /** - * Copies keep the store, so rows read from a store's table stay in that store. + * Copies keep the store. * * @param array $attributes */ diff --git a/src/Models/SettingAuditEntry.php b/src/Models/SettingAuditEntry.php index 0d2a0d3..a81a6ab 100644 --- a/src/Models/SettingAuditEntry.php +++ b/src/Models/SettingAuditEntry.php @@ -12,10 +12,7 @@ use Simtabi\Laranail\Settings\Database\Factories\SettingAuditEntryFactory; /** - * A row of the audit table (§16.8): an action or a denial, who, when and through which channel, - * never a value. Its key is always a ULID, whatever `ids.type` says. The trail is append-only: - * the engine writes it through its audit sinks and reads it with `Settings::audit()`; this model - * exists for factories and tests. + * A row of the append-only audit table, for factories and tests. Never holds a value. * * @property string $id * @property string $action diff --git a/src/Models/SettingCategory.php b/src/Models/SettingCategory.php index b7b7002..b2457fb 100644 --- a/src/Models/SettingCategory.php +++ b/src/Models/SettingCategory.php @@ -14,12 +14,8 @@ use Simtabi\Laranail\Settings\Database\Factories\SettingCategoryFactory; /** - * A row of the categories table (§4.1), for factories, seeders and admin screens. Category - * changes made through the settings API (`Settings::categories()`) are authorized, validated - * and audited; changes made through this model are not, so application code should prefer the - * API and keep the model to tests and seeding. - * - * Trashed categories (`categories.soft_deletes`) are hidden, as the engine hides them. + * A row of the categories table, for factories, seeders and admin screens. Changes made here skip + * authorization and audit; application code uses `Settings::categories()`. * * @property int|string $id * @property string $store diff --git a/src/Models/SettingDefinition.php b/src/Models/SettingDefinition.php index 80e9db4..2effb9d 100644 --- a/src/Models/SettingDefinition.php +++ b/src/Models/SettingDefinition.php @@ -12,9 +12,8 @@ use Simtabi\Laranail\Settings\Database\Factories\SettingDefinitionFactory; /** - * A row of the optional definitions table (§4.4, `definitions.table`). Definitions are shared - * by every tenant (they describe settings, they do not hold values), so this table has no tenant - * column. `is_system` rows are synced from code and config and are never read over code. + * A row of the optional definitions table. Shared by every tenant, so it has no tenant column. + * `is_system` rows are synced from code and config. * * @property int|string $id * @property string $store @@ -43,7 +42,6 @@ public function getConnectionName(): ?string return parent::getConnectionName() ?? ModelContext::connectionOf(ModelContext::defaultStore()); } - /** Definitions are shared by every tenant. */ public function usesTenantColumn(): bool { return false; diff --git a/src/Notifications/SettingsAlert.php b/src/Notifications/SettingsAlert.php index a287e18..8a6b6d4 100644 --- a/src/Notifications/SettingsAlert.php +++ b/src/Notifications/SettingsAlert.php @@ -13,33 +13,20 @@ use Illuminate\Notifications\Messages\MailMessage; /** - * An alert about a settings event, sent through Laravel's notification channels: mail, the - * database channel, and Slack when laravel/slack-notification-channel is installed. It carries an - * {@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. + * A notification about a settings event, sent by mail, database or Slack. It carries identifiers + * only, never a setting's value. */ final class SettingsAlert extends Notification implements ShouldQueue { use Queueable; - /** - * The legacy Slack message of laravel/slack-notification-channel (incoming webhooks). Kept as - * a string, split so tooling does not turn it into a `::class` of a class that is not installed. - */ + /** Kept as a split string so tooling does not turn it into a `::class` of an optional class. */ 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', @@ -57,7 +44,7 @@ final class SettingsAlert extends Notification implements ShouldQueue /** * @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 + * @param array $texts translated lines by message key; read from the translator when empty */ public function __construct( public readonly AlertContext $context, @@ -67,8 +54,8 @@ public function __construct( ) {} /** - * 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. + * The alert's lines in the current locale, built up front so a queued alert serializes + * strings rather than a translator. * * @return array */ @@ -84,7 +71,7 @@ public static function texts(Translator $translator): array return $texts; } - /** Whether Slack alerts can be sent (the Slack channel package is installed). */ + /** Whether laravel/slack-notification-channel is installed. */ public static function slackAvailable(): bool { return class_exists(self::SLACK_MESSAGE); @@ -100,8 +87,7 @@ public function toMail(object $notifiable): MailMessage { return new MailMessage() ->subject($this->context->headline()) - // Larastan resolves views without the package's provider, so it cannot see the - // `laranail/settings` namespace this view lives in; PackageLayoutTest proves it exists. + // Larastan cannot see the package's view namespace; PackageLayoutTest proves it exists. ->markdown(self::VIEW, [ // @phpstan-ignore argument.type 'headline' => $this->context->headline(), 'lines' => $this->lines(), @@ -121,10 +107,7 @@ public function toDatabase(object $notifiable): array return $this->toArray($notifiable); } - /** - * The Slack message (incoming webhook), only when the Slack channel package is installed; - * the alert is never routed to Slack otherwise. - */ + /** The Slack message; only built when the Slack channel package is installed. */ public function toSlack(object $notifiable): ?object { if (! class_exists($this->slackMessage)) { diff --git a/src/Owners/MorphMapOwnerResolver.php b/src/Owners/MorphMapOwnerResolver.php index 87f29aa..094c4d7 100644 --- a/src/Owners/MorphMapOwnerResolver.php +++ b/src/Owners/MorphMapOwnerResolver.php @@ -14,15 +14,13 @@ use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** - * 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. + * Resolves the owner a REST URL names from `http.owners` or the morph map. A {@see Settable} + * model is loaded so its parents take part in reads. */ #[Scoped] final readonly class MorphMapOwnerResolver { - /** @param array $owners `http.owners`: alias => class, for aliases outside the morph map */ + /** @param array $owners alias => class, for aliases outside the morph map */ public function __construct( #[Config('laranail.settings.http.owners', [])] private array $owners = [], @@ -52,8 +50,7 @@ public function resolve(string $alias, string $id): Settable|OwnerRef throw new UnknownOwner(sprintf('No [%s] owner with id [%s].', $alias, $id)); } - // Its parents count only when the alias is the model's own morph alias; otherwise the - // owner is addressed by alias and id alone, as the URL named it. + // Parents count only when the alias is the model's own morph alias. return $model->getMorphClass() === $alias ? $model : $ref; } } diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index c11fc01..375f387 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -38,9 +38,11 @@ use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Audit\AutoAuditSink; use Simtabi\Laranail\Settings\Audit\NullAuditSink; use Simtabi\Laranail\Settings\Console\DiffCommand; +use Simtabi\Laranail\Settings\Console\ShowCommand; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Data\ApprovalPolicy; use Simtabi\Laranail\Settings\Models\ModelContext; @@ -119,18 +121,10 @@ /** * Registers laranail/settings with the host application. * - * Every name it registers is vendor-scoped: config at `laranail.settings`, publish tags - * `laranail::settings-*`, and the install command `laranail::settings.install`. Nothing here - * 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. - * - * 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. + * Nothing here touches the database or the filesystem at boot: stores, drivers and definitions + * are built on first use. Most classes are autowired through `#[Scoped]`, `#[Singleton]` and + * `#[Config]` attributes; what is bound here is what configuration chooses or validates. A bad + * configuration value raises InvalidConfiguration naming its config path on first use. */ final class SettingsServiceProvider extends PackageServiceProvider { @@ -140,19 +134,13 @@ 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 - // settings API dispatches CategorySaving/Saved and writes the audit trail). + // Foreign keys stay checked (a child category needs its parent) and events fire. ->hasPackageSeeders(AutoSeederDefinition::make('laranail/settings:defaults') ->seeders([DefaultCategoriesSeeder::class]) ->options(['disable_foreign_key_checks' => false, 'fire_events' => true])) - // 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(); @@ -170,6 +158,7 @@ public function configurePackage(Package $package): void HistoryCommand::class, MakeStoreCommand::class, DoctorCommand::class, + ShowCommand::class, SyncDefinitionsCommand::class, WarmCacheCommand::class, ClearCacheCommand::class, @@ -199,59 +188,81 @@ public function packageRegistered(): void $this->app->scoped(Settings::class, SettingsManager::class); $this->registerTenancy(); + $this->registerDrivers(); $this->registerStores(); + $this->registerCache(); $this->registerDefinitions(); + $this->registerLogging(); + $this->registerAudit(); $this->registerAccess(); $this->registerHttp(); + $this->registerAlerts(); $this->registerTyped(); } #[Override] public function packageBooted(): void { - $app = $this->app; - $events = $app->make(Dispatcher::class); - $config = $app->make(Repository::class); + $config = $this->app->make(Repository::class); - // 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(); - }; + $this->bootReadinessFlush($config); + $this->bootTypedBindings($config); - foreach ([MigrationsEnded::class, JobProcessing::class, 'Laravel\\Octane\\Events\\RequestReceived', ...self::strings($config, 'laranail.settings.readiness.flush_on')] as $event) { - $events->listen($event, $flush); + if (filter_var($config->get('laranail.settings.http.enabled', false), FILTER_VALIDATE_BOOL)) { + $this->bootHttp($config); } - // 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))); - } - } + $this->bootListeners($config); + } - if (filter_var($config->get('laranail.settings.http.enabled', false), FILTER_VALIDATE_BOOL)) { - $this->bootHttp($config); + // Install steps ------------------------------------------------------------------------ + + /** Refuse to install over a same-named table that is not this package's. */ + 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), + )); } + } - // 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); + /** Record the schema the published migrations will produce; an existing record only gains new stores. */ + 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 + { + 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 ($config->get('laranail.settings.listeners.alerts', true) !== false && filter_var($config->get('laranail.settings.alerts.enabled', false), FILTER_VALIDATE_BOOL)) { - $events->listen(SendSettingsAlert::EVENTS, SendSettingsAlert::class); + if ($report['synced'] > 0) { + $command->info(sprintf('Synced %d definition(s) into the definitions table.', $report['synced'])); } } + // Configuration readers ---------------------------------------------------------------- + /** `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; } - /** A Laravel cache repository by store name (null: the default store), or InvalidConfiguration naming `$path`. */ + /** A Laravel cache repository by store name (null for the default store). */ private static function cacheStore(Application $app, mixed $name, string $path): CacheRepository { if ($name !== null && (! is_string($name) || $name === '')) { @@ -268,8 +279,7 @@ private static function cacheStore(Application $app, mixed $name, string $path): } /** - * `configuration.sources`: the merge order of `config`, `database` and `runtime` stores and - * layers, later wins. + * `configuration.sources`: the merge order of config, database and runtime entries, later wins. * * @return list */ @@ -286,8 +296,7 @@ private static function configurationSources(Repository $config): array } /** - * `definitions.sources` (D-6): which of `code`, `config` and `database` are read. Code - * definitions are registered in code and are always read. + * `definitions.sources`: which of code, config and database are read (code always is). * * @return list */ @@ -320,8 +329,7 @@ private static function authorizer(Application $app, mixed $driver, string $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. + // The registry's own collaborators audit through this sink, so it reaches the registry lazily. $database = static fn (): DatabaseAuditSink => new DatabaseAuditSink(static fn (): StoreRegistry => $app->make(StoreRegistry::class)); return match ($sink) { @@ -334,7 +342,7 @@ private static function auditSink(Application $app, mixed $sink, string $path): } /** - * A custom implementation named by class in config: it must exist and implement the contract. + * A custom implementation named by class in config; it must implement the contract. * * @template T of object * @@ -353,83 +361,9 @@ 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)); } - /** - * 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), - )); - } - } - - /** - * 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 - { - 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'])); - } - } + // Registration ------------------------------------------------------------------------- - /** - * 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(Repository $config): void - { - $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')); - } - - $handler = $this->app->make(ExceptionHandler::class); - $app = $this->app; - - if (method_exists($handler, 'renderable')) { - $handler->renderable(static fn (Throwable $exception, Request $request): mixed => $app->make(Problems::class)->render($exception, $request)); - } - } - - /** - * 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. - */ + /** The current tenant, and the context the Eloquent models read it from. */ private function registerTenancy(): void { $this->app->scoped(TenantDiscriminator::class, static function (Application $app): TenantDiscriminator { @@ -448,8 +382,8 @@ private function registerTenancy(): void ); } - /** Drivers, the recorded schema, the stores, the runtime configuration and the cache. */ - private function registerStores(): void + /** The driver factory, the recorded schema, installation evidence and the value encrypter. */ + private function registerDrivers(): void { // 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. @@ -486,6 +420,16 @@ class_exists($installer) ? static function () use ($app, $installer): bool { ); }); + // 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), + )); + } + + /** The store registry, its runtime configuration and the make-store action. */ + private function registerStores(): void + { // 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), @@ -494,7 +438,7 @@ class_exists($installer) ? static function () use ($app, $installer): bool { $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(OperationalLogger::class)->info('laranail/settings runtime configuration: ' . $change, LogContext::of(extra: ['change' => $change])); $app->make(Auditor::class)->record(AuditAction::Configure, AuditOutcome::Allowed, null, null, meta: ['change' => $change]); }, )); @@ -512,7 +456,17 @@ static function (string $change) use ($app): void { sources: self::configurationSources($app->make(Repository::class)), )); - // The settings cache (§7.5): the configured cache store, null for the default one. + $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), + )); + } + + /** The settings cache on the configured cache store, and the action that resets it. */ + private function registerCache(): void + { $this->app->scoped(SettingsCache::class, static function (Application $app): SettingsCache { $config = $app->make(Repository::class); @@ -531,22 +485,9 @@ static function (string $change) use ($app): void { self::cacheEnabled($app) ? $app->make(SettingsCache::class) : null, new StoreName($app->make(Repository::class)->string('laranail.settings.default', 'settings')), )); - - $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), - )); - - // 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), - )); } - /** Code and config definitions, the definitions table (D-6) and the approval policy (§16.7). */ + /** Code and config definitions, the definitions table and the approval policy. */ private function registerDefinitions(): void { $this->app->singleton(DefinitionRegistry::class, static fn (Application $app): DefinitionRegistry => new DefinitionRegistry( @@ -565,8 +506,8 @@ private function registerDefinitions(): void $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 + /** The operational log, on `logging.channel` at `logging.level`. */ + private function registerLogging(): void { $this->app->scoped(OperationalLogger::class, static function (Application $app): OperationalLogger { $config = $app->make(Repository::class); @@ -578,7 +519,11 @@ private function registerAccess(): void $app->make(RuntimeConfiguration::class), ); }); + } + /** The auditor and the sinks `audit.sinks` names. */ + private function registerAudit(): void + { $this->app->scoped(Auditor::class, static function (Application $app): Auditor { $sinks = $app->make(Repository::class)->array('laranail.settings.audit.sinks', []); @@ -588,7 +533,11 @@ private function registerAccess(): void $app->make(RuntimeConfiguration::class), ); }); + } + /** Actor resolution, authorization, verification and the access guard. */ + private function registerAccess(): void + { $this->app->scoped(Authorizer::class, static function (Application $app): Authorizer { $driver = $app->make(Repository::class)->get('laranail.settings.authorization.driver', 'gate'); @@ -646,7 +595,7 @@ private function registerAccess(): void }); } - /** The REST API's idempotency cache, and the alert listener with its rules and throttle. */ + /** The REST API's idempotency cache. */ private function registerHttp(): void { $this->app->bind(IdempotentWrites::class, static fn (Application $app): IdempotentWrites => new IdempotentWrites( @@ -654,7 +603,11 @@ private function registerHttp(): void $app->make(Repository::class)->integer('laranail.settings.http.idempotency.ttl', 86400), $app->make(Repository::class)->string('laranail.settings.cache.prefix', 'laranail-settings'), )); + } + /** The alert listener, with its rules and throttle. */ + private function registerAlerts(): void + { $this->app->bind(SendSettingsAlert::class, static function (Application $app): SendSettingsAlert { $config = $app->make(Repository::class); $throttle = $config->integer('laranail.settings.alerts.throttle', 300); @@ -680,11 +633,7 @@ private function registerHttp(): void }); } - /** - * 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. - */ + /** Each class in `typed.classes` registers its definitions; settings migrations get their migrator. */ private function registerTyped(): void { $app = $this->app; @@ -705,4 +654,73 @@ private function registerTyped(): void Actor::system('settings migration'), )); } + + // Boot --------------------------------------------------------------------------------- + + /** + * db-tools memoises schema readiness in a singleton and has no hook of its own: forget it after + * migrations, per queued job and Octane request, and on the events `readiness.flush_on` names. + */ + private function bootReadinessFlush(Repository $config): void + { + $app = $this->app; + $events = $app->make(Dispatcher::class); + + $flush = static function () use ($app): void { + $app->make(SchemaReadinessInterface::class)->flush(); + }; + + foreach ([MigrationsEnded::class, JobProcessing::class, 'Laravel\\Octane\\Events\\RequestReceived', ...self::strings($config, 'laranail.settings.readiness.flush_on')] as $event) { + $events->listen($event, $flush); + } + } + + /** Each typed settings class in `typed.classes` resolves loaded, through the request's handle. */ + private function bootTypedBindings(Repository $config): void + { + foreach (self::strings($config, 'laranail.settings.typed.classes') as $class) { + if (is_subclass_of($class, TypedSettings::class)) { + $this->app->bind($class, static fn (Application $app): TypedSettings => $class::load($app->make(Settings::class))); + } + } + } + + /** The REST API's routes under `http.prefix`/v1, and problem details for its errors. */ + private function bootHttp(Repository $config): void + { + $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')); + } + + $handler = $this->app->make(ExceptionHandler::class); + $app = $this->app; + + if (method_exists($handler, 'renderable')) { + $handler->renderable(static fn (Throwable $exception, Request $request): mixed => $app->make(Problems::class)->render($exception, $request)); + } + } + + /** The built-in listeners, registered by class so nothing is built until an event fires. */ + private function bootListeners(Repository $config): void + { + $events = $this->app->make(Dispatcher::class); + + if ($config->get('laranail.settings.listeners.log', false) === true) { + $events->listen(LogSettingsEvent::EVENTS, LogSettingsEvent::class); + } + + if ($config->get('laranail.settings.listeners.alerts', true) !== false && filter_var($config->get('laranail.settings.alerts.enabled', false), FILTER_VALIDATE_BOOL)) { + $events->listen(SendSettingsAlert::EVENTS, SendSettingsAlert::class); + } + } } diff --git a/src/Resolution/Explanation.php b/src/Resolution/Explanation.php index 98753ed..a4d8e4e 100644 --- a/src/Resolution/Explanation.php +++ b/src/Resolution/Explanation.php @@ -7,9 +7,7 @@ use Simtabi\Laranail\Settings\Data\Lookup; /** - * How a read was resolved: every (store, scope, locale, layer) tried, in order, and the result. - * For an actor who may not view the value, the result is redacted rather than refused, so the - * path stays explainable. + * How a read was resolved: every step tried, in order, and the result. */ final readonly class Explanation { diff --git a/src/Services/Access/AccessGuard.php b/src/Services/Access/AccessGuard.php index cd81917..a906aae 100644 --- a/src/Services/Access/AccessGuard.php +++ b/src/Services/Access/AccessGuard.php @@ -16,6 +16,7 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Contracts\Authorizer; use Simtabi\Laranail\Settings\Events\AccessWasDenied; use Simtabi\Laranail\Settings\Contracts\ActorResolver; @@ -30,12 +31,9 @@ use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** - * Enforces access for one call: the actor requirement, the token ceiling, the authorizer, the - * undefined-ability policy and step-up verification. Every denial is logged, audited and - * announced ({@see AccessWasDenied}, {@see VerificationWasRequired}) before it is thrown. Trusted - * calls (no actor, or an explicit system actor) are never authorized. + * Enforces access for one call: actor requirement, token ceiling, authorizer and verification. * - * Bound `scoped`: it reads the runtime configuration of the current request. + * Every denial is logged, audited and dispatched as an event before it is thrown. */ final readonly class AccessGuard { @@ -53,7 +51,7 @@ public function __construct( private ?Dispatcher $events = null, ) {} - /** A guard that denies every actor and audits nowhere: the safe default for anything built by hand. */ + /** A guard that denies every actor and audits nowhere. */ public static function closed(): self { return new self( @@ -65,7 +63,7 @@ public static function closed(): self ); } - /** A copy auditing through another auditor (the fake records entries in memory with it). */ + /** A copy auditing through another auditor. */ public function withAuditor(Auditor $auditor): self { return new self( @@ -87,7 +85,7 @@ public function auditor(): Auditor return $this->auditor; } - /** The actor the configured (or runtime) resolver finds for this request, if any. */ + /** The actor the resolver finds for this request, if any. */ public function resolveActor(?Request $request = null): ?Actor { return ($this->runtime?->actorResolver() ?? $this->resolver)->resolve($request); @@ -98,10 +96,7 @@ public function requiresActor(): bool return $this->runtime?->actorRequirement() ?? $this->requireActor; } - /** - * The decision for an actor, with the token ceiling applied and abstentions resolved by - * `authorization.undefined`. Never throws and never audits. - */ + /** The decision for an actor, without throwing or auditing. */ public function decide(Actor $actor, Ability $ability, Subject $subject): Decision { if ($actor->isSystem()) { @@ -121,7 +116,7 @@ public function decide(Actor $actor, Ability $ability, Subject $subject): Decisi return $decision; } - /** Whether the actor may do this right now, without throwing or auditing (used to redact). */ + /** Whether the actor may do this, without throwing or auditing. */ public function allows(Actor $actor, Ability $ability, Subject $subject): bool { return $this->decide($actor, $ability, $subject)->isAllowed(); @@ -200,13 +195,10 @@ private function needsVerification(Decision $decision, Ability $ability, Subject private function refuse(?Actor $actor, Ability $ability, Subject $subject, string $outcome, ?string $reason): void { - $this->logger->warning(sprintf('laranail/settings refused [%s]: %s', $ability->value, $outcome), [ - 'store' => $subject->store->value, - 'key' => $subject->key?->value, - 'scope' => $subject->scope()->value, - 'actor' => $actor?->toArray(), - 'reason' => $reason, - ]); + $this->logger->warning( + sprintf('laranail/settings refused [%s]: %s', $ability->value, $outcome), + LogContext::of($subject->store->value, $subject->key?->value, $subject->scope()->value, $actor, extra: ['reason' => $reason]), + ); $this->auditor->record( AuditAction::fromAbility($ability), @@ -216,8 +208,7 @@ private function refuse(?Actor $actor, Ability $ability, Subject $subject, strin meta: ['refusal' => $outcome, 'detail' => $reason], ); - // At once, not after commit: the refusal throws, so a surrounding transaction is about to - // roll back, and whoever listens for refusals must hear of this one regardless. + // Dispatched now, not after commit: the throw rolls back any surrounding transaction. $this->events?->dispatch($outcome === 'verification_required' && $actor instanceof Actor ? new VerificationWasRequired($ability, $subject, $actor) : new AccessWasDenied($ability, $subject, $actor, $outcome, $reason)); diff --git a/src/Services/Access/Auditor.php b/src/Services/Access/Auditor.php index 643f529..a2f33e0 100644 --- a/src/Services/Access/Auditor.php +++ b/src/Services/Access/Auditor.php @@ -15,8 +15,7 @@ use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** - * Builds audit entries and hands each to every configured sink, then to any sink added at - * runtime with `auditTo()`. A call without an actor is recorded as `system`. + * Builds audit entries and sends each to every configured and runtime sink. */ final readonly class Auditor { @@ -27,7 +26,7 @@ public function __construct( private ?RuntimeConfiguration $runtime = null, ) {} - /** A copy that also writes to these sinks (the fake uses it to record entries in memory). */ + /** A copy that also writes to these sinks. */ public function alsoTo(AuditSink ...$sinks): self { return new self([...$this->sinks, ...array_values($sinks)], $this->clock, $this->runtime); diff --git a/src/Services/Cache/SettingsCache.php b/src/Services/Cache/SettingsCache.php index bc8d683..32894f9 100644 --- a/src/Services/Cache/SettingsCache.php +++ b/src/Services/Cache/SettingsCache.php @@ -13,47 +13,28 @@ use Simtabi\Laranail\Settings\Data\RecordSet; use Simtabi\Laranail\Settings\Data\CacheTarget; use Simtabi\Laranail\Settings\Support\BagCodec; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Logging\OperationalLogger; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The settings cache (design §7.5): raw per-scope bags, never resolved values. + * Caches each scope's raw rows per store ("bags"), never resolved values. * - * A bag holds every row (every locale) one scope has in one store's table, so a write to `team:7` - * invalidates exactly one entry and every owner inheriting from team 7 sees it on the next read - * (G-32). Its key hashes connection, database, tenant, store, table and scope as a - * length-prefixed tuple (R-63: `scope` contains `:`), so no two tenants or databases share an - * entry (G-37). - * - * Invalidation replaces a **generation token** (a fresh ULID) rather than deleting the entry. The - * bag key carries three of them: the scope's, the store's and a global epoch, so one scope, one - * store or everything can be reset with one cache write. A stale-while-revalidate refresh - * computed before a write lands under the old token, where nothing reads any more, so it can - * never restore a value after its invalidation (R-23). An evicted token yields a new random one - * and a miss, where a counter would restart and could revive an old entry (R-41). - * - * Reads go through `Cache::flexible()` once an entry is past its fresh window: the stale bag is - * answered and a refresh is deferred. A scope with no rows is cached as an empty bag. Bags and - * tokens read in a request are held in memory for the rest of it (this service is bound - * `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 to the operational log. A failing invalidation is reported the same way. + * Invalidation replaces a generation token instead of deleting entries. A cache failure falls + * back to the database and is reported to the operational log. */ final class SettingsCache { - /** @var array token key => token, read or written in this request */ + /** @var array token key => token */ private array $tokens = []; - /** @var array bag key => records, read in this request */ + /** @var array bag key => records */ private array $bags = []; /** * @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 ?TenantDiscriminator $tenant the current tenant, none outside any tenant - * @param ?OperationalLogger $log told when the cache fails */ public function __construct( private readonly Repository $cache, @@ -70,8 +51,7 @@ public function __construct( } /** - * These scopes' records: from this request's memory, then the cache, and the rest from - * `$load` in **one** call, whose bags are then cached (an empty one included). + * Load these scopes' records from memory, then the cache, then one call to `$load`. * * @param list $scopes * @param Closure(list): RecordSet $load reads scopes from the store itself @@ -125,7 +105,7 @@ public function forgetAll(): void $this->rotate('all', $this->epochKey(), null); } - /** The key one scope's bag is cached under right now (tokens included). */ + /** The key one scope's bag is cached under now. */ public function bagKey(CacheTarget $target, Scope $scope): string { $tenant = $this->currentTenant(); @@ -134,8 +114,7 @@ public function bagKey(CacheTarget $target, Scope $scope): string } /** - * The bag key of every scope, and the bags already cached (fresh, or stale and being - * refreshed), by scope. + * The bag key of every scope, and the bags already cached, by scope. * * @param non-empty-list $scopes * @param Closure(list): RecordSet $load @@ -178,8 +157,7 @@ private function lookup(CacheTarget $target, array $scopes, Closure $load): arra continue; } - // Past its fresh window: flexible() answers the stale bag and defers a refresh, which - // lands under this key's tokens (so never over a newer write). + // Stale: flexible() answers it and refreshes under this key's tokens, never over a newer write. if ($created + $this->ttl <= now()->getTimestamp()) { $entry = $this->cache->flexible($key, [$this->ttl, $this->lifetime()], fn (): array => $this->codec->encode($this->only($load([$scope]), $scope))); } @@ -195,7 +173,7 @@ private function lookup(CacheTarget $target, array $scopes, Closure $load): arra } /** - * Cache freshly loaded bags in the shape flexible() reads (entry plus its creation time). + * Cache freshly loaded bags in the shape flexible() reads. * * @param list $keys * @param list $bags @@ -219,8 +197,7 @@ private function put(array $keys, array $bags): void } /** - * The (epoch, store, scope) tokens of each scope, as one generation string per scope. Missing - * tokens are created; every token is read in one cache call. + * The epoch, store and scope tokens of each scope as one generation string, created when missing. * * @param non-empty-list $scopes * @@ -292,7 +269,7 @@ private function epochKey(): string return $this->prefix . ':epoch'; } - /** Per store and database, not per tenant: a store reset reaches every tenant's bags. */ + /** Not per tenant, so a store reset reaches every tenant's bags. */ private function storeTokenKey(CacheTarget $target): string { return $this->prefix . ':store:' . $this->hash($target->parts()); @@ -304,7 +281,7 @@ private function scopeTokenKey(CacheTarget $target, string $tenant, Scope $scope } /** - * A length-prefixed tuple, hashed: `a` + `b:c` and `a:b` + `c` stay different (R-63). + * Hash a length-prefixed tuple, so `a` + `b:c` and `a:b` + `c` stay different. * * @param list $parts */ @@ -318,7 +295,7 @@ private function currentTenant(): string return $this->tenant?->current() ?? ''; } - /** Seconds a bag (and a scope token) is kept: fresh plus stale. */ + /** Seconds a bag and a scope token are kept: fresh plus stale. */ private function lifetime(): int { return $this->ttl + $this->stale; @@ -347,9 +324,9 @@ private function unique(array $scopes): array private function failed(string $operation, Throwable $exception): void { - $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()), [ + $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()), LogContext::of(extra: [ 'operation' => $operation, 'exception' => $exception::class, - ]); + ])); } } diff --git a/src/Services/Casting/CasterRegistry.php b/src/Services/Casting/CasterRegistry.php index f7bdfb4..1ebf6d8 100644 --- a/src/Services/Casting/CasterRegistry.php +++ b/src/Services/Casting/CasterRegistry.php @@ -17,8 +17,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; /** - * 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. + * Maps type aliases such as `string`, `bool` or `enum:plan` to casters, never to class names. */ #[Singleton] final class CasterRegistry diff --git a/src/Services/Configuration/PersistedConfiguration.php b/src/Services/Configuration/PersistedConfiguration.php index 93b5ccb..4ce8884 100644 --- a/src/Services/Configuration/PersistedConfiguration.php +++ b/src/Services/Configuration/PersistedConfiguration.php @@ -13,6 +13,7 @@ use Illuminate\Container\Attributes\Scoped; use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\StoreName; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Database\SchemaShape; use Illuminate\Database\ConnectionResolverInterface; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; @@ -25,14 +26,10 @@ use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /** - * Store and layer configuration saved through the API (§16.11, `configuration.persisted`), kept in - * the `settings_stores` table on the default store's connection. Read on first use, never at boot, - * once per request or job (bound `scoped`); an entry that fails validation is logged and skipped, - * so a bad row can never stop the application from booting. Writes are validated the same way - * first and refused with InvalidConfiguration. + * Store and layer configuration saved in the `settings_stores` table. * - * 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. + * Read on first use, never at boot. An invalid entry is logged and skipped so a bad row cannot + * stop the application from booting. */ #[Scoped] final class PersistedConfiguration @@ -46,10 +43,9 @@ final class PersistedConfiguration private int $generation = 0; /** - * @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 array $configStores `laranail.settings.stores` * @param array $configLayers `laranail.settings.layers` */ public function __construct( @@ -72,7 +68,7 @@ public function isEnabled(): bool return filter_var($this->enabled, FILTER_VALIDATE_BOOL) && $this->shape()->storesTable; } - /** Changes whenever an entry is saved or deleted, so registries rebuild. */ + /** Changes whenever an entry is saved or deleted so registries rebuild. */ public function generation(): int { return $this->generation; @@ -90,7 +86,7 @@ public function layers(): array return $this->load()['layers']; } - /** @return list why entries were skipped on the last read (doctor) */ + /** @return list why entries were skipped on the last read */ public function problems(): array { $this->load(); @@ -99,7 +95,7 @@ public function problems(): array } /** - * Save a store entry, as the configuration file would hold it. + * Save a store entry in the configuration file's shape. * * @param array $config * @@ -122,7 +118,7 @@ public function saveLayer(string $name, array $config): void $this->save('layer', $name, $config); } - /** Remove a persisted entry; returns whether there was one. */ + /** Remove a persisted entry and return whether there was one. */ public function delete(string $kind, string $name): bool { $this->assertEnabled(); @@ -241,7 +237,7 @@ private function skip(string $problem): void { $this->problems[] = $problem; - $this->log->warning('laranail/settings skipped a persisted configuration entry: ' . $problem); + $this->log->warning('laranail/settings skipped a persisted configuration entry: ' . $problem, LogContext::of()); } private function changed(): void @@ -273,7 +269,7 @@ private function shape(): SchemaShape return $this->shapes->current(); } - /** The connection of the default store's first database layer, as the configuration file names it. */ + /** The connection of the default store's first database layer. */ private function connection(): Connection { $default = $this->configStores[$this->default] ?? null; diff --git a/src/Services/Configuration/RuntimeConfiguration.php b/src/Services/Configuration/RuntimeConfiguration.php index 25ec516..86bdecd 100644 --- a/src/Services/Configuration/RuntimeConfiguration.php +++ b/src/Services/Configuration/RuntimeConfiguration.php @@ -32,12 +32,10 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** - * Configuration changed in code, for the current request or job only. + * Configuration changed in code for the current request or job only. * - * It is bound `scoped`, so Octane and queue workers flush it between requests: nothing set here - * outlives the request that set it. Store and layer changes are validated exactly like config - * (by building the stores) before they are accepted, so a bad change fails where it is made. - * Store and layer entries are merged over `laranail.settings.stores` / `.layers`; later wins. + * Store and layer changes are validated by building the stores, so a bad change fails where it + * is made. */ final class RuntimeConfiguration { @@ -70,7 +68,7 @@ final class RuntimeConfiguration /** * @param array $storeConfig `laranail.settings.stores` * @param array $layerConfig `laranail.settings.layers` - * @param (Closure(string): void)|null $onChange told about each accepted change (audit and log) + * @param (Closure(string): void)|null $onChange called with each accepted change */ public function __construct( private readonly DriverFactory $driverFactory, @@ -209,8 +207,7 @@ public function allowActorless(): self } /** - * Apply `$change`, run `$run`, then restore everything `$change` altered, even when `$run` - * throws. + * Apply `$change`, run `$run`, then restore the previous configuration even when `$run` throws. * * @template TResult * @@ -288,13 +285,13 @@ public function logger(): ?LoggerInterface return $this->logger; } - /** True or false when set for this request; null defers to `authorization.require_actor`. */ + /** The actor requirement set for this request, or null to use the config. */ public function actorRequirement(): ?bool { return $this->requireActor; } - /** Bumped on every change, so the store registry knows to rebuild. */ + /** Bumped on every change so the store registry knows to rebuild. */ public function generation(): int { return $this->generation; diff --git a/src/Services/Database/AuditRepository.php b/src/Services/Database/AuditRepository.php index 0cd9c5b..121bd59 100644 --- a/src/Services/Database/AuditRepository.php +++ b/src/Services/Database/AuditRepository.php @@ -20,10 +20,7 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; /** - * The audit table on one connection (§16.8): every read, write and delete of audit rows goes - * through here, so the audit sink, the audit query and the retention prune agree on the table, - * the columns, the tenant filter and the row format. In column-mode tenancy a row carries the - * current tenant and a query sees the current tenant's rows only; the prune is application-wide. + * Reads and writes the audit table on one connection, scoped to the current tenant. */ final readonly class AuditRepository { @@ -31,11 +28,7 @@ public function __construct( private DatabaseDriver $database, ) {} - /** - * The audit table a store's entries go to: its own active database layer, else the default - * store's (entries of a store without a database still land somewhere queryable). Null when - * neither has one. - */ + /** The audit table for a store: its own database layer's, else the default store's, else null. */ public static function locate(StoreRegistry $stores, ?StoreName $store): ?self { $database = ($store instanceof StoreName ? $stores->get($store) : $stores->default())->database() ?? $stores->default()->database(); @@ -44,8 +37,7 @@ public static function locate(StoreRegistry $stores, ?StoreName $store): ?self } /** - * One row as an entry; a row missing a required column raises DriverFailure rather than - * inventing an entry. + * Build an entry from one row; a malformed row raises DriverFailure. * * @param array $row */ @@ -92,7 +84,7 @@ public function database(): DatabaseDriver return $this->database; } - /** Write one entry. Its store names the store in an outage message only. */ + /** Write one entry. */ public function insert(AuditEntry $entry): void { $this->database->attempt(new StoreName($entry->store ?? 'audit'), fn (): bool => $this->table()->insert([ @@ -145,10 +137,7 @@ public function query(AuditFilter $filter): Builder return $query->orderByDesc('occurred_at')->orderByDesc('id'); } - /** - * Delete every tenant's rows older than the cutoff (retention is one policy for the whole - * application). The store names the store in an outage message only. - */ + /** Delete every tenant's rows older than the cutoff. */ public function prune(CarbonImmutable $cutoff, StoreName $store): int { return $this->database->attempt($store, fn (): int => $this->table()->where('occurred_at', '<', $cutoff)->delete()); diff --git a/src/Services/Database/CategoryRepository.php b/src/Services/Database/CategoryRepository.php index 02bac8b..58c353d 100644 --- a/src/Services/Database/CategoryRepository.php +++ b/src/Services/Database/CategoryRepository.php @@ -21,14 +21,7 @@ use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; /** - * The categories of one store, in the categories table on the store's connection. Every lookup is - * by (store, slug), so a store can never reach another store's category by accident; naming one - * that exists only in another store raises {@see CategoryStoreMismatch} (G-33). - * - * The recorded schema shape decides the rest: generated uuid / ulid keys (D-5), titles as - * per-locale JSON (D-8), and soft deletes (`categories.soft_deletes`), under which a deleted - * category is trashed and creating its slug again restores that row, so `unique(store, slug)` - * never collides. + * The categories of one store, looked up by store and slug. */ final readonly class CategoryRepository { @@ -40,7 +33,7 @@ public function __construct( /** * The categories of a store, on its active database layer. * - * @throws StoreNotWritable when the store has none: categories are kept in the database + * @throws StoreNotWritable when the store has no active database layer */ public static function of(Store $store): self { @@ -132,8 +125,7 @@ public function rename(CategorySlug $slug, string $title): void } /** - * Put a category under another (or at the top, with null). Moving it under itself or one - * of its descendants is refused. + * Move a category under another, or to the top level with null. * * @throws CategoryCycle * @throws CategoryStoreMismatch @@ -152,9 +144,9 @@ public function move(CategorySlug $slug, ?CategorySlug $parent): void } /** - * Delete a category. Its children move to the top level and settings in it lose their - * category, explicitly as well as through the foreign keys (SQLite may not enforce them). - * With soft deletes the row is trashed rather than removed. + * Delete a category, moving its children to the top level and unlinking its settings. + * + * Unlinks explicitly because SQLite may not enforce the foreign keys. * * @throws UnknownCategory */ @@ -200,7 +192,7 @@ private function ancestors(int|string $id): array $ancestors = []; $current = $id; - // Bounded by the number of categories, so a cycle already in the data cannot loop forever. + // Bounded, so a cycle already in the data cannot loop forever. for ($guard = 0; $guard < 10_000; $guard++) { $parent = $this->database->attempt($this->store, fn (): mixed => $this->query()->where('id', $current)->value('parent_id')); @@ -255,13 +247,13 @@ private function softDeletes(): bool return $this->database->shape()->categoriesSoftDeletes; } - /** Titles and descriptions as `translations.mode` stores them (D-8). */ + /** Titles and descriptions as `translations.mode` stores them. */ private function translations(): Translations { return new Translations($this->database->shape()->translations); } - /** The categories table, limited to the current tenant (column-mode tenancy). */ + /** The categories table, limited to the current tenant. */ private function table(): Builder { return $this->database->scoped($this->database->connection()->table($this->database->names()->categories())); diff --git a/src/Services/Database/ChangeRequestRepository.php b/src/Services/Database/ChangeRequestRepository.php index 3789c45..2ac0dfa 100644 --- a/src/Services/Database/ChangeRequestRepository.php +++ b/src/Services/Database/ChangeRequestRepository.php @@ -24,9 +24,7 @@ use Simtabi\Laranail\Settings\Exceptions\UnknownChangeRequest; /** - * The change requests table on one connection (§16.7): every read and write of change requests - * goes through here. In column-mode tenancy a request carries the current tenant and a query sees - * the current tenant's requests only; the expiry and retention sweeps are application-wide. + * Reads and writes the change requests table on one connection, scoped to the current tenant. */ final readonly class ChangeRequestRepository { @@ -35,8 +33,7 @@ public function __construct( ) {} /** - * Where a store's change requests live: its active database layer's connection, when the - * recorded schema has the change requests table. + * The repository for a store's change requests. * * @throws ApprovalUnavailable when the store cannot hold change requests */ @@ -52,7 +49,7 @@ public static function of(Store $store): self } /** - * One row as a request; a malformed row raises DriverFailure rather than inventing a request. + * Build a request from one row; a malformed row raises DriverFailure. * * @param array $row */ @@ -102,7 +99,7 @@ public static function request(array $row): ChangeRequest ); } - /** The current tenant's request with this id in the store, or UnknownChangeRequest. */ + /** @throws UnknownChangeRequest */ public function get(StoreName $store, string $id): ChangeRequest { return $this->find($store, $id) ?? throw new UnknownChangeRequest(sprintf('Store [%s] has no change request [%s].', $store, $id)); @@ -175,8 +172,7 @@ public function list(ChangeFilter $filter, int $limit = 100, ?string $after = nu } /** - * Move a request from one of `$from` to a new status, recording who decided it; returns - * false when it was no longer in any of `$from` (somebody else decided it first). + * Move a request from one of `$from` to a new status; false when someone else decided it first. * * @param list $from * @param list|null $approvals the approvals so far, when they change @@ -211,9 +207,8 @@ public function transition(ChangeRequest $request, array $from, ChangeStatus $to return true; } - // MySQL reports changed rows, not matched rows, so an update writing identical - // values reports 0. That can only happen when the target status is itself one of - // the allowed ones (approved -> approved); any other target means somebody else won. + // MySQL counts changed rows, so an identical update reports 0; that only means a lost + // race when the target status is not one of the allowed ones. if (! in_array($columns['status'], $statuses, true)) { return false; } @@ -226,12 +221,11 @@ public function transition(ChangeRequest $request, array $from, ChangeStatus $to } /** - * Rewrite every tenant's encrypted proposed payloads (re-encryption). `$rewrite` returns null - * when it cannot read a payload (counted as failed, left as it was). Returns [rewritten, failed]. + * Rewrite every tenant's encrypted proposed payloads. * - * @param Closure(string): ?string $rewrite + * @param Closure(string): ?string $rewrite returns null when it cannot read a payload * - * @return array{int, int} + * @return array{int, int} rewritten and failed counts */ public function rewriteEncrypted(StoreName $store, Closure $rewrite): array { @@ -258,7 +252,7 @@ public function rewriteEncrypted(StoreName $store, Closure $rewrite): array }); } - /** Rename an owner alias in every tenant's open and decided requests (rescope, G-30). */ + /** Rename an owner alias in every tenant's requests. */ public function rescope(StoreName $store, string $from, string $to): int { return $this->database->attempt($store, function () use ($from, $to): int { @@ -275,10 +269,9 @@ public function rescope(StoreName $store, string $from, string $to): int } /** - * Mark every tenant's open requests past their expiry as expired, and delete decided requests - * last touched before `$cutoff`. Returns [expired, deleted]. + * Expire overdue open requests and delete decided ones older than `$cutoff`, for every tenant. * - * @return array{int, int} + * @return array{int, int} expired and deleted counts */ public function sweep(CarbonImmutable $now, ?CarbonImmutable $cutoff, StoreName $store): array { @@ -300,7 +293,7 @@ public function sweep(CarbonImmutable $now, ?CarbonImmutable $cutoff, StoreName }); } - /** How many of the current tenant's requests are open but past their expiry (doctor). */ + /** How many of the current tenant's open requests are past their expiry. */ public function overdue(CarbonImmutable $now, StoreName $store): int { return $this->database->attempt($store, fn (): int => $this->database->scoped($this->table()) diff --git a/src/Services/Database/DefinitionsRepository.php b/src/Services/Database/DefinitionsRepository.php index c6ee1e6..e3b525c 100644 --- a/src/Services/Database/DefinitionsRepository.php +++ b/src/Services/Database/DefinitionsRepository.php @@ -16,9 +16,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; /** - * The definitions table on one connection (D-6, §4.4): syncing code and config definitions in as - * `is_system` rows, and reading the rows edited at runtime. Definitions are shared by every - * tenant, so nothing here filters on the tenant column. + * Reads and writes the definitions table, which every tenant shares. */ final readonly class DefinitionsRepository { @@ -48,8 +46,7 @@ public function runtimeRows(StoreName $store): array } /** - * Upsert a store's code and config definitions as system rows and remove system rows no - * definition covers any more; a runtime row sharing a key is a conflict and left alone. + * Sync a store's code and config definitions as system rows, leaving runtime rows alone. * * @param list $definitions * @@ -97,10 +94,9 @@ public function sync(StoreName $store, array $definitions): array } /** - * Save a definition edited through the API (§16.11) as a runtime row. A system row (synced - * from code or config) for the key refuses it: code is the source of truth for those. + * Save a definition edited through the API as a runtime row. * - * @throws InvalidDefinition + * @throws InvalidDefinition when a system row already defines the key */ public function save(StoreName $store, Definition $definition): void { @@ -132,7 +128,7 @@ public function save(StoreName $store, Definition $definition): void }); } - /** Delete a runtime definition row; returns whether one was there. System rows are kept. */ + /** Delete a runtime definition row and return whether one was there. */ public function delete(StoreName $store, Key $key): bool { $database = $this->database; diff --git a/src/Services/Database/HistoryRepository.php b/src/Services/Database/HistoryRepository.php index ce1c760..a982a5b 100644 --- a/src/Services/Database/HistoryRepository.php +++ b/src/Services/Database/HistoryRepository.php @@ -24,12 +24,10 @@ use Simtabi\Laranail\Settings\Services\Stores\StoreRegistry; /** - * The value history table on one connection (§4.3): every read, write and delete of history rows - * goes through here. A row keeps the payload before and after a change exactly as the values - * table stored it, so an encrypted value stays encrypted. Rows are looked up by - * (store, scope, key, locale), never by the row reference, so a forget followed by a set keeps one - * trail. In column-mode tenancy a row carries the current tenant and a query sees the current - * tenant's rows only; the retention prune is application-wide. + * Reads and writes the value history table on one connection. + * + * Payloads are kept as the values table stored them, so encrypted values stay encrypted. Rows + * are looked up by store, scope, key and locale, so a forget followed by a set keeps one trail. */ final readonly class HistoryRepository { @@ -37,11 +35,7 @@ public function __construct( private DatabaseDriver $database, ) {} - /** - * The history table of a store: on its active database layer's connection, when the recorded - * schema has one. Null otherwise (a file-only store, a store skipped during bootstrap, or a - * schema recorded without history). - */ + /** The history table of a store, or null when the store has none. */ public static function locate(StoreRegistry $stores, StoreName $store): ?self { $database = $stores->get($store)->database(); @@ -50,8 +44,7 @@ public static function locate(StoreRegistry $stores, StoreName $store): ?self } /** - * One row as an entry; a row missing a required column raises DriverFailure rather than - * inventing an entry. + * Build an entry from one row; a malformed row raises DriverFailure. * * @param array $row */ @@ -99,11 +92,7 @@ public function database(): DatabaseDriver return $this->database; } - /** - * Append one entry. `$before` is the row as it was (null for a first write), `$after` the row - * as it is now (null for a forget). Runs on the caller's transaction, so a failed insert rolls - * the change back with it. - */ + /** Append one entry in the caller's transaction; `$before` is null for a first write, `$after` for a forget. */ public function record( StoreName $store, HistoryOperation $operation, @@ -141,7 +130,7 @@ public function record( ] + $this->database->tenantColumns())); } - /** The highest version this identity's history holds (0 when it has none). */ + /** The highest version in this identity's history, or 0. */ public function latestVersion(StoreName $store, Scope $scope, Key $key, Locale $locale): int { $version = $this->database->attempt($store, fn (): mixed => $this->identity($store, $scope, $key, $locale)->max('version')); @@ -149,7 +138,7 @@ public function latestVersion(StoreName $store, Scope $scope, Key $key, Locale $ return is_numeric($version) ? (int) $version : 0; } - /** The entry that produced this version of the identity's value (never a tombstone), or null. */ + /** The entry that produced this version of the value, or null. */ public function find(StoreName $store, Scope $scope, Key $key, Locale $locale, int $version): ?HistoryEntry { $row = $this->database->attempt($store, fn (): ?object => $this->identity($store, $scope, $key, $locale) @@ -191,11 +180,7 @@ public function query(HistoryFilter $filter): Builder return $query->orderByDesc('version')->orderByDesc('id'); } - /** - * Delete every tenant's entries the retention policy no longer keeps: older than `$cutoff`, - * and/or more than `$keepVersions` versions behind their identity's newest. Returns how many - * went. The store names the store in an outage message only. - */ + /** Delete entries older than `$cutoff` or more than `$keepVersions` behind, and return how many. */ public function prune(?CarbonImmutable $cutoff, ?int $keepVersions, StoreName $store): int { return $this->database->attempt($store, function () use ($cutoff, $keepVersions): int { @@ -234,13 +219,11 @@ public function prune(?CarbonImmutable $cutoff, ?int $keepVersions, StoreName $s } /** - * Rewrite every encrypted payload in the history, every tenant's (re-encryption): the old and - * the new value of each entry. `$rewrite` returns null when it cannot read a payload (counted - * as failed, left as it was). Returns [rewritten, failed]. + * Rewrite every encrypted old and new payload in the history, for every tenant. * - * @param Closure(string): ?string $rewrite + * @param Closure(string): ?string $rewrite returns null when it cannot read a payload * - * @return array{int, int} + * @return array{int, int} rewritten and failed counts */ public function rewriteEncrypted(StoreName $store, Closure $rewrite): array { @@ -278,7 +261,7 @@ public function rewriteEncrypted(StoreName $store, Closure $rewrite): array }); } - /** Rename an owner alias in every tenant's history (rescope, G-30); returns how many entries changed. */ + /** Rename an owner alias in every tenant's history and return how many entries changed. */ public function rescope(StoreName $store, string $from, string $to): int { return $this->database->attempt($store, function () use ($store, $from, $to): int { diff --git a/src/Services/Database/SchemaInspector.php b/src/Services/Database/SchemaInspector.php index 68fdfe9..21cd9c1 100644 --- a/src/Services/Database/SchemaInspector.php +++ b/src/Services/Database/SchemaInspector.php @@ -6,14 +6,12 @@ use Throwable; use Illuminate\Database\Query\Builder; +use Illuminate\Database\Query\JoinClause; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; /** - * What the live database on one connection holds, for `doctor` and for install's foreign-table - * check: tables, columns, the `id` column's type, and rows whose category belongs to another - * store. Introspection that fails reports "unknown" (null) rather than throwing: a check that - * cannot look is not a check that found something. + * Inspects the live database on one connection; a failed inspection returns null instead of throwing. */ final readonly class SchemaInspector { @@ -45,7 +43,7 @@ public function columns(string $table): ?array } } - /** The database type of the table's `id` column; null when there is none or it cannot be read. */ + /** The database type of the table's `id` column, or null. */ public function idType(string $table): ?string { try { @@ -63,7 +61,7 @@ public function idType(string $table): ?string return null; } - /** Rows of a store's values table whose category link names another store (or none). */ + /** How many rows link to a category of another store. */ public function crossStoreCategoryLinks(StoreName $store): int { $database = $this->database; @@ -73,4 +71,37 @@ public function crossStoreCategoryLinks(StoreName $store): int ->where(static fn (Builder $query): Builder => $query->whereNull('category_store')->orWhere('category_store', '!=', $store->value)) ->count()); } + + /** + * Keys whose first segment is not the slug of the category they belong to. + * + * @return list `key (category)` for each mismatched row + */ + public function keysOutsideTheirCategory(StoreName $store): array + { + $database = $this->database; + $values = $database->tableFor($store); + $categories = $database->names()->categories(); + + $rows = $database->attempt($store, static fn (): array => $database->connection()->table($values) + ->join($categories, static fn (JoinClause $join): JoinClause => $join + ->on($categories . '.id', '=', $values . '.category_id') + ->on($categories . '.store', '=', $values . '.category_store')) + ->orderBy($values . '.key') + ->get([$values . '.key as key', $categories . '.slug as slug']) + ->all()); + + $mismatched = []; + + foreach ($rows as $row) { + $key = is_object($row) && property_exists($row, 'key') && is_string($row->key) ? $row->key : ''; + $slug = is_object($row) && property_exists($row, 'slug') && is_string($row->slug) ? $row->slug : ''; + + if (explode('.', $key, 2)[0] !== $slug) { + $mismatched[] = sprintf('%s (%s)', $key, $slug); + } + } + + return array_values(array_unique($mismatched)); + } } diff --git a/src/Services/Database/SchemaShapeRepository.php b/src/Services/Database/SchemaShapeRepository.php index 111c208..856964f 100644 --- a/src/Services/Database/SchemaShapeRepository.php +++ b/src/Services/Database/SchemaShapeRepository.php @@ -12,17 +12,12 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The schema-shape file (`database/settings-schema.php`, or `schema.path`): where `install` and - * `make-store` record the shape their migrations produce, and where the runtime and the - * migrations read it back. Application code, so it works on a read-only filesystem once written. - * - * Bound `scoped`: the file is read once per request or job, never at boot. + * Reads and writes the schema-shape file that `install` and `make-store` record. */ final class SchemaShapeRepository { private ?SchemaShape $current = null; - /** @param Repository $config the configuration the configured shape is described by */ public function __construct( private readonly Filesystem $files, private readonly string $path, @@ -69,15 +64,16 @@ public function configured(): SchemaShape 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. */ + /** The recorded shape, else the configured one. */ public function current(): SchemaShape { return $this->current ??= $this->recorded() ?? $this->configured(); } /** - * Record the configured shape. Anything already recorded wins: its switches and its stores - * describe tables that may already exist, so only stores new to the file are added. + * Record the configured shape, keeping anything already recorded. + * + * Recorded entries describe tables that may already exist, so only new stores are added. */ public function record(): SchemaShape { @@ -94,7 +90,7 @@ public function record(): SchemaShape return $shape; } - /** Record one more store (make-store); the rest of the file is kept as it is. */ + /** Record one more store, keeping the rest of the file. */ public function recordStore(StoreSchema $store): SchemaShape { $shape = ($this->recorded() ?? $this->configured())->withStore($store); diff --git a/src/Services/Definitions/DatabaseDefinitions.php b/src/Services/Definitions/DatabaseDefinitions.php index f339275..baf8e71 100644 --- a/src/Services/Definitions/DatabaseDefinitions.php +++ b/src/Services/Definitions/DatabaseDefinitions.php @@ -17,18 +17,10 @@ use Simtabi\Laranail\Settings\Services\Database\DefinitionsRepository; /** - * The `database` definition source (D-6): rows of the optional definitions table that are not - * `is_system`. `is_system` rows are copies of code and config definitions, kept for UIs, and are - * skipped: code is the source of truth for those, so an older synced copy can never override a - * release's new default (§4.4). A row only answers for a key that no code or config definition - * covers, so it can never loosen a coded setting. + * The `database` definition source: runtime rows of the definitions table. * - * Rules stored in a row are filtered through `definitions.allowed_rules`, and a row's type must - * be a registered caster alias, so a row can never make the package run arbitrary code. Read on - * first use per store and request (one query), never at boot, and not while the store's - * database layer is skipped (bootstrap mode). - * - * Bound `scoped`. + * System rows are skipped, since code is the source of truth for them. Stored rules are filtered + * through `definitions.allowed_rules`, so a row cannot make the package run arbitrary code. */ final class DatabaseDefinitions { @@ -43,7 +35,7 @@ public function __construct( private readonly bool $enabled = true, ) {} - /** Forget the store's loaded rows, so the next read sees a definition just saved or deleted. */ + /** Forget the store's loaded rows so the next read sees the latest change. */ public function forget(Store $store): void { unset($this->loaded[$store->name->value]); diff --git a/src/Services/Definitions/DefinitionRegistry.php b/src/Services/Definitions/DefinitionRegistry.php index da95246..9ee1757 100644 --- a/src/Services/Definitions/DefinitionRegistry.php +++ b/src/Services/Definitions/DefinitionRegistry.php @@ -13,12 +13,11 @@ use Simtabi\Laranail\Settings\Services\Casting\CasterRegistry; /** - * Every known setting definition, from code (`define()`) and from the `definitions` config map. - * The config map is parsed on first use, never at boot. + * Every setting definition from code and from the `definitions` config map. */ final class DefinitionRegistry { - /** Names under `laranail.settings.definitions` that are options (D-6), not setting keys. */ + /** Names under `laranail.settings.definitions` that are options, not setting keys. */ public const array OPTIONS = ['table', 'sources', 'allowed_rules']; /** @var array */ @@ -63,8 +62,7 @@ public function find(StoreName $store, Key $key): ?Definition } /** - * Every definition registered in code and config, in registration order (the definitions - * table sync copies them as `is_system` rows). + * Every definition registered in code and config, in registration order. * * @return list */ @@ -76,9 +74,7 @@ public function all(): array } /** - * Build, without registering, a definition from configuration-style attributes (`type`, - * `default`, `rules`, `encrypted`, …, as in `definitions.`): how a definition saved - * through the API (§16.11) is validated before it is stored. + * Build a definition from config-style attributes without registering it. * * @param array $attributes * diff --git a/src/Services/Definitions/Definitions.php b/src/Services/Definitions/Definitions.php index be805b7..dad098a 100644 --- a/src/Services/Definitions/Definitions.php +++ b/src/Services/Definitions/Definitions.php @@ -12,8 +12,7 @@ use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** - * Which definition applies to a key (D-6): one registered at runtime for this request, then code - * and config, then the definitions table. Scoped, like the runtime configuration it reads. + * Finds the definition for a key: runtime first, then code and config, then the definitions table. */ #[Scoped] final readonly class Definitions @@ -29,10 +28,7 @@ public function find(Store $store, Key $key): ?Definition return $this->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. - */ + /** Find a definition without querying the definitions table. */ 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 7e4bd97..10b96dc 100644 --- a/src/Services/Drivers/DriverFactory.php +++ b/src/Services/Drivers/DriverFactory.php @@ -24,9 +24,7 @@ use Simtabi\Laranail\DbTools\Schema\Contracts\SchemaReadinessInterface; /** - * Builds a layer's driver. Built-in names resolve through {@see DriverType} and an exhaustive - * match (the allow-list); anything else must have been registered with {@see extend()}, as a - * closure, never a class name. + * Builds a layer's driver from a built-in {@see DriverType} or a closure registered with {@see extend()}. */ final class DriverFactory { @@ -57,8 +55,7 @@ public function extend(string $name, Closure $factory): void } /** - * A copy that can also build these custom drivers (runtime configuration uses it, so a - * driver registered for one request never reaches the shared factory). + * A copy that can also build these custom drivers, leaving the shared factory unchanged. * * @param array $drivers */ @@ -98,11 +95,7 @@ public function make(LayerConfig $layer): Driver }; } - /** - * The database layer. `connection` is optional (null = the default connection); `table` is - * set by the store registry from `stores..table`. The driver reads the recorded schema - * shape through `$shape` on use. Nothing connects here. - */ + /** Build the database layer without connecting. */ private function database(LayerConfig $layer): DatabaseDriver { if (! $this->db instanceof ConnectionResolverInterface || ! $this->probe instanceof Closure) { @@ -137,8 +130,7 @@ private function json(LayerConfig $layer): JsonDriver $disk = $this->stringOption($layer, 'disk'); $path = $this->stringOption($layer, 'path'); - // The runtime file may hold settings written before install; never put it where the web - // server serves files from. + // The runtime file may hold settings written before install; never serve it publicly. if ($this->config->get(sprintf('filesystems.disks.%s.visibility', $disk)) === 'public') { throw new InvalidConfiguration(sprintf('laranail.settings.layers.%s.disk: [%s] is public; use a private disk.', $layer->name, $disk)); } diff --git a/src/Services/Resolution/PreloadedRecords.php b/src/Services/Resolution/PreloadedRecords.php index bcbec1d..3d0c486 100644 --- a/src/Services/Resolution/PreloadedRecords.php +++ b/src/Services/Resolution/PreloadedRecords.php @@ -10,11 +10,7 @@ use Simtabi\Laranail\Settings\Data\StoreName; /** - * Records loaded ahead of time for a list of owners (`preload()`, `withSettings()`), so reading a - * page of owners costs one query per store instead of one per owner (G-9). Held for the request - * only (the resolver that owns it is scoped) and dropped for a scope when that scope is written. - * Records are kept per tenant, so a tenant switch inside one request or job can never answer one - * tenant's read from another tenant's preload. + * Records preloaded for a list of owners, kept per tenant for the current request. */ final class PreloadedRecords { @@ -23,7 +19,7 @@ final class PreloadedRecords /** * @param list $scopes - * @param array $loaded layer => records, as the store loaded them for these scopes + * @param array $loaded layer => records */ public function remember(StoreName $store, array $scopes, array $loaded, string $tenant = ''): void { diff --git a/src/Services/Resolution/Resolver.php b/src/Services/Resolution/Resolver.php index 3aa2bbe..4f14996 100644 --- a/src/Services/Resolution/Resolver.php +++ b/src/Services/Resolution/Resolver.php @@ -21,15 +21,10 @@ use Simtabi\Laranail\Settings\Services\Values\ValuePipeline; /** - * Resolves a read through the cascade: + * Resolves a read through the cascade: owner, parents, global value, then the definition default. * - * owner → (if inheritance is allowed) each parent, in its own store → global → definition default - * - * The global step reads the store itself, or a dedicated store's fallback store (§7.2). - * - * At each step the store's layers are tried in order and the requested locale falls back to the - * 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. + * Layers are tried in order at each step, and a stored null is an answer. Each store is read + * once per resolution. */ #[Scoped] final readonly class Resolver @@ -44,8 +39,7 @@ public function __construct( ) {} /** - * Load these scopes now, one read per store and layer, and answer later reads of them from - * memory for the rest of the request. + * Load these scopes now and answer later reads of them from memory for the rest of the request. * * @param list}> $groups */ @@ -56,7 +50,7 @@ public function preload(array $groups): void } } - /** Drop what was preloaded for one scope (it was just written). */ + /** Drop what was preloaded for one scope after a write. */ public function forgetPreloaded(Store $store, Scope $scope): void { $this->preloaded->forget($store->name, $scope, $this->tenant()); @@ -96,7 +90,7 @@ public function resolve(Store $store, Key $key, Locale $locale, ?OwnerRef $owner } /** - * Ordered (store, scope) steps to try. + * The store and scope steps to try, in order. * * @param list $parents * @@ -127,7 +121,7 @@ private function plan(Store $store, ?OwnerRef $owner, array $parents, ?Definitio } /** - * One load per distinct store, covering every scope the plan needs from it. + * Load each distinct store once for every scope the plan needs from it. * * @param list $plan * @@ -153,7 +147,7 @@ private function loadAll(array $plan): array } /** - * One store's records for these scopes: preloaded scopes from memory, the rest in one read. + * One store's records for these scopes, from memory where preloaded. * * @param list $scopes * @@ -184,7 +178,7 @@ private function load(Store $store, array $scopes): array return $merged; } - /** @return list requested → fallback → none, without duplicates */ + /** @return list the requested, fallback and unlocalised locales, without duplicates */ private function locales(Locale $requested, ?Definition $definition): array { if ($definition instanceof Definition && ! $definition->localised) { @@ -200,7 +194,7 @@ private function locales(Locale $requested, ?Definition $definition): array return array_values($candidates); } - /** The current tenant's key ('' outside any tenant), which partitions the preloaded records. */ + /** The current tenant's key, which partitions the preloaded records. */ private function tenant(): string { return $this->tenant?->current() ?? ''; diff --git a/src/Services/Resolution/ScopeKeys.php b/src/Services/Resolution/ScopeKeys.php index e982837..baa01b3 100644 --- a/src/Services/Resolution/ScopeKeys.php +++ b/src/Services/Resolution/ScopeKeys.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** - * The keys a listing of one scope walks: every key the scope holds in any layer of the store, and - * every key a code or config definition of the store names, in key order. Shared by the PHP - * handle's `all()` and the REST API's `GET …/settings`, so the two list the same keys. + * The keys one scope lists: every stored key and every defined key of the store, in key order. */ final readonly class ScopeKeys { diff --git a/src/Services/Resolution/SettingTargets.php b/src/Services/Resolution/SettingTargets.php index f697856..3668468 100644 --- a/src/Services/Resolution/SettingTargets.php +++ b/src/Services/Resolution/SettingTargets.php @@ -19,9 +19,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\Definitions; /** - * Turns a {@see SettingAddress} (how a caller outside PHP names a setting) into what the actions - * take: the resolved store, the write target with its definition, a handle for reads, and the - * version of the address's own row. The definition is found as a settings handle finds it. + * Turns a {@see SettingAddress} into the store, write target, read handle and version the actions need. */ final readonly class SettingTargets { @@ -59,7 +57,7 @@ public function handle(Settings $settings, SettingAddress $address, ?Actor $acto return $actor instanceof Actor ? $handle->as($actor) : $handle; } - /** The version of the address's own row in the store's writable layer (0 when it has none). */ + /** The version of the address's own row in the writable layer, or 0. */ public function version(SettingAddress $address): int { $store = $this->store($address->store); diff --git a/src/Services/Stores/SettingWriter.php b/src/Services/Stores/SettingWriter.php index 52a78e7..3979e2f 100644 --- a/src/Services/Stores/SettingWriter.php +++ b/src/Services/Stores/SettingWriter.php @@ -16,6 +16,7 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Support\Clock; use Simtabi\Laranail\Settings\Data\Definition; +use Simtabi\Laranail\Settings\Logging\LogContext; use Simtabi\Laranail\Settings\Events\SettingSaved; use Simtabi\Laranail\Settings\Events\SettingLocked; use Simtabi\Laranail\Settings\Events\SettingSaving; @@ -35,24 +36,15 @@ use Simtabi\Laranail\Settings\Services\Database\HistoryRepository; /** - * Every write path: set, forget, lock, unlock. Checks run before anything is stored, in this - * order: definition (strict stores) → owner allowed → lock and precedence → locale → value - * pipeline → the first writable layer, with the version continued from the existing record - * (or from a trashed row, in a store with soft deletes, so the write restores it). + * Every write path: set, forget, lock and unlock. * - * A plain set that loses a race (another writer changed the row between the read and the - * write) is retried once when `writes.retry_on_conflict` is on, re-reading the row under a row - * lock; a write that names the version it expects is never retried. - * - * On a database layer whose schema has the history table (§4.3), every change also appends a - * history entry in the same transaction as the row, so a failed history insert rolls the change - * back. The entry keeps the payload as stored (encrypted values stay encrypted) and names the - * causer given to {@see causedBy()}. A row created again after a forget continues its version - * from the history, so "version N" always means one value. + * Checks the definition, owner, lock, precedence, locale and value before writing to the first + * writable layer. Where the schema has a history table, each change appends a history entry in + * the same transaction. */ final readonly class SettingWriter { - /** @param bool $retryOnConflict `writes.retry_on_conflict`; a retry is logged */ + /** @param bool $retryOnConflict retry a plain set once after a concurrent change */ public function __construct( private ValuePipeline $pipeline, private Dispatcher $events, @@ -64,15 +56,14 @@ public function __construct( private ?string $reason = null, ) {} - /** A copy whose history entries name this causer and reason (null causer: the system). */ + /** A copy whose history entries name this causer and reason; null is the system. */ public function causedBy(?Actor $causer, ?string $reason = null): self { return new self($this->pipeline, $this->events, $this->clock, $this->log, $this->retryOnConflict, $causer, $reason); } /** - * Write a value a rollback recovered, as a new version, only if the row is still at - * `$expectedVersion`; its history entry is a `rollback`. Lock rules apply as for a set. + * Write a recovered value as a new version, recorded as a `rollback`. * * @throws ConcurrentModification */ @@ -81,15 +72,14 @@ public function rollback(Store $store, Key $key, Locale $locale, ?OwnerRef $owne return $this->write($store, $key, $locale, $owner, $definition, $value, $overrideLock, $expectedVersion, HistoryOperation::Rollback); } - /** Store a value and return the stored record. A locked row refuses it. */ + /** Store a value and return the stored record. */ public function set(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value): Record { return $this->write($store, $key, $locale, $owner, $definition, $value, overrideLock: false); } /** - * Store a value only if this scope's row is still at `$expectedVersion` (0: no row yet). - * Anything else raises {@see ConcurrentModification}; it is never retried. + * Store a value only if the row is still at `$expectedVersion` (0 for no row); never retried. * * @throws ConcurrentModification */ @@ -98,17 +88,13 @@ public function setExpecting(Store $store, Key $key, Locale $locale, ?OwnerRef $ return $this->write($store, $key, $locale, $owner, $definition, $value, $overrideLock, $expectedVersion); } - /** - * Store a value over a row lock. Only for a caller that has already established the right - * to (an actor holding `override_lock` on a store whose locks are overridable); the lock - * stays in place. Definition locks and precedence still refuse. - */ + /** Store a value over a row lock, for a caller already allowed to override it. */ public function setOverridingLock(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition, mixed $value): Record { return $this->write($store, $key, $locale, $owner, $definition, $value, overrideLock: true); } - /** Remove this scope's own value; returns the removed record, or null when there was none. */ + /** Remove this scope's own value and return the removed record, if any. */ public function forget(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition): ?Record { return $this->remove($store, $key, $locale, $owner, $definition, overrideLock: false); @@ -128,10 +114,7 @@ public function isLocked(Store $store, Key $key, Locale $locale, ?OwnerRef $owne return $store->writableLayer()->driver->load($store->name, [$scope])->find($scope, $key, $locale)?->locked === true; } - /** - * Lock one row against writes; a lock with no value yet is kept as a value-less row. The - * definition, when given, supplies the row's group, category and visibility. - */ + /** Lock one row against writes, creating a value-less row when none exists. */ public function lock(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, ?Definition $definition = null): Record { return $this->storeLock($store, $key, $locale, $owner, locked: true, definition: $definition); @@ -155,11 +138,12 @@ private function write(Store $store, Key $key, Locale $locale, ?OwnerRef $owner, } $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, - ]); + $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), LogContext::of( + $store->name->value, + $key->value, + $scope->value, + $this->causer, + )); } } } @@ -203,11 +187,7 @@ private function writeOnce(Store $store, Key $key, Locale $locale, ?OwnerRef $ow return $record; } - /** - * The version a write continues: the live row's, else (soft deletes) the trashed row's, so - * the write restores it instead of colliding with it, else the newest version in the history - * (a row created again after a forget continues its trail), else 0. - */ + /** The version a write continues: the live row's, the trashed row's, the history's, or 0. */ private function baseVersion(Layer $layer, Store $store, Scope $scope, Key $key, Locale $locale, ?Record $existing): int { if ($existing instanceof Record) { @@ -219,10 +199,7 @@ private function baseVersion(Layer $layer, Store $store, Scope $scope, Key $key, return max($trashed, $this->history($layer)?->latestVersion($store->name, $scope, $key, $locale) ?? 0); } - /** - * Store a record and, where the layer keeps history, its history entry, in one transaction - * (a savepoint inside the caller's), so a failed history insert undoes the row. - */ + /** Store a record and its history entry in one transaction. */ private function persist(Store $store, Layer $layer, HistoryOperation $operation, ?Record $before, Record $after): void { $history = $this->history($layer); diff --git a/src/Services/Stores/StoreRegistry.php b/src/Services/Stores/StoreRegistry.php index 3f40e8a..f982c71 100644 --- a/src/Services/Stores/StoreRegistry.php +++ b/src/Services/Stores/StoreRegistry.php @@ -31,8 +31,7 @@ use Simtabi\Laranail\Settings\Services\Configuration\PersistedConfiguration; /** - * Builds and validates every store from configuration on first use. Configuration errors are - * raised here, naming the config path, rather than surfacing later as a wrong value. + * Builds and validates every store from configuration on first use. */ final class StoreRegistry { @@ -45,8 +44,8 @@ final class StoreRegistry /** * @param array $storeConfig `laranail.settings.stores` * @param array $layerConfig `laranail.settings.layers` - * @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 + * @param ?Dispatcher $events receives {@see LayerSkipped} when bootstrap mode skips a layer + * @param list $sources merge order of config, database and runtime entries; later wins */ public function __construct( private readonly DriverFactory $drivers, @@ -62,16 +61,13 @@ public function __construct( private readonly array $sources = ['config', 'database', 'runtime'], ) {} - /** A copy whose every layer is replaced by one driver (used by the fake). */ + /** A copy whose every layer is replaced by one driver. */ public function withEveryLayer(Driver $driver): self { return new self($this->drivers, $this->default, $this->storeConfig, $this->layerConfig, $driver, $this->runtime, $this->evidence, $this->events, $this->cache, $this->persisted, $this->sources); } - /** - * Build every store and every defined layer, raising InvalidConfiguration for the first - * problem. Runtime configuration calls this before accepting a change. - */ + /** @throws InvalidConfiguration for the first problem in any store or layer */ public function validate(): void { $this->all(); @@ -91,7 +87,7 @@ public function get(StoreName $name): Store return $this->all()[$name->value] ?? throw new UnknownStore(sprintf('Store [%s] is not configured in laranail.settings.stores.', $name)); } - /** Where a store's global values live: the store itself, or a dedicated store's fallback. */ + /** The store holding a store's global values: itself, or a dedicated store's fallback. */ public function globalOf(Store $store): Store { return $store->fallback instanceof StoreName ? $this->get($store->fallback) : $store; @@ -199,9 +195,9 @@ private function build(): array } /** - * A layer built for one store: a database layer learns the store's table, in a store in - * bootstrap mode it is put behind the bootstrap gate, and with caching on it is read through - * the settings cache (outside the gate, so a skipped layer is never cached). + * Build a layer for one store, with the bootstrap gate and settings cache where configured. + * + * The cache wraps the gate, so a skipped layer is never cached. */ private function storeLayer(string $name, string $storePath, StoreName $store, ?string $table, bool $bootstrap): Layer { @@ -223,7 +219,7 @@ private function gatedLayer(Layer $layer, StoreName $store, bool $bootstrap): La 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) */ + /** @param array $extra options the store adds */ private function layer(string $name, string $storePath, array $extra = []): Layer { $config = $this->layerConfigs()[$name] ?? null; @@ -258,7 +254,7 @@ private function layerConfigs(): array /** * @param array $config - * @param Closure(): array $persisted read only when `database` is a source + * @param Closure(): array $persisted * @param array $runtime * * @return array @@ -311,7 +307,7 @@ private function approvalKeys(mixed $approvals, string $path): array return $globs; } - /** @return list a list of strings, or InvalidConfiguration naming `$path` */ + /** @return list */ private function strings(mixed $value, string $path): array { $strings = is_array($value) ? array_values(array_filter($value, is_string(...))) : null; diff --git a/src/Services/Tenancy/TenantDiscriminators.php b/src/Services/Tenancy/TenantDiscriminators.php index deebf9b..c000ed6 100644 --- a/src/Services/Tenancy/TenantDiscriminators.php +++ b/src/Services/Tenancy/TenantDiscriminators.php @@ -11,10 +11,7 @@ use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; /** - * Builds the configured tenant discriminator (`tenancy.discriminator`): `auto` (stancl/tenancy, - * then spatie/laravel-multitenancy, when installed; else none), `null`, `stancl`, `spatie`, or a - * class implementing TenantDiscriminator. Neither tenancy package is required: both are detected - * with `class_exists` and read through the container, so no class of theirs is referenced. + * Builds the tenant discriminator named by `tenancy.discriminator`. */ final readonly class TenantDiscriminators { @@ -64,7 +61,7 @@ private function stancl(): mixed return is_object($tenant) && method_exists($tenant, 'getTenantKey') ? $tenant->getTenantKey() : null; } - /** spatie/laravel-multitenancy's current tenant key (its container binding), or null. */ + /** spatie/laravel-multitenancy's current tenant key, or null. */ private function spatie(): mixed { if (! $this->container->bound($this->spatieBinding)) { diff --git a/src/Services/Transfer/Importers.php b/src/Services/Transfer/Importers.php index 5c3b0ec..9d0acd8 100644 --- a/src/Services/Transfer/Importers.php +++ b/src/Services/Transfer/Importers.php @@ -10,14 +10,11 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The importers `import --from=` can use (`importers`, name => class), built on first use. - * A name that is not configured, or a class that is not an {@see Importer}, raises - * InvalidConfiguration naming the config path. + * The configured importers `import --from=` can use, built on first use. */ final readonly class Importers { /** - * @param Container $container builds a configured importer with its dependencies * @param array $classes `laranail.settings.importers` */ public function __construct( diff --git a/src/Services/Transfer/StoreSnapshots.php b/src/Services/Transfer/StoreSnapshots.php index 6302907..18424e8 100644 --- a/src/Services/Transfer/StoreSnapshots.php +++ b/src/Services/Transfer/StoreSnapshots.php @@ -19,9 +19,7 @@ use Simtabi\Laranail\Settings\Services\Database\CategoryRepository; /** - * Reads a store's database layer into an {@see ExportDocument}, and compares a store with one. - * Values are the stored JSON as it is (lossless whatever the caster), so nothing is cast on the - * way out; encrypted values follow the export mode. Only the current tenant's rows are read. + * Exports a store's current-tenant rows to an {@see ExportDocument} and compares a store with one. */ final readonly class StoreSnapshots { @@ -30,7 +28,7 @@ public function __construct( private ValueEncoder $encoder, ) {} - /** Whether two exported settings hold the same value (and lock). */ + /** Whether two exported settings hold the same value and lock. */ public static function same(ExportedSetting $a, ExportedSetting $b): bool { if ($a->ciphertext !== null || $b->ciphertext !== null) { @@ -66,9 +64,9 @@ public function export(Store $store, ExportMode $mode): ExportDocument } /** - * Compare the store with a document. Encrypted values are compared by ciphertext only when - * both sides hold one (it changes with every encryption, so "changed" may be a re-encryption); - * a redacted side cannot be compared. + * Compare the store with a document. + * + * Encrypted values compare by ciphertext, so a re-encryption reads as a change. */ public function diff(Store $store, ExportDocument $document): StoreDiff { diff --git a/src/Services/Values/ValuePipeline.php b/src/Services/Values/ValuePipeline.php index 50f01f5..47d55b1 100644 --- a/src/Services/Values/ValuePipeline.php +++ b/src/Services/Values/ValuePipeline.php @@ -27,7 +27,7 @@ public function __construct( private ValueEncoder $encoder, ) {} - /** The encoded (and, for an encrypted definition, encrypted) payload. */ + /** The encoded, and where defined encrypted, payload. */ public function toPayload(Key $key, mixed $value, ?Definition $definition): string { $this->validator->validate($key, $value, $definition->rules ?? []); diff --git a/src/SettingsManager.php b/src/SettingsManager.php index c043093..be71184 100644 --- a/src/SettingsManager.php +++ b/src/SettingsManager.php @@ -74,10 +74,8 @@ 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 write actions, which authorize and audit. Every fluent - * method returns a copy, so a handle is never changed in place. + * The {@see Settings} implementation: an immutable handle over a store, owner, locale and actor. + * Fluent methods return a copy. */ final class SettingsManager implements Settings { @@ -94,10 +92,6 @@ final class SettingsManager implements Settings private ?string $reason = null; - /** - * 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 readonly StoreRegistry $stores, private readonly DefinitionRegistry $registry, @@ -518,8 +512,7 @@ private function scope(): Scope } /** - * The store, key, definition and subject of a read, after checking `view` (or that an actor - * is not required) and the strict-store rule. + * The store, key, definition and subject of a read, after the access and strict-store checks. * * @return array{Store, Key, ?Definition, Subject} */ @@ -579,10 +572,7 @@ private function activeLocale(): Locale return $this->selectedLocale ?? Locale::none(); } - /** - * A definition registered at runtime for this request wins over the shared registry (code and - * config); the definitions table answers only for keys neither covers (D-6). - */ + /** Runtime definitions win over the registry; the definitions table answers only for the rest. */ private function definition(Store $store, Key $key): ?Definition { return $this->definitions->find($store, $key); diff --git a/src/Stores/InstallationEvidence.php b/src/Stores/InstallationEvidence.php index 8034767..47232a0 100644 --- a/src/Stores/InstallationEvidence.php +++ b/src/Stores/InstallationEvidence.php @@ -7,14 +7,14 @@ use Closure; /** - * Bootstrap evidence from the operator's flag (`laranail.settings.bootstrap`, set for the install - * window) or from laranail/installer-headless reporting an install in progress. Its - * `isInstalled()` is deliberately not used: with its marker missing it probes the live database, - * which answers "not installed" during an outage. + * Whether an install is in progress, from the `laranail.settings.bootstrap` flag or installer-headless. + * + * Installer-headless' `isInstalled()` is not used: it probes the database, which reads as "not + * installed" during an outage. */ final readonly class InstallationEvidence { - /** @param (Closure(): bool)|null $installing installer-headless' `isInstalling()`, when that package is present */ + /** @param (Closure(): bool)|null $installing installer-headless' `isInstalling()` */ public function __construct( private bool $flag, private ?Closure $installing = null, diff --git a/src/Stores/Store.php b/src/Stores/Store.php index 9de059f..4d1b259 100644 --- a/src/Stores/Store.php +++ b/src/Stores/Store.php @@ -17,18 +17,13 @@ /** * A configured store: its layers in read order, the owner aliases it accepts, and its policies. - * `locksOverridable` (`locks.overridable`) lets an actor holding `override_lock` write a locked - * setting; it is off by default, so a lock binds everyone. `bootstrap` lets the database layer be - * skipped while the application is being installed (§7.4); `table` is the configured values - * table (`stores..table`), null for the store name. A `dedicated` store (D-3) holds owner - * rows only; its global values are read from `fallback`. */ final readonly class Store { /** * @param list $layers * @param list $owners - * @param list $approvalKeys key globs whose writes become change requests (`approvals.keys`) + * @param list $approvalKeys key globs whose writes become change requests */ public function __construct( public StoreName $name, @@ -44,13 +39,13 @@ public function __construct( public array $approvalKeys = [], ) {} - /** Whether `approvals.keys` makes a write of this key a change request (§16.7). */ + /** Whether a write of this key becomes a change request. */ public function requiresApproval(Key $key): bool { return array_any($this->approvalKeys, static fn (string $glob): bool => fnmatch($glob, $key->value, FNM_NOESCAPE)); } - /** Whether this store can hold change requests: its database layer is active and has the table. */ + /** Whether this store has an active database layer with a change requests table. */ public function acceptsChangeRequests(): bool { return $this->database()?->shape()->changeRequestsTable ?? false; @@ -61,13 +56,13 @@ public function isDedicated(): bool return $this->mode === StoreMode::Dedicated; } - /** Whether any layer of this store is a database layer, whether or not it is active. */ + /** Whether any layer of this store is a database layer, active or not. */ public function hasDatabaseLayer(): bool { return array_any($this->layers, fn (Layer $layer): bool => $layer->driver instanceof DatabaseBacked); } - /** The first active database layer's driver, or null (none, or skipped during bootstrap). */ + /** The first active database layer's driver, or null. */ public function database(): ?DatabaseDriver { foreach ($this->layers as $layer) { @@ -80,10 +75,9 @@ public function database(): ?DatabaseDriver } /** - * The first active database layer's driver, or StoreNotWritable: "Store [x] has no active - * database layer" followed by `$why` (`; categories are kept in the database`). + * The first active database layer's driver. * - * @throws StoreNotWritable + * @throws StoreNotWritable with `$why` appended to the message */ public function requireDatabase(string $why): DatabaseDriver { @@ -91,8 +85,7 @@ public function requireDatabase(string $why): DatabaseDriver } /** - * Run a write and everything that must commit with it (the audit row) in one transaction on - * the store's database connection. A store without an active database layer just runs it. + * Run a write and its audit row in one transaction on the store's database connection. * * @template T * @@ -130,10 +123,7 @@ public function isCached(): bool return array_any($this->layers, fn (Layer $layer): bool => $layer->driver instanceof CachingDriver); } - /** - * Forget one scope's cached bag in every cached layer (after the surrounding transaction - * commits), for writes that reach the database without passing through the cache. - */ + /** Forget one scope's cached bag in every cached layer once the transaction commits. */ public function forgetCached(Scope $scope): void { foreach ($this->cachedLayers() as $driver) { @@ -150,8 +140,7 @@ public function forgetCachedStore(): void } /** - * Load these scopes into the cache of every active cached layer (one read per layer on a - * miss, none on a hit); returns how many records the cached layers hold for them. + * Load these scopes into every cached layer and return how many records they hold. * * @param list $scopes */ @@ -169,7 +158,7 @@ public function warmCache(array $scopes): int } /** - * Every layer's records for these scopes, in layer order: one read per layer. + * Every layer's records for these scopes, one read per layer. * * @param list $scopes * diff --git a/src/Support/AuditedTransaction.php b/src/Support/AuditedTransaction.php index 6e75775..f4e89d0 100644 --- a/src/Support/AuditedTransaction.php +++ b/src/Support/AuditedTransaction.php @@ -14,13 +14,8 @@ use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** - * The one way a change and its audit entry are committed: the work and an `allowed` audit entry - * run in one transaction on the store's database connection (when it has one), so a failed audit - * insert rolls the change back; on any SettingsException the transaction rolls back, a `failed` - * entry is recorded outside it, and the original exception is rethrown (if recording the failure - * fails too, the original still wins). Authorization happens before this, in the caller. - * - * Used by every write action, every category change and promotion, so all three audit alike. + * Commits a change and its `allowed` audit entry in one transaction. On failure it rolls back, + * records a `failed` entry outside the transaction and rethrows the original exception. */ final readonly class AuditedTransaction { @@ -31,10 +26,10 @@ public function __construct( /** * @template T * - * @param Closure(): T $work the change - * @param (Closure(T): array{from?: ?int, to?: ?int, meta?: array})|null $allowed audit details from the change's result - * @param (Closure(T): void)|null $then runs after the allowed entry, still inside the transaction (events) - * @param array $meta meta on both the allowed and the failed entry + * @param Closure(): T $work + * @param (Closure(T): array{from?: ?int, to?: ?int, meta?: array})|null $allowed audit details from the result + * @param (Closure(T): void)|null $then runs inside the transaction after the audit entry + * @param array $meta * * @return T */ diff --git a/src/Support/BagCodec.php b/src/Support/BagCodec.php index fc511ef..45bcf67 100644 --- a/src/Support/BagCodec.php +++ b/src/Support/BagCodec.php @@ -13,15 +13,12 @@ use Simtabi\Laranail\Settings\Data\RecordSet; /** - * Converts one scope's raw records (a "bag", design §7.5) to and from the plain array the cache - * holds. Plain arrays rather than objects, so the cache never unserializes a package class (an - * application may restrict `cache.serializable_classes`). An empty bag encodes to a non-null - * array, which is what lets a miss be cached. A payload that does not decode, from an older - * release or a corrupted entry, reads as no entry at all, never as an empty bag. Stateless. + * Converts one scope's records to and from the plain array the cache holds. A payload that does + * not decode reads as a cache miss, never as an empty scope. */ final readonly class BagCodec { - /** Bumped when the encoded shape changes, so an entry written by another release is a miss. */ + /** Bump when the encoded shape changes, so entries from another release are misses. */ public const int VERSION = 1; /** @return array{v: int, r: list>} */ @@ -43,7 +40,7 @@ public function encode(RecordSet $records): array ], $records->all())]; } - /** The records an entry holds, or null when it is not an entry this release wrote. */ + /** The records an entry holds, or null when this release did not write it. */ public function decode(mixed $entry): ?RecordSet { if (! is_array($entry) || ($entry['v'] ?? null) !== self::VERSION || ! is_array($entry['r'] ?? null)) { diff --git a/src/Support/Clock.php b/src/Support/Clock.php index c7c70f3..0fc3207 100644 --- a/src/Support/Clock.php +++ b/src/Support/Clock.php @@ -8,8 +8,7 @@ use Illuminate\Support\Facades\Date; /** - * The current time, through Laravel's date seam, so `$this->travelTo()` and `Date::use()` reach - * every timestamp the package writes. The one place the package reads the clock. + * The current time through Laravel's date seam, so `travelTo()` and `Date::use()` apply. */ final readonly class Clock { diff --git a/src/Support/DatabaseValues.php b/src/Support/DatabaseValues.php index 0771ede..adc59f4 100644 --- a/src/Support/DatabaseValues.php +++ b/src/Support/DatabaseValues.php @@ -5,11 +5,11 @@ namespace Simtabi\Laranail\Settings\Support; /** - * Reading column values the way each database returns them. Stateless. + * Normalises column values across database drivers. */ final readonly class DatabaseValues { - /** A boolean column: drivers return bool, int or a numeric string; anything else is false. */ + /** Drivers return bool, int or a numeric string; anything else is false. */ public static function boolean(mixed $value): bool { return in_array($value, [true, 1, '1'], true); diff --git a/src/Support/EventSummary.php b/src/Support/EventSummary.php index de94ede..40adaf5 100644 --- a/src/Support/EventSummary.php +++ b/src/Support/EventSummary.php @@ -9,10 +9,8 @@ use Simtabi\Laranail\Settings\Data\Subject; /** - * A package event flattened to identifiers, for the operational log and for alerts: scalar - * properties as they are, a Subject as store / scope / key / locale / category, an Actor as - * `actor` (type, alias and id), an enum as its value. Events never carry a value, and this adds - * none: anything else (an object it does not know) is left out rather than stringified. + * Flattens a package event to identifiers for the log and alerts. Unknown objects are left out + * rather than stringified. */ final readonly class EventSummary { diff --git a/src/Support/Json.php b/src/Support/Json.php index 827a2cd..f40ee85 100644 --- a/src/Support/Json.php +++ b/src/Support/Json.php @@ -8,15 +8,13 @@ use Simtabi\Laranail\Settings\Exceptions\DriverFailure; /** - * JSON for the package's own columns (titles, rules, owner lists, audit meta), with one set of - * flags: unescaped Unicode and slashes, so a stored value reads as it was written. An encoding - * failure is a DriverFailure naming what was being stored. Stateless. + * Encodes and decodes the package's own JSON columns, with unescaped Unicode and slashes. */ final readonly class Json { /** * @param array $value - * @param string $what what is being encoded, for the error (`A definition`, `An audit entry's meta`) + * @param string $what what is being encoded, for the error message * * @throws DriverFailure */ @@ -30,8 +28,7 @@ public static function encode(array $value, string $what): string } /** - * A JSON list of strings, or [] for null, invalid JSON or anything that is not a list of - * strings (non-string entries are dropped). + * A JSON list of strings; [] for null or invalid JSON, and non-string entries dropped. * * @return list */ diff --git a/src/Support/LaravelValueEncrypter.php b/src/Support/LaravelValueEncrypter.php index 7e3b408..811843d 100644 --- a/src/Support/LaravelValueEncrypter.php +++ b/src/Support/LaravelValueEncrypter.php @@ -12,9 +12,8 @@ use Simtabi\Laranail\Settings\Exceptions\EncryptionUnavailable; /** - * Laravel's encrypter, resolved only when a value is encrypted or decrypted, so an application - * without an APP_KEY yet (before install) still boots and reads its unencrypted settings. - * Laravel's encrypter already tries APP_PREVIOUS_KEYS when decrypting. + * Laravel's encrypter, resolved lazily so an application without an APP_KEY still boots and reads + * its unencrypted settings. */ final class LaravelValueEncrypter { diff --git a/src/Support/LaravelValueValidator.php b/src/Support/LaravelValueValidator.php index 34713ef..bcb6400 100644 --- a/src/Support/LaravelValueValidator.php +++ b/src/Support/LaravelValueValidator.php @@ -9,8 +9,8 @@ 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. + * Validates a value against a definition's rules before casting, so rules see what the caller + * passed. */ final readonly class LaravelValueValidator { diff --git a/src/Support/RecordSerializer.php b/src/Support/RecordSerializer.php index 8e815e1..a6464d2 100644 --- a/src/Support/RecordSerializer.php +++ b/src/Support/RecordSerializer.php @@ -12,9 +12,7 @@ use Illuminate\Container\Attributes\Singleton; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; -/** - * Converts records to and from the plain arrays file layers store. - */ +/** Converts records to and from the plain arrays file layers store. */ #[Singleton] final readonly class RecordSerializer { diff --git a/src/Support/Translations.php b/src/Support/Translations.php index 43deec1..7e32380 100644 --- a/src/Support/Translations.php +++ b/src/Support/Translations.php @@ -7,10 +7,8 @@ use Simtabi\Laranail\Settings\Enums\TranslationsMode; /** - * How titles, labels and descriptions are stored (D-8, `translations.mode`): under `lang` the - * text itself; under `json` a JSON map of locale to text, where `''` is the text for any locale. - * One reader and one writer for categories, definitions and the factories, so the format cannot - * drift between them. Stateless. + * Reads and writes titles, labels and descriptions per `translations.mode`: plain text, or a JSON + * map of locale to text where `''` applies to any locale. */ final readonly class Translations { @@ -26,7 +24,7 @@ public function isJson(): bool /** * The text as the column holds it. * - * @param array $translations locale => text (json mode only) + * @param array $translations locale => text, used in json mode */ public function store(string $text, array $translations = []): string { @@ -62,8 +60,7 @@ public function nullableText(?string $stored): ?string } /** - * Every text by locale; `['' => stored]` under `lang`, or when the stored value is not a - * JSON map with at least one text. + * Every text by locale; `['' => stored]` when the value is not a JSON map of texts. * * @return array */ diff --git a/src/Support/ValueEncoder.php b/src/Support/ValueEncoder.php index ca05e34..5514cc2 100644 --- a/src/Support/ValueEncoder.php +++ b/src/Support/ValueEncoder.php @@ -10,8 +10,7 @@ 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). + * Encodes values as JSON. A stored null becomes the string `null`, distinct from no value. */ #[Singleton] final readonly class ValueEncoder diff --git a/src/Tenancy/ClosureTenantDiscriminator.php b/src/Tenancy/ClosureTenantDiscriminator.php index 551b0a3..46d1945 100644 --- a/src/Tenancy/ClosureTenantDiscriminator.php +++ b/src/Tenancy/ClosureTenantDiscriminator.php @@ -10,10 +10,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /** - * The tenant a closure reports: how the stancl/tenancy and spatie/laravel-multitenancy adapters - * are built (the closure asks the tenancy package), and a way for an application to plug in its - * own. An integer or Stringable key is turned into a string; anything else, or a key longer than - * 64 characters, is refused rather than truncated, because two tenants must never share a key. + * The tenant a closure reports. Keys longer than 64 characters are refused rather than truncated, + * so two tenants never share a key. */ final readonly class ClosureTenantDiscriminator implements TenantDiscriminator { diff --git a/src/Testing/FakeLog.php b/src/Testing/FakeLog.php index 0a59bc3..d09a099 100644 --- a/src/Testing/FakeLog.php +++ b/src/Testing/FakeLog.php @@ -6,9 +6,7 @@ use Simtabi\Laranail\Settings\Audit\InMemoryAuditSink; -/** - * The writes and audit entries a {@see SettingsFake} and its derived handles recorded. - */ +/** The writes and audit entries a {@see SettingsFake} and its handles recorded. */ final class FakeLog { /** @var list */ diff --git a/src/Testing/SettingsFake.php b/src/Testing/SettingsFake.php index 9d4027b..5ec851d 100644 --- a/src/Testing/SettingsFake.php +++ b/src/Testing/SettingsFake.php @@ -33,12 +33,8 @@ use Simtabi\Laranail\Settings\Services\Configuration\RuntimeConfiguration; /** - * Installed by `Settings::fake()`: the real engine over in-memory layers, recording writes and - * every audit entry (allowed, denied and failed) so tests can assert on access as well as values. - * Actors, authorizers and verifiers behave exactly as in the real engine. - * - * It replaces the container binding, so it must be installed before the code under test - * resolves `Settings`; anything resolved earlier keeps the real instance. + * The real engine over in-memory layers, recording writes and audit entries for assertions. + * Installed by `Settings::fake()`, before the code under test resolves `Settings`. */ final readonly class SettingsFake implements Settings { @@ -175,7 +171,7 @@ public function forget(string $key): void $this->log->forgotten[] = $key; } - /** Each write goes through this fake's own set(), so assertSaved() sees every key. */ + /** Routed through set() so assertSaved() sees every key. */ public function setMany(array $values): void { foreach ($values as $key => $value) { @@ -183,7 +179,7 @@ public function setMany(array $values): void } } - /** Each key goes through this fake's own forget(), so assertForgotten() sees every key. */ + /** Routed through forget() so assertForgotten() sees every key. */ public function forgetMany(iterable $keys): void { foreach ($keys as $key) { @@ -191,7 +187,7 @@ public function forgetMany(iterable $keys): void } } - /** The write, when one is made, goes through this fake's own set(), so assertSaved() sees it. */ + /** Routed through set() so assertSaved() sees the write. */ public function remember(string $key, callable $value): mixed { $lookup = $this->inner->lookup($key); diff --git a/src/Typed/Attributes/Encrypted.php b/src/Typed/Attributes/Encrypted.php index 8f9edad..bc8a2ec 100644 --- a/src/Typed/Attributes/Encrypted.php +++ b/src/Typed/Attributes/Encrypted.php @@ -6,8 +6,6 @@ use Attribute; -/** - * The property's setting is encrypted at rest: `register()` defines it encrypted. - */ +/** Stores the property's setting encrypted. */ #[Attribute(Attribute::TARGET_PROPERTY)] final readonly class Encrypted {} diff --git a/src/Typed/Attributes/Group.php b/src/Typed/Attributes/Group.php index ada2175..79e41f1 100644 --- a/src/Typed/Attributes/Group.php +++ b/src/Typed/Attributes/Group.php @@ -6,10 +6,7 @@ use Attribute; -/** - * The key prefix of a typed settings class: property `fromAddress` in group `mail` is the key - * `mail.from_address`. - */ +/** The key prefix of a typed settings class: `fromAddress` in group `mail` is `mail.from_address`. */ #[Attribute(Attribute::TARGET_CLASS)] final readonly class Group { diff --git a/src/Typed/Attributes/Key.php b/src/Typed/Attributes/Key.php index 96fbeb4..0887558 100644 --- a/src/Typed/Attributes/Key.php +++ b/src/Typed/Attributes/Key.php @@ -6,9 +6,7 @@ use Attribute; -/** - * The exact key a property maps to, instead of its group and snake-cased name. - */ +/** The exact key a property maps to, instead of its group and snake-cased name. */ #[Attribute(Attribute::TARGET_PROPERTY)] final readonly class Key { diff --git a/src/Typed/Attributes/Store.php b/src/Typed/Attributes/Store.php index 9540dfb..d7b4085 100644 --- a/src/Typed/Attributes/Store.php +++ b/src/Typed/Attributes/Store.php @@ -6,9 +6,7 @@ use Attribute; -/** - * The store a typed settings class reads and writes (default: the handle's store). - */ +/** The store a typed settings class uses instead of the handle's. */ #[Attribute(Attribute::TARGET_CLASS)] final readonly class Store { diff --git a/src/Typed/Attributes/Type.php b/src/Typed/Attributes/Type.php index ffafe3b..77f0044 100644 --- a/src/Typed/Attributes/Type.php +++ b/src/Typed/Attributes/Type.php @@ -6,10 +6,7 @@ use Attribute; -/** - * The caster alias `register()` gives the property's definition, instead of the one its PHP type - * implies (`enum:plan`, `money`). - */ +/** The caster alias for the property's definition, instead of the one its PHP type implies. */ #[Attribute(Attribute::TARGET_PROPERTY)] final readonly class Type { diff --git a/src/Typed/SettingsMigration.php b/src/Typed/SettingsMigration.php index ea53de0..9a2d66e 100644 --- a/src/Typed/SettingsMigration.php +++ b/src/Typed/SettingsMigration.php @@ -9,8 +9,8 @@ use Illuminate\Database\Migrations\Migration; /** - * A database migration that changes settings rather than tables (G-17): renames, moves, deletions - * and new defaults, run with the application's other migrations and in their order. + * A migration that changes settings rather than tables: renames, moves, deletions and new + * defaults, run in order with the application's other migrations. * * return new class extends SettingsMigration * { @@ -25,8 +25,8 @@ * } * }; * - * A migration is built with `new`, so nothing can be injected: the service provider hands this - * class the migrator through {@see resolveMigratorUsing()}, as it hands the models their context. + * Migrations are built with `new`, so the provider supplies the migrator through + * {@see resolveMigratorUsing()}. */ abstract class SettingsMigration extends Migration { diff --git a/src/Typed/SettingsMigrator.php b/src/Typed/SettingsMigrator.php index acd82a9..e0d406b 100644 --- a/src/Typed/SettingsMigrator.php +++ b/src/Typed/SettingsMigrator.php @@ -11,8 +11,8 @@ use Simtabi\Laranail\Settings\Data\SettingsMigrationStep; /** - * What a settings migration (G-17) calls: rename, move, delete and add keys, in the default store - * unless a store is named. Each step runs through {@see MigrateSettings} as the system actor. + * Renames, moves, deletes and adds keys for a settings migration, as the system actor. Uses the + * default store unless one is named. */ final readonly class SettingsMigrator { @@ -30,13 +30,13 @@ public function rename(string $from, string $to, ?string $store = null): int return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::RENAME, $name, new Key($from), $name, new Key($to)), $this->actor); } - /** Move a key from one store to another (optionally under a new key). */ + /** Move a key to another store, optionally under a new key. */ public function move(string $key, string $fromStore, string $toStore, ?string $toKey = null): int { return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::RENAME, new StoreName($fromStore), new Key($key), new StoreName($toStore), new Key($toKey ?? $key)), $this->actor); } - /** Remove a key everywhere: every owner and locale. */ + /** Remove a key for every owner and locale. */ public function delete(string $key, ?string $store = null): int { return $this->migrate->handle(new SettingsMigrationStep(SettingsMigrationStep::DELETE, $this->store($store), new Key($key)), $this->actor); diff --git a/src/Typed/TypedProperty.php b/src/Typed/TypedProperty.php index b8781ed..c7077fe 100644 --- a/src/Typed/TypedProperty.php +++ b/src/Typed/TypedProperty.php @@ -17,10 +17,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; /** - * One public typed property of a typed settings class: the key it maps to, and how its value - * crosses into storage (an enum as its backing value, a date as an ISO 8601 string) and back. - * Supported types: string, int, float, bool, array, a backed enum and the immutable date types, - * each nullable. + * A typed settings property: its key and how its value converts to and from storage. Supports + * string, int, float, bool, array, backed enums and immutable dates, each nullable. */ final readonly class TypedProperty { diff --git a/src/Typed/TypedSettings.php b/src/Typed/TypedSettings.php index 611ad70..f27d446 100644 --- a/src/Typed/TypedSettings.php +++ b/src/Typed/TypedSettings.php @@ -17,10 +17,8 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /** - * Typed settings classes over the key-value engine (Phase 5; the idea is spatie/laravel-settings'): - * a class whose public typed properties map to keys, loaded and saved through a settings handle, - * so the handle's store, owner, locale and actor apply, and every save goes through the same - * write actions as `set()` (validation, encryption, locks, approvals, history, audit). + * A class whose public typed properties map to setting keys, loaded and saved through a settings + * handle. Saves go through the same write actions as `set()`. * * #[Group('mail')] * final class MailSettings extends TypedSettings @@ -33,22 +31,20 @@ * $mail->fromAddress = 'ops@example.com'; * $mail->save(); * - * A property keeps its declared default until a value is stored for its key. `save()` writes only - * the properties that changed since `load()`. `register()` turns the properties into definitions - * (type, default, encryption), so the key-value API reads them the same way. + * A property keeps its declared default until a value is stored. `save()` writes only the + * properties that changed since `load()`. */ abstract class TypedSettings { private ?Settings $handle = null; - /** @var array stored form of each property as loaded */ + /** @var array each property's stored form as loaded */ private array $loaded = []; final public function __construct() {} /** - * Read every property's key through the handle (scoped to the class's store, when it names - * one); a key with no value keeps the property's default. + * Load every property through the handle; a key with no value keeps the property's default. * * @throws TypeMismatch when a stored value cannot be the property's type */ @@ -74,9 +70,8 @@ public static function load(Settings $settings): static } /** - * Register a definition for every property: its key, the caster alias its type implies (or - * `#[Type]`), its declared default and `#[Encrypted]`, in the class's store. A key already - * defined in code or configuration is left as it is. + * Register a definition for every property, leaving keys already defined in code or + * configuration as they are. * * @return list */ @@ -116,7 +111,7 @@ public static function register(DefinitionRegistry $registry): array } /** - * Every mapped property, by name: the public, non-static properties the class declares. + * The public, non-static properties the class declares, by name. * * @return array * @@ -137,8 +132,8 @@ public static function properties(): array } /** - * Write every property that changed since `load()` through the handle it was loaded with; given - * a handle, write every property through that one instead (copying settings to an owner). + * Write the properties changed since `load()`. Given a handle, write every property through it + * instead. */ public function save(?Settings $settings = null): void { diff --git a/src/Verification/ActorTimestampVerifier.php b/src/Verification/ActorTimestampVerifier.php index 23ecbaa..69c9fdc 100644 --- a/src/Verification/ActorTimestampVerifier.php +++ b/src/Verification/ActorTimestampVerifier.php @@ -12,19 +12,18 @@ use Simtabi\Laranail\Settings\Contracts\Verifier; /** - * Trusts {@see Actor::$verifiedAt} when it is no older than `verification.ttl` seconds: for API - * clients and queued work that verified elsewhere (a fresh TOTP, a confirmed password). + * Trusts {@see Actor::$verifiedAt} when it is no older than `verification.ttl` seconds. */ final readonly class ActorTimestampVerifier implements Verifier { - /** @param int $ttl `verification.ttl`: seconds a verification stays fresh */ + /** @param int $ttl seconds a verification stays fresh */ public function __construct( #[Config('laranail.settings.verification.ttl', 900)] private int $ttl, private Clock $clock, ) {} - /** Whether a verification at `$at` is still fresh at `$now`; a timestamp in the future is not. */ + /** Whether a verification at `$at` is still fresh; a future timestamp is not. */ public static function fresh(?CarbonImmutable $at, CarbonImmutable $now, int $ttl): bool { if (! $at instanceof CarbonImmutable || $at->greaterThan($now)) { diff --git a/src/Verification/ClosureVerifier.php b/src/Verification/ClosureVerifier.php index ec65be2..bf61acf 100644 --- a/src/Verification/ClosureVerifier.php +++ b/src/Verification/ClosureVerifier.php @@ -9,9 +9,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Contracts\Verifier; -/** - * A verifier from a closure, registered at runtime with `configuration()->verifyUsing()`. - */ +/** A verifier from a closure, registered with `configuration()->verifyUsing()`. */ final readonly class ClosureVerifier implements Verifier { /** @param Closure(Actor, Subject): bool $callback */ diff --git a/src/Verification/NullVerifier.php b/src/Verification/NullVerifier.php index 3708348..68f9b00 100644 --- a/src/Verification/NullVerifier.php +++ b/src/Verification/NullVerifier.php @@ -8,9 +8,7 @@ use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Contracts\Verifier; -/** - * Treats every actor as verified: step-up verification off (`verification.driver = none`). - */ +/** Treats every actor as verified (`verification.driver = none`). */ final readonly class NullVerifier implements Verifier { public function isVerified(Actor $actor, Subject $subject): bool diff --git a/src/Verification/PasswordConfirmationVerifier.php b/src/Verification/PasswordConfirmationVerifier.php index 3736c7b..2f4bf3b 100644 --- a/src/Verification/PasswordConfirmationVerifier.php +++ b/src/Verification/PasswordConfirmationVerifier.php @@ -13,18 +13,15 @@ use Simtabi\Laranail\Settings\Contracts\Verifier; /** - * Laravel's own password confirmation: the session's `auth.password_confirmed_at` within - * `auth.password_timeout`, the same check as the `password.confirm` middleware. Outside HTTP, - * or when the session has no confirmation, it reads {@see Actor::$verifiedAt} with the same - * timeout. + * Laravel's password confirmation, as the `password.confirm` middleware checks it. Falls back to + * {@see Actor::$verifiedAt} outside HTTP. */ final readonly class PasswordConfirmationVerifier implements Verifier { public const string SESSION_KEY = 'auth.password_confirmed_at'; /** - * @param Closure(): ?Session $session the current session, or null outside HTTP; a closure - * because the request changes under this scoped service + * @param Closure(): ?Session $session the current session, or null outside HTTP */ public function __construct( private Closure $session, diff --git a/tests/Arch/ArchitectureTest.php b/tests/Arch/ArchitectureTest.php index 4aaf4a4..2962bc0 100644 --- a/tests/Arch/ArchitectureTest.php +++ b/tests/Arch/ArchitectureTest.php @@ -14,7 +14,7 @@ use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** - * The rules from the design (§7.10) that a reviewer would otherwise have to remember. + * Structural rules a reviewer would otherwise have to remember. */ arch('every source file declares strict types') ->expect('Simtabi\Laranail\Settings') @@ -46,10 +46,8 @@ ->not->toBeUsed(); /* - * 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. + * Headless: no Blade components, Livewire, Filament or published assets. The one view is the alert + * mail's markdown body, 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') @@ -103,8 +101,7 @@ }); /* - * Every write capability is one final action with a single public entry point, shared by every - * channel (design §16.2, D-17). + * Every write capability is one final action with a single public entry point, shared by every channel. */ arch('actions are final and expose handle()') ->expect('Simtabi\Laranail\Settings\Actions') diff --git a/tests/Arch/LayeringTest.php b/tests/Arch/LayeringTest.php index 66bd23d..c30c4e5 100644 --- a/tests/Arch/LayeringTest.php +++ b/tests/Arch/LayeringTest.php @@ -3,7 +3,7 @@ declare(strict_types=1); /* - * The layering (refactor plan, 2026-11-09): entry points → actions → services → support. + * The layering: entry points → actions → services → support. * * 1. An action exposes handle() and nothing else public. * 2. Actions never touch the database connection or schema builder themselves; repositories diff --git a/tests/Arch/ServicesTest.php b/tests/Arch/ServicesTest.php index 1716aaf..2c693cc 100644 --- a/tests/Arch/ServicesTest.php +++ b/tests/Arch/ServicesTest.php @@ -11,12 +11,9 @@ use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; /* - * The Services namespace (Phase 4 plan §1): stateful collaborators that own I/O or a body of - * rules live under Services\, and nowhere else. Contract implementations (drivers, sinks, - * authorizers, casters, verifiers, resolvers, discriminators) stay beside their kind, so nothing - * under Services\ implements a plug-in contract; and a repository or registry anywhere else is a - * service that was filed in the wrong place. The classes moved in 0.1 have no old name left: - * the aliases were removed before the first tag, so nothing resolves under the old namespaces. + * Stateful collaborators that own I/O or a body of rules live under Services\, and nowhere else. + * Contract implementations stay beside their kind, so nothing under Services\ implements a plug-in + * contract, and no class resolves under the namespaces it moved out of. */ const PLUGIN_CONTRACTS = [ diff --git a/tests/Feature/AccessEventsTest.php b/tests/Feature/AccessEventsTest.php index f326204..e8d1bb3 100644 --- a/tests/Feature/AccessEventsTest.php +++ b/tests/Feature/AccessEventsTest.php @@ -22,7 +22,7 @@ use Simtabi\Laranail\Settings\Exceptions\VerificationRequired; /* - * Phase 4 events: locks, refusals and maintenance. None carries a value. + * Lock, refusal and maintenance events. None carries a value. */ it('announces a lock and an unlock with identifiers and the new version', function (): void { diff --git a/tests/Feature/Database/ApprovalsTest.php b/tests/Feature/Database/ApprovalsTest.php index 5aaa28a..abf91ac 100644 --- a/tests/Feature/Database/ApprovalsTest.php +++ b/tests/Feature/Database/ApprovalsTest.php @@ -28,7 +28,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * §16.7: a write to a setting that needs approval becomes a change request; approvals apply it + * A write to a setting that needs approval becomes a change request; approvals apply it * through the write pipeline against the version it was opened at; the requester cannot approve * their own; rejected, cancelled, stale and expired requests write nothing. */ diff --git a/tests/Feature/Database/AuditQueryTest.php b/tests/Feature/Database/AuditQueryTest.php index 0295b1a..5be30de 100644 --- a/tests/Feature/Database/AuditQueryTest.php +++ b/tests/Feature/Database/AuditQueryTest.php @@ -25,7 +25,7 @@ function auditKeys(array $entries): array return array_map(static fn (AuditEntry $entry): string => $entry->action->value . ':' . ($entry->key ?? '-'), $entries); } -it('queries the audit trail by owner, store, key, action, outcome and time, newest first (§16.8)', function (): void { +it('queries the audit trail by owner, store, key, action, outcome and time, newest first', function (): void { $this->travelTo(now()->subDays(3)); settings()->set('site.name', 'Old'); $this->travelBack(); diff --git a/tests/Feature/Database/BootstrapAndPromotionTest.php b/tests/Feature/Database/BootstrapAndPromotionTest.php index 1b795a8..5bc1435 100644 --- a/tests/Feature/Database/BootstrapAndPromotionTest.php +++ b/tests/Feature/Database/BootstrapAndPromotionTest.php @@ -44,7 +44,7 @@ function bootstrapWithoutDatabase(bool $evidence): void ->and(DB::getQueryLog())->toBe([]); }); -it('raises DriverUnavailable after install when the database is down: no fallback to files (G-36)', function (): void { +it('raises DriverUnavailable after install when the database is down: no fallback to files', function (): void { bootstrapWithoutDatabase(evidence: false); shipDefaults(['maintenance' => false]); app()->forgetInstance(DriverFactory::class); @@ -97,7 +97,7 @@ function bootstrapWithoutDatabase(bool $evidence): void ->and(new InstallationEvidence(false, static fn (): bool => false)->holds())->toBeFalse(); }); -it('promotes only runtime-written values, never shipped defaults (G-28)', function (): void { +it('promotes only runtime-written values, never shipped defaults', function (): void { shipDefaults(['site.name' => 'Shipped', 'site.motto' => 'Shipped motto']); app()->forgetScopedInstances(); settings()->set('site.name', 'Written at install'); diff --git a/tests/Feature/Database/CachingTest.php b/tests/Feature/Database/CachingTest.php index 81bb4e6..c43df89 100644 --- a/tests/Feature/Database/CachingTest.php +++ b/tests/Feature/Database/CachingTest.php @@ -31,12 +31,9 @@ use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; /* - * Phase 3 (design §7.5, §11): the cache holds raw per-scope bags, keyed by connection, database, - * tenant, store and scope, invalidated by generation tokens on every write path. - * - * "A new request" is simulated with forgetScopedInstances(): every scoped service (the registry, - * the resolver, the cache's in-request memory) is rebuilt, while the cache store itself, a - * singleton, keeps its entries, exactly as a second request or a second node would see it. + * The cache holds raw per-scope bags, keyed by connection, database, tenant, store and scope, and + * invalidated by generation tokens on every write path. forgetScopedInstances() stands in for a new + * request: scoped services are rebuilt while the cache store keeps its entries. */ /** Start a new request: scoped services rebuilt, the cache store kept. */ @@ -213,7 +210,7 @@ function defaultTarget(): CacheTarget expect(settings()->get('site.name'))->toBe('Committed'); }); -it('keeps two connections apart even where every other key component is equal (G-37)', function (): void { +it('keeps two connections apart even where every other key component is equal', function (): void { // A second in-memory SQLite connection: same database name (`:memory:`), store, table and // scope as the default one under SQLite, so only the connection name tells them apart. config()->set('database.connections.other', ['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '']); diff --git a/tests/Feature/Database/CommandsTest.php b/tests/Feature/Database/CommandsTest.php index 92a0444..144af2a 100644 --- a/tests/Feature/Database/CommandsTest.php +++ b/tests/Feature/Database/CommandsTest.php @@ -13,10 +13,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; -// Writes into the testbench application shared by every process (config/, database/), so it -// cannot run beside itself in parallel; the parallel mutation run leaves this group out. -// mutation-excluded: Pest's parallel runner honours only the first --exclude-group, so every group -// the mutation job leaves out also carries this one. +// Writes into the testbench application shared by every process, so it cannot run in parallel. +// It also carries `mutation-excluded`, because Pest's parallel runner honours one --exclude-group. pest()->group('shared-app', 'mutation-excluded'); /** @return list */ @@ -47,7 +45,7 @@ function settingsMigrations(): array ->and(app(SchemaShapeRepository::class)->recorded()?->hasStore(new StoreName('settings')))->toBeTrue(); }); -it('refuses to install over a table of the same name that is not its own (D-4)', function (): void { +it('refuses to install over a table of the same name that is not its own', function (): void { config()->set('laranail.settings.stores.settings.layers', ['database', 'runtime', 'shipped']); app()->forgetScopedInstances(); Schema::create('settings', static function (Blueprint $table): void { diff --git a/tests/Feature/Database/DatabaseLayerTest.php b/tests/Feature/Database/DatabaseLayerTest.php index 9495736..006d685 100644 --- a/tests/Feature/Database/DatabaseLayerTest.php +++ b/tests/Feature/Database/DatabaseLayerTest.php @@ -54,7 +54,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver ->and(DB::table('settings')->count())->toBe(1); }); -it('keeps one global row per key, because scope is never null (G-1)', function (): void { +it('keeps one global row per key, because scope is never null', function (): void { settings()->set('site.name', 'One'); settings()->set('site.name', 'Two'); @@ -62,14 +62,14 @@ function databaseDriver(bool $writable = true): DatabaseDriver ->and(DB::table('settings')->where('key', 'site.name')->value('scope'))->toBe('global'); }); -it('identifies a row by scope, key and locale, never by group (G-25)', function (): void { +it('identifies a row by scope, key and locale, never by group', function (): void { $unique = collect(Schema::getIndexes('settings'))->filter(static fn (array $index): bool => $index['unique'] && ! $index['primary']); expect($unique->pluck('columns')->all())->toContain(['scope', 'key', 'locale']) ->and($unique->pluck('columns')->flatten()->all())->not->toContain('group'); }); -it('keeps the identity index inside the utf8mb4 byte budget, tenant column included (G-5)', function (): void { +it('keeps the identity index inside the utf8mb4 byte budget, tenant column included', function (): void { $migration = (string) file_get_contents(dirname(__DIR__, 3) . '/database/migrations/create_laranail_settings_tables.php'); $values = substr($migration, (int) strpos($migration, 'private function createValues'), 4000); preg_match_all("/string\\('(tenant|scope|key|locale)', (\\d+)\\)/", $values, $matches); @@ -80,7 +80,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver ->and(array_sum($lengths) * 4)->toBeLessThan(3072); }); -it('treats keys case-sensitively in the table and lower-cases them in the API (G-38)', function (): void { +it('treats keys case-sensitively in the table and lower-cases them in the API', function (): void { $now = now(); $row = static fn (string $key, string $uid): array => ['scope' => 'global', 'key' => $key, 'locale' => '', 'group' => 'x', 'uid' => $uid, 'value' => '1', 'version' => 1, 'created_at' => $now, 'updated_at' => $now]; @@ -93,7 +93,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver ->and(settings()->get('theme'))->toBe('dark'); }); -it('stores owner rows by scope with the owner id as a string, and reads them back (G-26)', function (): void { +it('stores owner rows by scope with the owner id as a string, and reads them back', function (): void { config()->set('laranail.settings.stores.settings.owners', ['user']); app()->forgetScopedInstances(); @@ -148,7 +148,7 @@ function databaseDriver(bool $writable = true): DatabaseDriver expect(fn () => settings()->set(str_repeat('g', 65) . '.key', 1))->toThrow(InvalidSettingValue::class, 'longer than 64'); }); -it('links a setting to its category in the same store and refuses one from another store (G-33)', function (): void { +it('links a setting to its category in the same store and refuses one from another store', function (): void { $now = now(); $id = DB::table('settings_categories')->insertGetId(['store' => 'settings', 'title' => 'Mail', 'slug' => 'mail', 'created_at' => $now, 'updated_at' => $now]); DB::table('settings_categories')->insert(['store' => 'billing', 'title' => 'Tax', 'slug' => 'tax', 'created_at' => $now, 'updated_at' => $now]); diff --git a/tests/Feature/Database/DebuggingAidsTest.php b/tests/Feature/Database/DebuggingAidsTest.php new file mode 100644 index 0000000..b60175a --- /dev/null +++ b/tests/Feature/Database/DebuggingAidsTest.php @@ -0,0 +1,184 @@ +> */ + public array $contexts = []; + + public function log($level, string|Stringable $message, array $context = []): void + { + $this->contexts[] = $context; + } + }; +} + +beforeEach(function (): void { + useDatabase(['stores.settings.owners' => ['user']]); +}); + +it('shows the resolved value, its layer, type, version, flags and the last audit entry', function (): void { + settings()->set('site.name', 'Acme'); + settings()->set('site.name', 'Acme Ltd'); + + $this->artisan('laranail::settings.show', ['key' => 'site.name']) + ->expectsOutputToContain('"Acme Ltd"') + ->expectsOutputToContain('| Layer | database') + ->expectsOutputToContain('| From scope | global') + ->expectsOutputToContain('| Version | 2') + ->expectsOutputToContain('| Locked | no') + ->expectsOutputToContain('| Encrypted | no') + ->expectsOutputToContain('| Last audit | update allowed by system via php') + ->assertSuccessful(); +}); + +it('shows an owner value and reports a missing one', function (): void { + settings()->for(new OwnerRef('user', 7))->set('theme', 'dark'); + + $this->artisan('laranail::settings.show', ['key' => 'theme', '--owner' => 'user:7']) + ->expectsOutputToContain('"dark"') + ->expectsOutputToContain('| Scope | user:7') + ->assertSuccessful(); + + $this->artisan('laranail::settings.show', ['key' => 'theme']) + ->expectsOutputToContain('(not set)') + ->expectsOutputToContain('| Version | -') + ->assertSuccessful(); + + $this->artisan('laranail::settings.show', ['key' => 'theme', '--owner' => 'nonsense']) + ->expectsOutputToContain('is not alias:id') + ->assertFailed(); +}); + +it('masks a sensitive value unless --reveal is given', function (): void { + app(DefinitionRegistry::class)->define('mail.password')->encrypted()->register(); + $secret = TestCredentials::secret(); + settings()->set('mail.password', $secret); + + $this->artisan('laranail::settings.show', ['key' => 'mail.password']) + ->expectsOutputToContain('[protected]') + ->doesntExpectOutputToContain($secret) + ->expectsOutputToContain('| Encrypted | yes') + ->expectsOutputToContain('| Sensitive | yes') + ->assertSuccessful(); + + $this->artisan('laranail::settings.show', ['key' => 'mail.password', '--reveal' => true]) + ->expectsOutputToContain('"' . $secret . '"') + ->assertSuccessful(); +}); + +it('warns, without failing, about a value whose key is outside its category', function (): void { + settings()->categories()->create(new NewCategory('mail', 'Mail')); + $mail = DB::table('settings_categories')->where('slug', 'mail')->value('id'); + $now = now(); + $row = static fn (string $key, string $uid): array => ['scope' => 'global', 'key' => $key, 'locale' => '', 'group' => 'x', 'uid' => $uid, 'value' => '1', 'version' => 1, 'category_id' => $mail, 'category_store' => 'settings', 'created_at' => $now, 'updated_at' => $now]; + + DB::table('settings')->insert($row('mail.host', str_repeat('A', 26))); + + $this->artisan('laranail::settings.doctor') + ->expectsOutputToContain("Every categorised key starts with its category's slug.") + ->assertSuccessful(); + + DB::table('settings')->insert($row('site.name', str_repeat('B', 26))); + + $this->artisan('laranail::settings.doctor') + ->expectsOutputToContain("1 key(s) do not start with their category's slug: site.name (mail)") + ->assertSuccessful(); +}); + +it('warns, without failing, about a definition whose key is outside its category', function (): void { + app(DefinitionRegistry::class)->define('mail.host')->inCategory('mail')->register(); + + $this->artisan('laranail::settings.doctor') + ->expectsOutputToContain("Every categorised definition starts with its category's slug.") + ->assertSuccessful(); + + app(DefinitionRegistry::class)->define('site.name')->inCategory('mail')->register(); + + $this->artisan('laranail::settings.doctor') + ->expectsOutputToContain("1 definition(s) do not start with their category's slug: settings:site.name (mail)") + ->assertSuccessful(); +}); + +it('puts store, key, scope, actor and channel first in every log context', function (): void { + $sink = contextLog(); + $logger = new OperationalLogger($sink, 'debug'); + + $logger->info('plain', ['extra' => 1]); + $logger->info('built', LogContext::of('settings', 'site.name', 'global', Actor::system('nightly', Channel::Console), extra: ['extra' => 2])); + + expect($sink->contexts[0])->toBe(['store' => null, 'key' => null, 'scope' => null, 'actor' => null, 'channel' => null, 'extra' => 1]) + ->and(array_keys($sink->contexts[1]))->toBe(['store', 'key', 'scope', 'actor', 'channel', 'extra']) + ->and($sink->contexts[1]['channel'])->toBe('console') + ->and($sink->contexts[1]['actor'])->toBe(['type' => 'system', 'alias' => null, 'id' => null, 'channel' => 'console']); +}); + +it('logs an audit entry with the standard context', function (): void { + $sink = contextLog(); + new LogAuditSink(new OperationalLogger($sink, 'debug'))->record(new AuditEntry( + '01JAAAAAAAAAAAAAAAAAAAAAAA', + now()->toImmutable(), + AuditAction::Update, + AuditOutcome::Allowed, + 'settings', + 'user:7', + 'theme', + '', + null, + 2, + ActorType::User, + 'user', + '7', + Channel::Rest, + null, + null, + null, + null, + )); + + expect(array_slice($sink->contexts[0], 0, 5))->toBe([ + 'store' => 'settings', + 'key' => 'theme', + 'scope' => 'user:7', + 'actor' => ['type' => 'user', 'alias' => 'user', 'id' => '7'], + 'channel' => 'rest', + ])->and($sink->contexts[0]['action'])->toBe('update'); +}); + +it('logs a refusal with the standard context', function (): void { + $sink = contextLog(); + config()->set('laranail.settings.authorization.driver', 'permissions'); + app()->forgetScopedInstances(); + settings()->configuration()->logTo($sink); + + try { + settings()->as(user(3))->set('site.name', 'Nope'); + } catch (Throwable) { + } + + $refusal = array_values(array_filter($sink->contexts, static fn (array $context): bool => array_key_exists('reason', $context)))[0] ?? []; + + expect(array_slice($refusal, 0, 3))->toBe(['store' => 'settings', 'key' => 'site.name', 'scope' => 'global']) + ->and($refusal['actor']['id'] ?? null)->toBe('3') + ->and($refusal['channel'])->toBe('php'); +}); diff --git a/tests/Feature/Database/DedicatedStoreTest.php b/tests/Feature/Database/DedicatedStoreTest.php index aaec2a6..d92d183 100644 --- a/tests/Feature/Database/DedicatedStoreTest.php +++ b/tests/Feature/Database/DedicatedStoreTest.php @@ -24,7 +24,7 @@ function useDedicatedStore(array $extra = []): void DB::table('users')->insert([['id' => 1, 'name' => 'Ada'], ['id' => 2, 'name' => 'Grace']]); } -it('replaces settable_* with a non-null owner_id foreign key (D-3)', function (): void { +it('replaces settable_* with a non-null owner_id foreign key', function (): void { useDedicatedStore(); settings()->for(new OwnerRef('user', 1))->set('theme', 'dark'); @@ -37,14 +37,14 @@ function useDedicatedStore(array $extra = []): void ->and(collect(Schema::getForeignKeys('user_settings'))->pluck('foreign_table')->all())->toContain('users'); }); -it('holds owner rows only: a global write is refused and names the fallback store (D-3)', function (): void { +it('holds owner rows only: a global write is refused and names the fallback store', function (): void { useDedicatedStore(); expect(fn () => settings()->store('user_settings')->set('theme', 'dark'))->toThrow(OwnerNotAllowed::class, 'store [settings]') ->and(DB::table('user_settings')->count())->toBe(0); }); -it('reads its global value from the fallback store when owners inherit (§7.2)', function (): void { +it('reads its global value from the fallback store when owners inherit', function (): void { useDedicatedStore(['inherits' => true]); settings()->set('theme', 'light'); diff --git a/tests/Feature/Database/DefinitionsTableTest.php b/tests/Feature/Database/DefinitionsTableTest.php index f665805..b6927b6 100644 --- a/tests/Feature/Database/DefinitionsTableTest.php +++ b/tests/Feature/Database/DefinitionsTableTest.php @@ -30,7 +30,7 @@ function runtimeDefinition(string $key, array $columns = []): void ]); } -it('syncs code and config definitions in as system rows and removes stale ones (D-6)', function (): void { +it('syncs code and config definitions in as system rows and removes stale ones', function (): void { config()->set('laranail.settings.definitions', ['site.name' => ['type' => 'string', 'default' => 'Acme', 'label' => 'Site name']] + config('laranail.settings.definitions')); useDatabase(['definitions.table' => true]); settings()->categories()->create(new NewCategory('mail', 'Mail')); diff --git a/tests/Feature/Database/GovernanceEventsTest.php b/tests/Feature/Database/GovernanceEventsTest.php index c4b2770..edb102b 100644 --- a/tests/Feature/Database/GovernanceEventsTest.php +++ b/tests/Feature/Database/GovernanceEventsTest.php @@ -14,7 +14,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * The events Phase 4 added for maintenance and categories: dispatched once the change is made, + * Maintenance and category events: dispatched once the change is made, * carrying counts and identifiers only. */ diff --git a/tests/Feature/Database/HistoryTest.php b/tests/Feature/Database/HistoryTest.php index 6c4136f..758598c 100644 --- a/tests/Feature/Database/HistoryTest.php +++ b/tests/Feature/Database/HistoryTest.php @@ -29,7 +29,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * §4.3: every set, forget, lock, unlock and rollback appends the value before and after, as + * Every set, forget, lock, unlock and rollback appends the value before and after, as * stored, in the same transaction as the change; history is queried by (store, scope, key, * locale); a rollback is a write; a diff decrypts only for an actor allowed to see the value. */ diff --git a/tests/Feature/Database/MaintenanceTest.php b/tests/Feature/Database/MaintenanceTest.php index 1216d20..f2bc4b4 100644 --- a/tests/Feature/Database/MaintenanceTest.php +++ b/tests/Feature/Database/MaintenanceTest.php @@ -17,7 +17,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * §6 and G-30: reencrypt reads every secret with the current or a previous key and writes it + * Reencrypt reads every secret with the current or a previous key and writes it * under the current one (values, history, change requests); rescope renames an owner alias * everywhere it is stored; doctor reports what neither has fixed yet. */ @@ -103,7 +103,7 @@ function rotateKey(bool $keepPrevious): void ->and(DB::table('settings_history')->where('scope', 'member:4')->count())->toBe(1) ->and(DB::table('settings_change_requests')->where('scope', 'member:4')->count())->toBe(1); - // A class name from before the alias allow-list (G-6) is renamed the same way. + // A class name stored before the alias allow-list is renamed the same way. app(RescopeOwners::class)->handle('App\\Models\\Legacy', 'member'); Artisan::call('laranail::settings.doctor', ['--json' => true]); diff --git a/tests/Feature/Database/ModelsAndFactoriesTest.php b/tests/Feature/Database/ModelsAndFactoriesTest.php index 10cf284..2ab467c 100644 --- a/tests/Feature/Database/ModelsAndFactoriesTest.php +++ b/tests/Feature/Database/ModelsAndFactoriesTest.php @@ -18,7 +18,7 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; /* - * The Eloquent models and their factories (Amendment B): for tests, seeding and admin screens. + * The Eloquent models and their factories: for tests, seeding and admin screens. * The engine never reads through them, but what they write must be what the engine reads. */ diff --git a/tests/Feature/Database/OwnersTest.php b/tests/Feature/Database/OwnersTest.php index 18ae21e..3b58785 100644 --- a/tests/Feature/Database/OwnersTest.php +++ b/tests/Feature/Database/OwnersTest.php @@ -50,13 +50,13 @@ ->and($owner->settingsOwner()->alias)->toBe('owner'); }); -it('refuses a model without a morph map entry, whose alias would be a class name (G-6)', function (): void { +it('refuses a model without a morph map entry, whose alias would be a class name', function (): void { Relation::morphMap([], false); expect(fn () => SettingsOwner::query()->create()->settingsOwner())->toThrow(InvalidIdentifier::class); }); -it('deletes an owner\'s settings with the owner, and keeps them through a soft delete (G-7)', function (): void { +it('deletes an owner\'s settings with the owner, and keeps them through a soft delete', function (): void { $owner = SettingsOwner::query()->create(); $owner->settings()->set('ui.theme', 'dark'); $soft = SoftDeletingOwner::query()->create(); @@ -79,7 +79,7 @@ expect($owner->delete())->toBeTrue(); }); -it('eager-loads a page of owners in one query per store, then reads them with none (G-9)', function (): void { +it('eager-loads a page of owners in one query per store, then reads them with none', function (): void { config()->set('laranail.settings.stores.settings.inherits', true); app()->forgetScopedInstances(); $owners = collect(range(1, 5))->map(static fn (int $i): SettingsOwner => SettingsOwner::query()->create(['team_id' => 7])); diff --git a/tests/Feature/Database/PersistedConfigurationTest.php b/tests/Feature/Database/PersistedConfigurationTest.php index b6e43cc..5feccb5 100644 --- a/tests/Feature/Database/PersistedConfigurationTest.php +++ b/tests/Feature/Database/PersistedConfigurationTest.php @@ -18,7 +18,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * §16.11: stores, layers and definitions saved through the API, validated like configuration, + * Stores, layers and definitions saved through the API, validated like configuration, * gated and audited, merged in configuration.sources order, read lazily, and an invalid row is * skipped and reported rather than breaking the application. */ diff --git a/tests/Feature/Database/RestApiTest.php b/tests/Feature/Database/RestApiTest.php index 17b7ff1..07df693 100644 --- a/tests/Feature/Database/RestApiTest.php +++ b/tests/Feature/Database/RestApiTest.php @@ -20,7 +20,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * §16.10: the REST API runs the actions the PHP API runs, answers problem details, ETags and + * 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 * matches its shape (tests/Support/ApiSchemas.php). */ diff --git a/tests/Feature/Database/SchemaMatrixTest.php b/tests/Feature/Database/SchemaMatrixTest.php index 7885c20..a026c60 100644 --- a/tests/Feature/Database/SchemaMatrixTest.php +++ b/tests/Feature/Database/SchemaMatrixTest.php @@ -16,7 +16,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * §13: the schema switches, kept tested. Every pair of switch values meets in at least one shape + * The schema switches. Every pair of switch values meets in at least one shape * (pairwise), and each shape runs the same scenario: migrate, write global and owner values, * categories, a forget followed by a set, locks, the definitions table, then `doctor` against the * recorded schema. Runs on SQLite with the rest of the suite and, being in the `database` group, @@ -66,10 +66,8 @@ function switchShapes(): array } } - // 141 pairs among the eight Phase 2b switches, plus tenancy's 2 values × the other 18 - // values = 177, plus history's 2 values × the other 20 values = 217 (Phase 4), plus the - // change requests table's 2 values × the other 22 values = 261 (Phase 4b); the full product - // doubles again from 2,304 to 4,608, and the pairwise set stays at 11 shapes. + // 141 pairs among the first eight switches, plus 2 × 18 for tenancy, 2 × 20 for history and + // 2 × 22 for the change requests table = 261. The full product is 4,608 shapes; pairwise is 11. expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 4608 : 11) ->and(count($all))->toBe(261) ->and(array_diff_key($all, $covered))->toBe([]); @@ -133,7 +131,7 @@ function switchShapes(): array expect(app(SyncDefinitions::class)->handle()['synced'])->toBe(1); } - // History (§4.3): the forget left a tombstone, so the row created again continued the trail. + // History: the forget left a tombstone, so the row created again continued the trail. $trail = $shape['history'] ? settings()->for($user)->history()->key('theme')->get() : []; $exit = Artisan::call('laranail::settings.doctor', ['--json' => true]); diff --git a/tests/Feature/Database/SchemaShapeTest.php b/tests/Feature/Database/SchemaShapeTest.php index 74b1004..d7151a2 100644 --- a/tests/Feature/Database/SchemaShapeTest.php +++ b/tests/Feature/Database/SchemaShapeTest.php @@ -13,10 +13,8 @@ use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; -// Writes into the testbench application shared by every process (config/, database/), so it -// cannot run beside itself in parallel; the parallel mutation run leaves this group out. -// mutation-excluded: Pest's parallel runner honours only the first --exclude-group, so every group -// the mutation job leaves out also carries this one. +// Writes into the testbench application shared by every process, so it cannot run in parallel. +// It also carries `mutation-excluded`, because Pest's parallel runner honours one --exclude-group. pest()->group('shared-app', 'mutation-excluded'); function shapes(): SchemaShapeRepository @@ -45,7 +43,7 @@ function doctorReport(): string ->and(shapes()->current()->store(new StoreName('settings'))->softDeletes)->toBeTrue(); }); -it('makes the runtime read the recorded shape, not config changed after migrating (§4.0)', function (): void { +it('makes the runtime read the recorded shape, not config changed after migrating', function (): void { useDatabase(); shapes()->record(); diff --git a/tests/Feature/Database/SchemaSwitchesTest.php b/tests/Feature/Database/SchemaSwitchesTest.php index 6feedcb..4de2a18 100644 --- a/tests/Feature/Database/SchemaSwitchesTest.php +++ b/tests/Feature/Database/SchemaSwitchesTest.php @@ -19,7 +19,7 @@ function valueColumns(string $table = 'settings'): array return Schema::getColumnListing($table); } -it('gives every row a shared slug and its own uid by default (D-1 slug_uid)', function (): void { +it('gives every row a shared slug and its own uid by default', function (): void { useDatabase(['stores.settings.owners' => ['user']]); settings()->set('mail.from_address', 'a@acme.test'); @@ -31,7 +31,7 @@ function valueColumns(string $table = 'settings'): array ->and($rows->pluck('uid')->unique())->toHaveCount(2); }); -it('gives each row a unique sha1 slug and no uid in slug_per_row mode (D-1)', function (): void { +it('gives each row a unique sha1 slug and no uid in slug_per_row mode', function (): void { useDatabase(['identity.mode' => 'slug_per_row', 'stores.settings.owners' => ['user']]); settings()->set('mail.from_address', 'a@acme.test'); @@ -48,7 +48,7 @@ function valueColumns(string $table = 'settings'): array expect($unique)->toHaveCount(1); }); -it('keeps only a uid in uid_only mode (D-1)', function (): void { +it('keeps only a uid in uid_only mode', function (): void { useDatabase(['identity.mode' => 'uid_only']); settings()->set('site.name', 'Acme'); @@ -58,7 +58,7 @@ function valueColumns(string $table = 'settings'): array ->and(settings()->get('site.name'))->toBe('Acme'); }); -it('keys every package table by uuid or ulid, with matching category keys (D-5)', function (string $type, int $length): void { +it('keys every package table by uuid or ulid, with matching category keys', function (string $type, int $length): void { useDatabase(['ids.type' => $type, 'definitions.table' => true]); $category = settings()->categories()->create(new NewCategory('mail', 'Mail')); @@ -76,7 +76,7 @@ function valueColumns(string $table = 'settings'): array 'ulid' => ['ulid', 26], ]); -it('follows laranail.db-tools.id_type when ids.type is not set (D-5)', function (): void { +it('follows laranail.db-tools.id_type when ids.type is not set', function (): void { config()->set('laranail.db-tools.id_type', 'ULID'); useDatabase(); @@ -92,7 +92,7 @@ function valueColumns(string $table = 'settings'): array expect(fn () => app(SchemaShapeRepository::class)->configured())->toThrow(InvalidConfiguration::class, 'laranail.settings.ids.type'); }); -it('types settable_id like the owners\' keys when ids.owner_key is typed (D-5)', function (): void { +it('types settable_id like the owners\' keys when ids.owner_key is typed', function (): void { useDatabase(['ids.owner_key' => 'typed', 'stores.settings.owners' => ['user']]); settings()->for(new OwnerRef('user', 42))->set('theme', 'dark'); @@ -102,7 +102,7 @@ function valueColumns(string $table = 'settings'): array ->and(fn () => settings()->for(new OwnerRef('user', 'abc'))->set('theme', 'light'))->toThrow(OwnerNotAllowed::class, 'bigint'); }); -it('stores titles as per-locale JSON in json translations mode (D-8)', function (): void { +it('stores titles as per-locale JSON in json translations mode', function (): void { useDatabase(['translations.mode' => 'json']); $categories = settings()->categories(); @@ -129,7 +129,7 @@ function valueColumns(string $table = 'settings'): array ->and(fn (): NewCategory => new NewCategory('x', 'X', translations: ['fr' => ' ']))->toThrow(InvalidIdentifier::class); }); -it('prefixes every table and honours each override, including the foreign-table check (D-4)', function (): void { +it('prefixes every table and honours each override, including the foreign-table check', function (): void { useDatabase([ 'tables.prefix' => 'app_', 'tables.categories' => 'setting_groups', @@ -160,7 +160,7 @@ function valueColumns(string $table = 'settings'): array expect(app(FindForeignTables::class)->handle())->toBe([DB::getDefaultConnection() . '.app_setting_log']); }); -it('runs the definitions migration as a no-op while the table is off (D-6)', function (): void { +it('runs the definitions migration as a no-op while the table is off', function (): void { useDatabase(); expect(Schema::hasTable('settings_definitions'))->toBeFalse(); diff --git a/tests/Feature/Database/SoftDeletesTest.php b/tests/Feature/Database/SoftDeletesTest.php index e5379c2..dc8870e 100644 --- a/tests/Feature/Database/SoftDeletesTest.php +++ b/tests/Feature/Database/SoftDeletesTest.php @@ -14,7 +14,7 @@ useDatabase(['stores.settings.soft_deletes' => true, 'stores.settings.owners' => ['user'], 'categories.soft_deletes' => true]); }); -it('trashes a forgotten row instead of deleting it, and reads past it (D-9)', function (): void { +it('trashes a forgotten row instead of deleting it, and reads past it', function (): void { settings()->set('site.name', 'Acme'); settings()->forget('site.name'); @@ -23,7 +23,7 @@ ->and(DB::table('settings')->value('deleted_at'))->not->toBeNull(); }); -it('restores a trashed row on the next set, continuing its version, never as a conflict (D-9)', function (): void { +it('restores a trashed row on the next set, continuing its version, never as a conflict', function (): void { $audit = auditInMemory(); settings()->set('site.name', 'One'); settings()->set('site.name', 'Two'); diff --git a/tests/Feature/Database/TenancyTest.php b/tests/Feature/Database/TenancyTest.php index 9d87473..34f0aa5 100644 --- a/tests/Feature/Database/TenancyTest.php +++ b/tests/Feature/Database/TenancyTest.php @@ -15,7 +15,7 @@ use Simtabi\Laranail\Settings\Services\Database\SchemaShapeRepository; /* - * Amendment B: column-mode tenancy. One database; every values, categories and audit row carries + * Column-mode tenancy. One database; every values, categories and audit row carries * the current tenant and every query is limited to it, so two tenants writing the same key never * see each other's value, and '' holds the central rows. */ diff --git a/tests/Feature/Database/TransferTest.php b/tests/Feature/Database/TransferTest.php index eb33fe1..936c309 100644 --- a/tests/Feature/Database/TransferTest.php +++ b/tests/Feature/Database/TransferTest.php @@ -25,7 +25,7 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * G-10, G-42, G-43: exports name categories by slug and settings by scope, key and locale; secrets + * Exports name categories by slug and settings by scope, key and locale; secrets * are redacted unless asked for; import is a dry run until applied, goes through the write * pipeline, and creates categories first; importers read other packages without needing them. */ @@ -95,7 +95,7 @@ function seedStore(): string expect($report->applied)->toBeTrue() ->and(settings()->get('mail.port'))->toBe(587) ->and(settings()->for(new OwnerRef('user', 7))->get('theme'))->toBe('dark') - // Untrusted: the lock in the file is not applied (G-10). + // Untrusted: the lock in the file is not applied. ->and((bool) DB::table('settings')->where('scope', 'user:7')->value('is_locked'))->toBeFalse() ->and(settings()->categories()->get('smtp')->parent?->value)->toBe('mail') ->and(settings()->compare($document)->isEmpty())->toBeFalse() diff --git a/tests/Feature/Database/TypedSettingsTest.php b/tests/Feature/Database/TypedSettingsTest.php index 1ad565d..a438577 100644 --- a/tests/Feature/Database/TypedSettingsTest.php +++ b/tests/Feature/Database/TypedSettingsTest.php @@ -21,9 +21,9 @@ use Simtabi\Laranail\Settings\Services\Definitions\DefinitionRegistry; /* - * Phase 5: typed settings classes over the key-value engine. The typed API and the key-value + * Typed settings classes over the key-value engine. The typed API and the key-value * API read and write the same rows (parity), saves go through the write actions (actor, audit, - * history), and settings migrations rename, move, add and delete keys (G-17). + * history), and settings migrations rename, move, add and delete keys. */ beforeEach(function (): void { diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index d588a3f..0954963 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -4,10 +4,8 @@ use Illuminate\Support\Facades\File; -// Writes into the testbench application shared by every process (config/, database/), so it -// cannot run beside itself in parallel; the parallel mutation run leaves this group out. -// mutation-excluded: Pest's parallel runner honours only the first --exclude-group, so every group -// the mutation job leaves out also carries this one. +// Writes into the testbench application shared by every process, so it cannot run in parallel. +// It also carries `mutation-excluded`, because Pest's parallel runner honours one --exclude-group. pest()->group('shared-app', 'mutation-excluded'); beforeEach(function (): void { diff --git a/tests/Feature/ProviderLayoutTest.php b/tests/Feature/ProviderLayoutTest.php index d19210b..9d0ea30 100644 --- a/tests/Feature/ProviderLayoutTest.php +++ b/tests/Feature/ProviderLayoutTest.php @@ -4,10 +4,7 @@ /** * Every service provider lives in a Providers/ directory, with a namespace ending in \Providers. - * - * This is a layout rule, so it is asserted against the filesystem rather than the container: a - * provider that drifts back to the root of src/ still boots perfectly well, which is exactly why - * nothing else would notice. Copy this file into any package in the family. + * Checked on the filesystem, because a provider at the root of src/ still boots. * * @return list */ @@ -49,8 +46,7 @@ function providerFiles(string $src): array $checked = 0; foreach (providerFiles(__DIR__ . '/../../src') as $file) { - // The directory and the namespace are separate facts -- PSR-4 makes them agree only if the - // file declares the namespace its path implies, and a bad move can leave them disagreeing. + // The directory and the namespace are separate facts; a bad move can leave them disagreeing. $source = file_get_contents($file->getPathname()); preg_match('/^namespace\s+([^;]+);/m', $source === false ? '' : $source, $matches); diff --git a/tests/Feature/RestApiRoutesTest.php b/tests/Feature/RestApiRoutesTest.php index ffdf52f..397cb04 100644 --- a/tests/Feature/RestApiRoutesTest.php +++ b/tests/Feature/RestApiRoutesTest.php @@ -6,7 +6,7 @@ use Illuminate\Routing\Router; /* - * §16.2 (D-17): every REST route runs the action the PHP API runs. Read from the live router: + * Every REST route runs the action the PHP API runs. Read from the live router: * each route names a controller method, each controller method is routed, and each delegates * to an Actions\* class it was handed as a parameter. */ diff --git a/tests/Feature/SettingsCacheTest.php b/tests/Feature/SettingsCacheTest.php index 0d96543..1618dd2 100644 --- a/tests/Feature/SettingsCacheTest.php +++ b/tests/Feature/SettingsCacheTest.php @@ -22,7 +22,7 @@ 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 + * The cache service on its own, over an in-memory cache store: the database side is * a closure that counts how often, and for which scopes, it is asked. */ @@ -127,7 +127,7 @@ public function forever($key, $value): bool expect($calls)->toBe([['global', 'user:1'], ['user:1'], ['global', 'user:1'], ['global'], ['global']]); }); -it('keys every component apart, including a split that a plain join would collide on (R-63, G-37)', function (): void { +it('keys every component apart, including a split that a plain join would collide on', function (): void { $cache = new SettingsCache(new Repository(new ArrayStore)); $keys = [ $cache->bagKey(cacheTarget('a', 'b:c'), Scope::global()), @@ -315,5 +315,5 @@ public function log($level, Stringable|string $message, array $context = []): vo ->and($failure)->toHaveCount(1) ->and($failure[0][0])->toBe('warning') ->and($failure[0][1])->toContain('(read): cache down') - ->and($failure[0][2])->toBe(['operation' => 'read', 'exception' => RuntimeException::class]); + ->and($failure[0][2])->toBe(['store' => null, 'key' => null, 'scope' => null, 'actor' => null, 'channel' => null, 'operation' => 'read', 'exception' => RuntimeException::class]); });