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
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* text=auto eol=lf

# Keep the Composer dist lean: exclude dev-only paths from package archives.
# Source, config, database stubs, README, LICENSE, CHANGELOG and composer.json ship.
# Source, config, database (migration, factories, seeders), README, LICENSE, CHANGELOG and composer.json ship.
/.github export-ignore
/docs export-ignore
/tests export-ignore
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,13 @@ jobs:
- name: Run the database group
run: vendor/bin/pest --group=database

# §13: the full product of the schema switches (576 shapes) on SQLite, weekly and on demand.
# §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: 20
timeout-minutes: 40
env:
LARANAIL_SETTINGS_MATRIX: full
COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{ secrets.GITHUB_TOKEN }}"}}'
Expand Down
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- Tenancy (`tenancy.mode`: `none`, `column`, `database`; recorded in the schema file). Column
mode adds a `tenant` column to the values, categories and audit tables, leading their unique
keys; every row is stamped with the current tenant and every query, the audit trail and the
models included, is limited to it. A `TenantDiscriminator` contract (`NullTenantDiscriminator`,
`ClosureTenantDiscriminator`) picked by `tenancy.discriminator` (`auto` detects stancl/tenancy,
then spatie/laravel-multitenancy; both only suggested). Preloaded records are kept per tenant
in every mode. New enum `TenancyMode`.
- Default categories: `DefaultCategoriesSeeder` (in `database/seeders`, registered with the
application's `db:seed`) creates `seed.categories` (general, appearance, localisation, mail,
notifications, security) as system categories in `seed.stores`, through the settings API as
the system actor; idempotent; `seed.enabled` switches it off. `NewCategory` takes `system`.
- Eloquent models (`Models\Setting`, `SettingCategory`, `SettingDefinition`,
`SettingAuditEntry`) and their factories in `database/factories`, for tests, seeding and admin
screens; they follow the recorded shape and tenancy. The engine itself stays on the query
builder.
- Schema switches (design phase 2b, §4.0): `identity.mode` (`slug_uid`, `slug_per_row`,
`uid_only`), `ids.type` (`bigint`, `uuid`, `ulid`; follows `laranail.db-tools.id_type` unless
set) with matching category keys, `ids.owner_key` (`string`, `typed`), `stores.<name>.mode`
Expand Down Expand Up @@ -46,6 +61,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- The four migration stubs are replaced by one migration,
`database/migrations/create_laranail_settings_tables.php`, which creates categories, the
optional definitions table, every recorded database store's values table (on its own
connection, with that connection's categories and audit tables) and the audit table, in
that order, and drops them in reverse. `install` publishes it; migrations published from the
stubs keep working. `make-store` writes one migration per store, a copy of it pinned to the
store (and connection), instead of up to three stub copies.
- The schema-switch matrix covers `tenancy.mode`: 10 pairwise shapes for 177 pairs per pull
request, 1,152 shapes in the weekly full product.
- The migration stubs read the recorded schema shape (or configuration, when nothing is
recorded) instead of individual config keys, and run on the store's recorded connection.
- `laranail::settings.install` publishes a fourth migration (`create_settings_definitions_table`,
Expand Down
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ They are added once each claim is true.

Requires PHP 8.4.1+ or 8.5 and Laravel 13. Works on MySQL, PostgreSQL and SQLite; SQL Server is not supported in 0.x.

> **Pre-release.** The engine reads and writes through file and config layers today; the
> database layer, caching and history arrive in the next phases. See
> [Getting started](docs/getting-started.md).
> **Pre-release.** The engine reads and writes through database, file and config layers;
> caching and history arrive in the next phases. See [Getting started](docs/getting-started.md).

## Install

Expand All @@ -24,15 +23,20 @@ composer require laranail/settings

### Getting started

Publish the config and the migrations (`settings`, `settings_categories`, `settings_audit`), then
migrate: the default store reads the database first, then its runtime file, then shipped defaults
from `settings/defaults.php` when that file exists.
Publish the config and the package's one migration (it creates `settings_categories`, a values
table per database store, and `settings_audit`), migrate, and optionally seed the default
categories: the default store reads the database first, then its runtime file, then shipped
defaults from `settings/defaults.php` when that file exists.

```bash
php artisan laranail::settings.install
php artisan migrate
php artisan db:seed # general, appearance, localisation, mail, notifications, security
```

For multi-tenant applications set `tenancy.mode` before migrating (see
[Tenancy](docs/tools/tenancy.md)).

An application without a database drops `database` from `stores.settings.layers` and keeps its
values in `storage/app/private/laranail/settings/settings.json`.

Expand Down Expand Up @@ -86,13 +90,16 @@ The hosted docs live at <https://opensource.simtabi.com/documentation/laranail/s
- [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.

### Recipes

- [Ship defaults with the application](docs/recipes/shipped-defaults.md) — a versioned defaults file instead of `.env`.
- [Test code that uses settings](docs/recipes/testing-with-the-fake.md) — `Settings::fake()` and its assertions.
- [Act as a user](docs/recipes/acting-as-a-user.md) — authorize and audit changes made on a user's behalf.
- [Move from files to the database](docs/recipes/moving-from-files-to-the-database.md) — bootstrap mode during install, then promotion.
- [Seed the default categories](docs/recipes/seeding-default-categories.md) — the shipped set, your own set, and per tenant.

## Contributing & security

Expand Down
8 changes: 6 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,15 @@
},
"suggest": {
"laranail/installer-headless": "Lets a store's database layer be skipped while the application is being installed (design: bootstrap mode).",
"laravel/sanctum": "Enables the sanctum actor resolver, which makes a token's settings:<ability> abilities a ceiling on what the token may do."
"laravel/sanctum": "Enables the sanctum actor resolver, which makes a token's settings:<ability> abilities a ceiling on what the token may do.",
"stancl/tenancy": "Detected automatically (tenancy.discriminator = auto): settings, categories, audit rows and in-memory reads are kept per tenant.",
"spatie/laravel-multitenancy": "Detected automatically (tenancy.discriminator = auto), like stancl/tenancy."
},
"autoload": {
"psr-4": {
"Simtabi\\Laranail\\Settings\\": "src/"
"Simtabi\\Laranail\\Settings\\": "src/",
"Simtabi\\Laranail\\Settings\\Database\\Factories\\": "database/factories/",
"Simtabi\\Laranail\\Settings\\Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
Expand Down
62 changes: 56 additions & 6 deletions config/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@
|
| php artisan laranail::settings.install
|
| The default store keeps its values in the database (publish and run the
| migrations with the install command above), above a JSON runtime file and
| the shipped PHP defaults. An application without a database drops
| `database` from the store's `layers`.
| 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`.
|
*/

Expand Down Expand Up @@ -91,8 +92,9 @@
| Schema switches (migration-time)
|--------------------------------------------------------------------------
|
| Read by `install` and `make-store`, which record the shape they produce
| in the schema file (`schema.path`, default database/settings-schema.php).
| 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.
Expand Down Expand Up @@ -128,6 +130,54 @@
'soft_deletes' => false,
],

/*
|--------------------------------------------------------------------------
| 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.
*/
'tenancy' => [
'mode' => env('LARANAIL_SETTINGS_TENANCY', 'none'),
'discriminator' => 'auto',
],

/*
| 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.
*/
'seed' => [
'enabled' => env('LARANAIL_SETTINGS_SEED', true),
'stores' => [],
'categories' => [
'general' => ['title' => 'General', 'description' => 'Site name, contact details and other application-wide settings.', 'icon' => 'cog'],
'appearance' => ['title' => 'Appearance', 'description' => 'Theme, branding and layout.', 'icon' => 'swatch'],
'localisation' => ['title' => 'Localisation', 'description' => 'Language, time zone, date and number formats.', 'icon' => 'globe'],
'mail' => ['title' => 'Mail', 'description' => 'Sender name and address, and other mail options.', 'icon' => 'envelope'],
'notifications' => ['title' => 'Notifications', 'description' => 'Which notifications are sent, and how.', 'icon' => 'bell'],
'security' => ['title' => 'Security', 'description' => 'Sign-in, sessions and other security options.', 'icon' => 'shield'],
],
],

/*
| 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
Expand Down
54 changes: 54 additions & 0 deletions database/factories/SettingAuditEntryFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Database\Factories;

use DateTimeInterface;
use Simtabi\Laranail\Settings\Enums\Channel;
use Simtabi\Laranail\Settings\Enums\ActorType;
use Simtabi\Laranail\Settings\Enums\AuditAction;
use Simtabi\Laranail\Settings\Enums\AuditOutcome;
use Simtabi\Laranail\Settings\Models\ModelContext;
use Illuminate\Database\Eloquent\Factories\Factory;
use Simtabi\Laranail\Settings\Models\SettingAuditEntry;

/**
* Audit rows for tests of audit queries and retention. Real entries come from the audit sinks.
*
* @extends Factory<SettingAuditEntry>
*/
final class SettingAuditEntryFactory extends Factory
{
protected $model = SettingAuditEntry::class;

/** @return array<string, mixed> */
public function definition(): array
{
return [
'occurred_at' => now(),
'action' => AuditAction::Update->value,
'outcome' => AuditOutcome::Allowed->value,
'store' => ModelContext::defaultStore()->value,
'scope' => 'global',
'key' => 'test.key',
'actor_type' => ActorType::System->value,
'channel' => Channel::Console->value,
];
}

public function action(AuditAction $action, AuditOutcome $outcome = AuditOutcome::Allowed): static
{
return $this->state(['action' => $action->value, 'outcome' => $outcome->value]);
}

public function by(string $alias, int|string $id): static
{
return $this->state(['actor_type' => ActorType::User->value, 'actor_alias' => $alias, 'actor_id' => (string) $id]);
}

public function at(DateTimeInterface $when): static
{
return $this->state(['occurred_at' => $when]);
}
}
76 changes: 76 additions & 0 deletions database/factories/SettingCategoryFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Database\Factories;

use Illuminate\Support\Str;
use Simtabi\Laranail\Settings\Models\ModelContext;
use Illuminate\Database\Eloquent\Factories\Factory;
use Simtabi\Laranail\Settings\Enums\TranslationsMode;
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
* install it.
*
* SettingCategory::factory()->forStore('user_settings')->system()->create(['slug' => 'mail']);
* SettingCategory::factory()->parent($general)->create();
*
* @extends Factory<SettingCategory>
*/
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
{
if (ModelContext::shape()->translations !== TranslationsMode::Json) {
return $text;
}

return json_encode(['' => $text], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

/** @return array<string, mixed> */
public function definition(): array
{
$slug = 'category-' . Str::lower(Str::random(10));

return [
'store' => ModelContext::defaultStore()->value,
'slug' => $slug,
'title' => self::text(Str::headline($slug)),
'description' => null,
'icon' => null,
'sort_order' => 0,
'is_system' => false,
];
}

/** In this store (default: the default store). */
public function forStore(string $store): static
{
return $this->state(['store' => $store]);
}

/** Shipped by code: `is_system`, which UIs do not let anyone delete. */
public function system(): static
{
return $this->state(['is_system' => true]);
}

/** Under a parent, in the parent's store. */
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. */
public function titled(string $title, ?string $description = null): static
{
return $this->state(['title' => self::text($title), 'description' => $description === null ? null : self::text($description)]);
}
}
Loading
Loading