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
10 changes: 4 additions & 6 deletions .github/workflows/static-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,10 @@ jobs:
- name: Mutation testing (minimum score 70)
# Pest's own mutator, not Infection: Infection has no Pest adapter, reads Pest's
# version as PHPUnit's, writes a config PHPUnit 12 rejects, and cannot map Pest's
# generated test classes to its JUnit report. The schema matrix (group `matrix`)
# covers almost every line, so it is left out, and group `shared-app` writes into the
# testbench application every process shares; the Tests workflow runs both. Both carry
# group `mutation-excluded`, which is what is excluded: under --parallel Pest honours
# only the first --exclude-group, and a comma-separated list excludes nothing, so
# `--exclude-group=matrix,shared-app` ran every test and raced on the shared config file.
# generated test classes to its JUnit report. Group `shared-app` writes into the
# testbench application every process shares, so it is left out; the Tests workflow
# runs it. It also carries group `mutation-excluded`, which is what is excluded: under
# --parallel Pest honours only the first --exclude-group.
env:
MUTATE_PATHS: ${{ steps.scope.outputs.paths }}
run: |
Expand Down
30 changes: 2 additions & 28 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ jobs:
test-command: 'vendor/bin/pest'

# The shared workflow runs on SQLite only, so the `database` test group runs again here on
# MySQL and Postgres service containers. Their passwords are throwaway literals: GitHub starts
# MySQL and Postgres service containers. That group includes the tenancy matrix (group
# `tenancy`: `tenancy.mode` none and column, end to end). Their passwords are throwaway literals: GitHub starts
# services before any step, so they cannot come from a generator.
databases:
name: Database group · ${{ matrix.database }}
Expand Down Expand Up @@ -78,30 +79,3 @@ jobs:

- name: Run the database group
run: vendor/bin/pest --group=database

# §13: the full product of the schema switches (1,152 shapes, tenancy included) on SQLite, weekly and on demand.
# Pull requests run the pairwise set (10 shapes) inside the jobs above.
matrix-full:
name: Schema switches · full product
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
timeout-minutes: 40
env:
LARANAIL_SETTINGS_MATRIX: full
COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{ secrets.GITHUB_TOKEN }}"}}'
steps:
- uses: actions/checkout@v7

- name: Setup PHP 8.4
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
with:
php-version: '8.4'
extensions: dom, curl, libxml, mbstring, zip, fileinfo, pdo, sqlite3, pdo_sqlite
coverage: none
tools: composer:v2

- name: Install dependencies
run: composer update --prefer-dist --no-interaction --no-progress

- name: Run the full switch matrix
run: vendor/bin/pest --group=matrix
42 changes: 42 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- The table shape is fixed, with `tenancy.mode` as the one switch: every table is keyed by a ULID,
each values row has a unique `uid` (the history's `setting_ref`) and no `slug`, `settable_id` is
`string(36)`, and titles, labels and descriptions are JSON maps of locale to text. The migration
always creates the definitions, history, change requests and persisted configuration tables, and
every values table has `deleted_at`. In `column` mode each tenant-owned table gets `tenant` in its
unique and lookup keys. Dedicated stores keep their `owner_id` foreign key.
- History is always recorded for a store with a database layer, and change requests always have
their table. A store on file layers only still raises `HistoryUnavailable` and
`ApprovalUnavailable`.
- `definitions.sources` defaults to `['code', 'config']`: add `database` to read definitions saved at
runtime, which costs one query per store per request.
- `configuration.persisted` now only turns the persisted configuration on and off; its table always
exists.
- Deleting a category deletes the row; creating the slug again makes a new category.
- The Eloquent models are the data layer for categories, definitions, audit, history and change
requests: `SettingsModel` holds the ULID keys, the connection and the tenant scope
(`Models\Scopes\TenantScope`, lifted with `allTenants()`), and the new `SettingHistory` and
`SettingChangeRequest` join `Setting`, `SettingCategory`, `SettingDefinition` and
`SettingAuditEntry`. The database driver still reads and writes values through the query builder
and takes the table name from `Setting::tableFor()`. `ModelContext` now holds the configuration
and the current tenant only.
- `doctor` checks that every column the package uses exists, instead of comparing a recorded shape
with configuration and the database.
- `QueryHistory::handle()` returns an Eloquent builder of `SettingHistory`.

- 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
Expand Down Expand Up @@ -302,6 +327,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Removed

- Removed with the owner's approval (2026-11-10), before the first tag, with the fixed schema:
the config keys `schema.path`, `identity.mode`, `ids.type`, `ids.owner_key`,
`translations.mode`, `categories.soft_deletes`, `definitions.table`, `history.enabled` and
`approvals.table`; `Database\SchemaShape`, `Database\StoreSchema`,
`Services\Database\SchemaShapeRepository` and the `database/settings-schema.php` file that
`install` and `make-store` recorded; the `Enums\IdentityMode`, `Enums\OwnerKeyType` and
`Enums\TranslationsMode` enums; `DatabaseDriver::newId()`, `shape()` and `schemaOf()`; the
`doctor` checks against a recorded shape; the pairwise schema matrix
(`tests/Feature/Database/SchemaMatrixTest.php`, `tests/Support/Pairwise.php`, test groups
`matrix`) and the weekly `matrix-full` CI job, replaced by a tenancy matrix (`none`, `column`)
in the `database` group; and `docs/tools/schema-switches.md`, whose surviving content is in
`docs/tools/database.md`.
- Removed with the same approval: `Services\Database\CategoryRepository`,
`DefinitionsRepository`, `AuditRepository`, `HistoryRepository` and `ChangeRequestRepository`,
whose queries live on the models and in the actions; and `Models\Concerns\UsesSettingsSchema`,
replaced by `Models\Concerns\BelongsToTenant` on `SettingsModel`.

- 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`,
Expand Down
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [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.
- [Runtime configuration](docs/tools/runtime-configuration.md) — stores, definitions and access changed in code for one request.
- [Schema switches](docs/tools/schema-switches.md) — identity, key types, dedicated stores, soft deletes, JSON translations, the definitions table and the schema file.
- [Audit queries](docs/tools/audit-queries.md) — reading the audit trail from PHP, gated by `view_audit`.
- [Tenancy](docs/tools/tenancy.md) — tenant column or database per tenant, the discriminator, and the stancl and spatie adapters.
- [Models and factories](docs/tools/models-and-factories.md) — Eloquent models and factories for tests, seeding and admin screens.
Expand Down
1 change: 0 additions & 1 deletion benchmarks/ReadBench.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,6 @@ private function boot(array $cache): void
$config->set('database.default', 'bench');
$config->set('database.connections.bench', ['driver' => 'sqlite', 'database' => $directory . '/database.sqlite', 'prefix' => '', 'foreign_key_constraints' => true]);
$config->set('cache.stores.file.path', $directory . '/cache');
$config->set('laranail.settings.schema.path', $directory . '/settings-schema.php');
$config->set('laranail.settings.layers.shipped.path', $directory . '/none.php');
$config->set('laranail.settings.stores.settings.layers', ['database']);
$config->set('laranail.settings.stores.settings.owners', ['owner', 'team']);
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
"test": "vendor/bin/pest --colors=always",
"test-coverage": "@test --coverage --min=90",
"test-dirty": "@test --dirty --compact",
"mutate": "vendor/bin/pest --mutate --everything --exclude-group=matrix --min=70",
"mutate": "vendor/bin/pest --mutate --everything --exclude-group=mutation-excluded --min=70",
"bench": [
"@composer --working-dir=tools/phpbench update --no-interaction --no-progress --quiet",
"tools/phpbench/vendor/bin/phpbench run --config=phpbench.json --report=settings"
Expand Down
60 changes: 9 additions & 51 deletions config/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
| 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.
| foreign key to `owner.table`; read when migrating).
| soft_deletes: keep forgotten rows trashed and restore them on write.
|
| 'user_settings' => [
Expand Down Expand Up @@ -82,51 +82,12 @@
'stores' => 'settings_stores',
],

/*
|--------------------------------------------------------------------------
| Schema switches
|--------------------------------------------------------------------------
|
| 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`, `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'),
],

'identity' => [
'mode' => 'slug_uid',
],

'ids' => [
'type' => null,
'owner_key' => 'string',
],

'translations' => [
'mode' => 'lang',
],

'categories' => [
'soft_deletes' => false,
],

/*
|--------------------------------------------------------------------------
| Tenancy
|--------------------------------------------------------------------------
|
| mode (recorded at migration time):
| mode (read when migrating, and on every query):
| `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).
Expand Down Expand Up @@ -227,13 +188,13 @@
| Setting definitions are registered in code with DefinitionRegistry::define()
| or kept in the definitions table.
|
| table: create the settings_definitions table (migration time).
| sources: where definitions come from, merged in order, later wins.
| Add `database` to read rows edited at runtime from the
| definitions table (one query per store per request).
| allowed_rules: the validation rules a database definition may use.
*/
'definitions' => [
'table' => false,
'sources' => ['code', 'config', 'database'],
'sources' => ['code', 'config'],
'allowed_rules' => ['required', 'nullable', 'string', 'integer', 'numeric', 'boolean', 'array', 'email', 'url', 'in', 'not_in', 'min', 'max', 'between', 'size', 'regex', 'date', 'alpha', 'alpha_dash', 'alpha_num'],
],

Expand Down Expand Up @@ -327,13 +288,12 @@
| History
|--------------------------------------------------------------------------
|
| enabled: create the settings_history table (migration time) and
| record every value change in it.
| Every value change is recorded in the history table.
|
| 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),
'keep_days' => 365,
'keep_versions' => null,
],
Expand Down Expand Up @@ -389,14 +349,12 @@
| Writes to definitions marked requiresApproval(), or to keys matched by
| `stores.<name>.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,
'min_approvals' => 1,
'allow_self' => false,
'expire_after' => 7,
Expand All @@ -408,8 +366,8 @@
| Persisted configuration
|--------------------------------------------------------------------------
|
| persisted: create settings_stores (migration time) to hold stores and
| layers saved through the API.
| persisted: read and write the stores and layers saved through the API
| (the settings_stores table).
| sources: merge order, later wins: `config`, `database`, `runtime`.
*/
'configuration' => [
Expand Down
15 changes: 9 additions & 6 deletions database/factories/SettingCategoryFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
use Simtabi\Laranail\Settings\Models\SettingCategory;

/**
* Categories for tests and seeding. Titles follow `translations.mode` (plain text, or a JSON map
* of locale to text). No Faker: slugs and titles are generated, so host applications need not
* Categories for tests and seeding. Titles are JSON maps of locale to text. No Faker: slugs and titles are generated, so host applications need not
* install it.
*
* SettingCategory::factory()->forStore('user_settings')->system()->create(['slug' => 'mail']);
Expand All @@ -24,10 +23,14 @@ final class SettingCategoryFactory extends Factory
{
protected $model = SettingCategory::class;

/** Text as `translations.mode` stores it: as is, or `{"": text}` (the text for any locale), as the engine writes it. */
public static function text(string $text): string
/**
* Text as the engine stores it: `['' => text]`, the text for any locale.
*
* @return array<string, string>
*/
public static function text(string $text): array
{
return new Translations(ModelContext::shape()->translations)->store($text);
return Translations::of($text);
}

/** @return array<string, mixed> */
Expand Down Expand Up @@ -64,7 +67,7 @@ public function parent(SettingCategory $parent): static
return $this->state(['parent_id' => $parent->getKey(), 'store' => $parent->store]);
}

/** A title (and optionally a description) as the shape stores them. */
/** A title, and optionally a description. */
public function titled(string $title, ?string $description = null): static
{
return $this->state(['title' => self::text($title), 'description' => $description === null ? null : self::text($description)]);
Expand Down
2 changes: 1 addition & 1 deletion database/factories/SettingDefinitionFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use Simtabi\Laranail\Settings\Models\SettingDefinition;

/**
* Rows of the definitions table (`definitions.table`). `default` holds the encoded default, as
* Rows of the definitions table. `default` holds the encoded default, as
* the definitions sync writes it.
*
* @extends Factory<SettingDefinition>
Expand Down
23 changes: 2 additions & 21 deletions database/factories/SettingFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

use Illuminate\Support\Str;
use Simtabi\Laranail\Settings\Models\Setting;
use Simtabi\Laranail\Settings\Enums\IdentityMode;
use Simtabi\Laranail\Settings\Models\ModelContext;
use Illuminate\Database\Eloquent\Factories\Factory;
use Simtabi\Laranail\Settings\Models\SettingCategory;

Expand All @@ -31,7 +29,7 @@ public function definition(): array
{
$key = 'test.' . Str::lower(Str::random(12));

return $this->identity($key) + [
return [
'scope' => 'global',
'key' => $key,
'group' => 'test',
Expand All @@ -51,7 +49,7 @@ public function forStore(string $store): static

public function key(string $key): static
{
return $this->state(fn (): array => ['key' => $key, 'group' => explode('.', $key, 2)[0]] + $this->identity($key));
return $this->state(['key' => $key, 'group' => explode('.', $key, 2)[0]]);
}

/** The value, encoded as the pipeline encodes an unencrypted value. */
Expand Down Expand Up @@ -80,21 +78,4 @@ public function inCategory(SettingCategory $category): static
{
return $this->state(['category_id' => $category->getKey(), 'category_store' => $category->store]);
}

/** @return array<string, string> the slug and uid columns the identity mode has */
private function identity(string $key): array
{
$mode = ModelContext::shape()->identity;
$columns = [];

if ($mode->hasSlug()) {
$columns['slug'] = $mode === IdentityMode::SlugPerRow ? sha1('global|' . $key . '|') : str_replace('.', '-', $key);
}

if ($mode->hasUid()) {
$columns['uid'] = (string) Str::ulid();
}

return $columns;
}
}
Loading
Loading