Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 66 additions & 14 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Consumer conveniences on the `Settings` contract, each a thin delegation onto the existing read
and write paths: `missing()`, `many()` (keys or `key => default` pairs), `setMany()` and
`forgetMany()` (one write each, not atomic), `remember()` (read-through: writes a computed value
once through `set()`), `all(?string $prefix)` (every visible value of the handle's scope, the PHP
form of the REST listing) and `definitions()` (the store's definitions, the PHP form of
`GET stores/{store}/definitions`). `SettingsFake` implements all of them and records the writes.
The facade's docblock now lists every contract method.
- A namespaced `Simtabi\Laranail\Settings\settings()` helper (`use function …\settings;`): the
handle with no argument, else `get($key, $default)`. Deliberately not a global function.
- `Services\Resolution\ScopeKeys`: the key walk a listing uses, shared by `all()` and the REST
listing (moved verbatim out of `Actions\Reads\ReadSettings`).
- Documentation: a complete PHP API reference (every contract method with signature, example,
exceptions and events, plus the facade, the helper, `HasSettings` and typed settings), a per-route
REST API reference with every problem type, an exceptions reference, the six approval events and
a call-to-event table in the events reference, and recipes for an admin UI on the REST API, SPA and
mobile clients, a per-user preferences screen, multi-tenancy, auditing a change, moving settings
between environments and typed settings. Tests fail when a contract method, route, event,
exception, command or config key (and its default) goes undocumented.

- Approvals (design §16.7, Phase 4b): a write (`set`, `forget`, `lock`, `unlock`) to a setting
whose definition is `requiresApproval()`, or whose key matches the store's new
`approvals.keys` globs, opens a change request instead of writing. A
Expand Down Expand Up @@ -179,6 +198,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- The package is wired the way Laravel wires an application (conventions review, 2026-11-10).
`routes/api.php` declares every REST route by hand in named, nested groups, each `http.routes`
switch an `if` around its group; the service provider loads it once, under `http.prefix`/v1 and
the `laranail-settings.api.` name prefix. URIs, names, methods and middleware are unchanged (39
routes). `routes/web.php` is no longer loaded while it holds no routes.
- `http.prefix` reads `LARANAIL_SETTINGS_HTTP_PREFIX` (default still `api/settings`); slashes are
trimmed and an empty prefix mounts the API at `/v1`. Change it when the application already has
routes under `/api/settings`: Laravel keeps the last route registered for a method and URI.
- Most classes are autowired, with their lifetime as `#[Scoped]` / `#[Singleton]` on the class and
their configuration as `#[Config]` on the parameter; the service provider binds only what
configuration chooses or validates (1,180 lines to about 700). Closure collaborators became
injected ones: one `Support\Clock` (Laravel's `Date` seam) for every timestamp, the operational
log for write retries and cache failures, the event dispatcher for skipped layers, and a
`Services\Definitions\Definitions` service for "which definition applies", which replaced a
provider closure and two copies of the same rule.
- `SettingsManager` takes every collaborator, required, and its fluent methods return a copy; the
"built without X" `LogicException`s are gone. `CategoryManager`, `Approvals` and
`PersistedConfigurationEditor` take their actions and are narrowed with `in($store, $actor)`.
- REST controllers take their actions per method, return JSON resources and resource collections
(bodies unchanged), and validate each write with its own form request.
- Each exception names its HTTP status and problem type (`STATUS`, `TYPE`); `Problems` renders them
and reads its titles through the translator. Messages are read through Laravel's translator
(`laranail/settings::settings.*`), `__()` and `trans_choice()` in the commands.
- Typed settings classes listed in `typed.classes` are bound when the application boots; the global
`beforeResolving` hook is gone, so a class not listed resolves unloaded (build it with
`::load()`).
- The REST rate limiter is registered through package-tools' `registerRateLimiter()` and reads
`http.rate_limit` per request.
- Configuration is read with the repository's typed getters, which throw on a value of the wrong
type where the old reader fell back to the default (a digit string for a number is now an error).

- A write to a setting that needs approval opens a change request where the store can hold one;
`ApprovalUnavailable` is now raised only where it cannot (no active database layer, or no
change requests table). `SetSetting`, `ForgetSetting`, `LockSetting` and `UnlockSetting` return
Expand Down Expand Up @@ -226,21 +276,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `Contracts\Settings` gains `clearCache()` and `warmCache()`; `Actions\StoreActions` gains the
optional `warmCache` and `clearCache` actions.

### Deprecated
### Removed

- Removed with the owner's approval (2026-11-10), before the first tag: `Http\ApiRoutes`,
`Enums\Capability`, `Http\OpenApi\OpenApiDocument` and the `laranail::settings.openapi`
command; `Http\Middleware\FreshControllers`; the seven action bundles (`SettingActions`,
`StoreActions`, `HistoryActions`, `ApprovalActions`, `TransferActions`, `ConfigurationActions`,
`CategoryActions`); `Http\Requests\BodyRequest`, `Data\Http\BodyInput` and
`Http\Support\ListResponse`; the static `fields()` of the five resources; `Support\Messages`
and `Support\ConfigValues`; and the single-implementation contracts `ReadinessProbe` (with
`Database\SchemaReadinessProbe`), `ValueValidator`, `ValueEncrypter`, `BootstrapEvidence` and
`OwnerResolver`. Inject the action, the concrete class or db-tools' `SchemaReadinessInterface`
instead.

- The old names of the 19 classes moved into `Services\` (listed under Changed):
`Database\AuditRepository`, `Database\CategoryRepository`, `Database\DefinitionsRepository`,
`Database\SchemaInspector`, `Database\SchemaShapeRepository`, `Stores\SettingWriter`,
`Stores\StoreRegistry`, `Resolution\Resolver`, `Resolution\PreloadedRecords`,
`Authorization\AccessGuard`, `Audit\Auditor`, `Configuration\RuntimeConfiguration`,
`Definitions\DefinitionRegistry`, `Definitions\DatabaseDefinitions`,
`Tenancy\TenantDiscriminators`, `Casting\CasterRegistry`, `Support\ValuePipeline`,
`Drivers\DriverFactory` and `Caching\SettingsCache`. Each still resolves to the moved class
through `class_alias` in `src/deprecated-aliases.php` (Composer `autoload.files`), so imports,
type declarations, container bindings and `instanceof` keep working; removed in 1.0.
- `PruneOrphans::find()`: use `FindOrphans::handle()`. It forwards; removed in 1.0.
- `DatabaseDefinitions::localised()`: use `Support\Translations::nullableText()`. It forwards;
removed in 1.0.
- The old names of the 19 classes moved into `Services\` (listed under Changed), the
`src/deprecated-aliases.php` file that aliased them, `PruneOrphans::find()` (use
`FindOrphans::handle()`) and `DatabaseDefinitions::localised()` (use
`Support\Translations::nullableText()`). None was ever in a tagged release.

- The four migration stubs are replaced by one migration,
`database/migrations/create_laranail_settings_tables.php`, which creates categories, the
Expand Down
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ use Simtabi\Laranail\Settings\Facades\Settings;
Settings::set('site.name', 'Acme');
Settings::get('site.name'); // 'Acme'
Settings::get('site.tagline', 'Welcome'); // the default when nothing is stored
Settings::many(['site.name', 'site.tagline' => 'Welcome']);
Settings::all('mail'); // every visible key under mail.
```

```php
Expand Down Expand Up @@ -88,12 +90,13 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s

### Reference

- [Settings API](docs/tools/settings-api.md) — handles, reads, writes and the exceptions they raise.
- [Settings API](docs/tools/settings-api.md) — every method of the handle, the facade, the `settings()` helper, `HasSettings` and typed settings, with examples, exceptions and events.
- [Exceptions](docs/tools/exceptions.md) — every exception, when it is raised and how the REST API answers it.
- [Definitions](docs/tools/definitions.md) — types, defaults, rules, encryption, locks and precedence.
- [Drivers and layers](docs/tools/drivers.md) — the built-in drivers and custom ones.
- [Database](docs/tools/database.md) — the tables, version-checked writes, eager loading and `HasSettings`.
- [Categories](docs/tools/categories.md) — nested, per-store categories and the rules that guard them.
- [Commands](docs/tools/commands.md) — install, make-store, promote, doctor, warm, clear-cache, history, export, import, diff, reencrypt, rescope, openapi and the prune commands.
- [Commands](docs/tools/commands.md) — install, make-store, promote, doctor, warm, clear-cache, history, export, import, diff, reencrypt, rescope and the prune commands.
- [Owners and inheritance](docs/tools/owners.md) — owner references, store routing and the cascade.
- [Access control](docs/tools/access-control.md) — actors, abilities, authorizers, guarded locks, sensitive reads and step-up verification.
- [Audit and logging](docs/tools/audit-and-logging.md) — the audit trail, its sinks and the operational log.
Expand All @@ -111,7 +114,8 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [Importers](docs/tools/importers.md) — moving in from spatie/laravel-settings, toolkit's JSON store and akaunting/laravel-setting.
- [Re-encryption and rescoping](docs/tools/reencryption.md) — after an `APP_KEY` rotation, and after renaming a morph alias.
- [Persisted configuration](docs/tools/persisted-configuration.md) — stores, layers and definitions kept in the database.
- [REST API](docs/tools/rest-api.md) — the opt-in JSON API: endpoints, ETags, approvals, problem details, idempotency and OpenAPI.
- [REST API](docs/tools/rest-api.md) — the opt-in JSON API: endpoints, ETags, approvals, problem details and idempotency.
- [REST API reference](docs/tools/rest-api-reference.md) — every route: ability, request, response, status codes and problem types.
- [Typed settings](docs/tools/typed-settings.md) — typed classes over the key-value engine, and settings migrations.

### Recipes
Expand All @@ -127,6 +131,13 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [Approve a change](docs/recipes/approving-a-change.md) — require a second person, then review and apply.
- [Call the REST API with Sanctum](docs/recipes/calling-the-rest-api-with-sanctum.md) — a token with an ability ceiling, ETags and idempotency.
- [Migrate from spatie/laravel-settings](docs/recipes/migrating-from-spatie-laravel-settings.md) — import the values and keep typed classes.
- [Build your own admin UI on the REST API](docs/recipes/building-an-admin-ui-on-the-rest-api.md) — forms from definitions, ETag saves, history and activity.
- [Read settings from an SPA or a mobile app](docs/recipes/consuming-from-an-spa-or-mobile-app.md) — cookies or tokens, ETags and safe retries.
- [Build a per-user preferences screen](docs/recipes/building-a-preferences-screen.md) — defaults, `many()`, `setMany()` and resetting.
- [Set up multi-tenancy](docs/recipes/setting-up-multi-tenancy.md) — a tenant column or a database per tenant.
- [Audit a change](docs/recipes/auditing-a-change.md) — who, when, why, and the value before.
- [Move settings between environments](docs/recipes/moving-settings-between-environments.md) — export, diff and a dry-run import.
- [Use typed settings](docs/recipes/using-typed-settings.md) — a typed class over a group of keys.

## Contributing & security

Expand Down
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"Simtabi\\Laranail\\Settings\\Database\\Seeders\\": "database/seeders/"
},
"files": [
"src/deprecated-aliases.php"
"helpers/helpers.php"
]
},
"autoload-dev": {
Expand Down Expand Up @@ -144,3 +144,5 @@
}
]
}


2 changes: 1 addition & 1 deletion config/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@

'http' => [
'enabled' => env('LARANAIL_SETTINGS_HTTP', false),
'prefix' => 'api/settings',
'prefix' => env('LARANAIL_SETTINGS_HTTP_PREFIX', 'api/settings'),
'middleware' => null,
'rate_limit' => 60,
'routes' => [
Expand Down
32 changes: 25 additions & 7 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ How `laranail/settings` is shaped, and why.
| Services (`Services/`) | the database, the files, a body of rules | `Services\Database\AuditRepository`, `Services\Database\HistoryRepository`, `Services\Database\CategoryRepository`, `Services\Stores\SettingWriter`, `Services\Resolution\Resolver`, `Services\Access\AccessGuard`, `Services\Tenancy\TenantDiscriminators`, `Services\Cache\SettingsCache` |
| Contract implementations | one per kind, beside its kind | the drivers, the audit sinks, the authorizers, the casters, the verifiers, the actor resolvers |
| Listeners (`Listeners/`) and notifications | react to events | `SendSettingsAlert`, `LogSettingsEvent`, `Notifications\SettingsAlert` |
| Support (`Support/`) | stateless logic shared by several classes | `AuditedTransaction`, `Translations`, `Json`, `DatabaseValues`, `ConfigValues`, `ValueEncoder`, `BagCodec` |
| Support (`Support/`) | stateless logic shared by several classes | `AuditedTransaction`, `Translations`, `Json`, `DatabaseValues`, `ValueEncoder`, `BagCodec`, `Clock` |

An action never builds a query or reads the schema itself; it asks a repository, so the table,
the tenant filter and the row format live in one place. A change and its audit entry always go
Expand All @@ -48,11 +48,9 @@ entry points.
Two architecture tests keep it so: nothing under `Services\` implements a plug-in contract (a
driver, sink, authorizer, caster, verifier, resolver or discriminator stays beside its kind, where
a reader looking for "the drivers" finds them), and no class named `*Repository` or `*Registry`
lives anywhere else. The 19 classes that moved keep their old names through `class_alias` in
`src/deprecated-aliases.php`, loaded by Composer, until 1.0. The aliases are declared eagerly:
PHP does not autoload a class for a type check, so a lazily declared alias would make
`function f(Stores\SettingWriter $w)` refuse the object it accepted before. A third test asserts the
alias file names exactly the moved classes.
lives anywhere else. The 19 classes that moved there in 0.1 kept no old name: the package had never
been tagged, so the aliases were removed before the first release, and a third test asserts the old
names no longer resolve.

## Why history and audit are separate tables

Expand Down Expand Up @@ -224,12 +222,32 @@ The package ships no views, Blade components, Livewire, Filament or assets. A se

## Why the REST API lives in the package

The API is a channel, not a product: every endpoint runs an action the PHP API already runs (`Enums\Capability::actions()`), with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside, keep its own copy of the capability list, and drift a release behind the engine whenever an action changed; the design moved it in (D-26) so one pull request changes a capability in every channel at once, and an architecture test fails when a route, the capability enum or a controller disagrees with the others. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless.
The API is a channel, not a product: every endpoint runs an action the PHP API already runs, with the same authorizer, verifier, audit, locks and approvals. Shipped as a separate `settings-http` package it would have to reach into those actions from outside and drift a release behind the engine whenever an action changed; the design moved it in (D-26) so one pull request changes a capability in every channel at once. The routes are declared by hand in `routes/api.php`, each controller method takes the action it runs as a parameter, and a test reading the live router fails when a route names no controller method, a controller method is not routed, or one does not delegate to an action. It costs nothing until it is used: no route is registered, no middleware or rate limiter defined, unless `http.enabled` is on, and it adds no dependency (Sanctum stays a suggestion). It returns JSON only, so the package stays headless.

## Why change requests are a table

A write that needs approval has to outlive the request that proposed it: the approver acts later, from another request, maybe another server, and a queue or a cache entry can be evicted before anyone looks. So a proposal is a row, written in the same transaction as its `pending` audit entry, on the store's own connection (one table per connection, like the history), with the proposed value stored exactly as the values table would store it, encrypted for an encrypted definition. Keeping the base version on the row is what makes applying it safe: the approval writes through the version-checked update, so a setting that changed in the meantime is never overwritten and the request becomes `stale`. Requests are keyed by ULID, so the table never depends on `ids.type`, and the table is a schema switch (`approvals.table`) like the history.

## How the container builds it

Most classes are autowired. A class's lifetime is an attribute on the class (`#[Scoped]` for
anything derived from a request, so Octane and queue workers start each request clean;
`#[Singleton]` for stateless helpers), and a configuration value is a `#[Config]` attribute on the
constructor parameter that needs it. The service provider binds only what configuration chooses or
validates: the drivers, sinks, authorizers, verifiers and actor resolvers named in config, the cache
stores, and the stores themselves. A handle (`SettingsManager`) takes every collaborator it calls,
required, and a fluent method returns a copy with a new target, so a handle is never half-built.
Time is read in one place, `Support\Clock`, through Laravel's `Date` seam, so `travelTo()` reaches
every timestamp the package writes.

A few collaborators stay closures on purpose, each because the alternative is worse: the
`DriverFactory` is a singleton (a driver registered with `extend()` must last) and hands database
drivers the scoped readiness, schema and tenant services through closures; the runtime
configuration's change log and the database audit sink reach the logger, the auditor and the store
registry lazily, because those read the runtime configuration themselves; the encrypter is resolved
only when a value is encrypted, so an application without an `APP_KEY` still boots; and the session
and request are read per call, because they change under a scoped service.

## Dependencies

Built on `laranail/package-tools` (provider, testing guards), `laranail/console` (command base),
Expand Down
Loading
Loading