diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index ca01a3c..d4def25 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -119,13 +119,16 @@ jobs: # 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. + # 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. if: github.event_name != 'pull_request' || steps.scope.outputs.paths != '' env: MUTATE_PATHS: ${{ steps.scope.outputs.paths }} run: | if [ -n "$MUTATE_PATHS" ]; then - vendor/bin/pest --mutate --path="$MUTATE_PATHS" --parallel --processes=8 --exclude-group=matrix,shared-app --ignore-min-score-on-zero-mutations --min=70 + vendor/bin/pest --mutate --path="$MUTATE_PATHS" --parallel --processes=8 --exclude-group=mutation-excluded --ignore-min-score-on-zero-mutations --min=70 else - vendor/bin/pest --mutate --everything --parallel --processes=8 --exclude-group=matrix,shared-app --min=70 + vendor/bin/pest --mutate --everything --parallel --processes=8 --exclude-group=mutation-excluded --min=70 fi diff --git a/CHANGELOG.md b/CHANGELOG.md index 67be44d..dd47ffc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -61,6 +61,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- The code is layered entry points → actions → services → support, held by architecture + tests. Database work moved out of actions into `Database\AuditRepository` (the audit sink, + query and prune), `Database\DefinitionsRepository` (definitions sync and reads) and + `Database\SchemaInspector` (`doctor` and install's foreign-table check); the tenant adapters + into `Tenancy\TenantDiscriminators`; the transaction-and-audit sequence of every write, + category change and promotion into `Support\AuditedTransaction`; shared helpers into + `Support\Json`, `Support\Translations`, `Support\DatabaseValues` and + `Support\ConfigValues`, and `Scope::of()`, `Scope::fromString()`, `Scope::owner()`, + `Store::requireDatabase()`, `CategoryRepository::of()`. Behaviour, messages and audit entries + are unchanged. +- `FindOrphans` finds orphaned owners' settings; `PruneOrphans` removes them. + +### Deprecated + +- `PruneOrphans::find()`: use `FindOrphans::handle()`. It forwards; removed in 1.0. +- `DatabaseDefinitions::localised()`: use `Support\Translations::nullableText()`. It forwards; + removed in 1.0. + - 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 diff --git a/database/factories/SettingCategoryFactory.php b/database/factories/SettingCategoryFactory.php index 27b39c1..5d7a847 100644 --- a/database/factories/SettingCategoryFactory.php +++ b/database/factories/SettingCategoryFactory.php @@ -7,7 +7,7 @@ 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\Support\Translations; use Simtabi\Laranail\Settings\Models\SettingCategory; /** @@ -27,11 +27,7 @@ final class SettingCategoryFactory extends Factory /** 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 new Translations(ModelContext::shape()->translations)->store($text); } /** @return array */ diff --git a/docs/architecture.md b/docs/architecture.md index a9af21a..db3ecda 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -16,6 +16,22 @@ How `laranail/settings` is shaped, and why. - **Categories.** A shared `settings_categories` table, scoped per store, organises settings for people and interfaces; `group` remains a lightweight code namespace. +## How the code is layered + +| Layer | Holds | Examples | +|---|---|---| +| Entry points | resolve inputs and delegate; no work of their own | `SettingsManager`, `CategoryManager`, `AuditQuery`, the console commands, the facade | +| Actions (`Actions/`) | one intent each, `handle()` only, final and readonly | `SetSetting`, `PromoteStore`, `SyncDefinitions`, `FindOrphans` | +| Services | the database, the files, a body of rules | `Database\AuditRepository`, `Database\DefinitionsRepository`, `Database\SchemaInspector`, `Database\CategoryRepository`, the drivers, `Stores\SettingWriter`, `Resolution\Resolver`, `Authorization\AccessGuard`, `Tenancy\TenantDiscriminators` | +| Support (`Support/`) | stateless logic shared by several classes | `AuditedTransaction`, `Translations`, `Json`, `DatabaseValues`, `ConfigValues`, `ValueEncoder` | + +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 +through `Support\AuditedTransaction`, so every write, category change and promotion commits and +audits the same way. Only entry points depend on actions. Architecture tests hold each rule, +and each exemption (the guards the actions run through, the action bundles, `QueryAudit`'s three +result shapes) carries its reason and fails when it is no longer needed. + ## Why build rather than adopt? No existing package combines polymorphic owners, per-store categories, multiple tables and a diff --git a/src/Actions/Categories/CategoryGuard.php b/src/Actions/Categories/CategoryGuard.php index 2c5bbbf..e05775e 100644 --- a/src/Actions/Categories/CategoryGuard.php +++ b/src/Actions/Categories/CategoryGuard.php @@ -12,12 +12,11 @@ use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Data\CategorySlug; use Simtabi\Laranail\Settings\Enums\AuditAction; -use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Support\AuditedTransaction; use Simtabi\Laranail\Settings\Database\CategoryRepository; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; -use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** * What every category change does around its work: authorize `manage_categories`, then run the @@ -46,26 +45,22 @@ public function run(Store $store, CategorySlug $slug, ?Actor $actor, string $ope $this->access->authorize($actor, Ability::ManageCategories, $subject); - $database = $store->database() - ?? throw new StoreNotWritable(sprintf('Store [%s] has no active database layer; categories are kept in the database.', $store->name)); + $database = $store->requireDatabase('; categories are kept in the database.'); - try { - return $store->transaction(function () use ($store, $database, $work, $before, $after, $subject, $actor, $meta): mixed { + return new AuditedTransaction($this->access)->run( + $store, + AuditAction::ManageCategories, + $subject, + $actor, + function () use ($store, $database, $work, $before): mixed { $this->events->dispatch($before); - $result = $work(new CategoryRepository($database, $store->name), $database); - $this->access->auditor()->record(AuditAction::ManageCategories, AuditOutcome::Allowed, $subject, $actor, meta: $meta); - $this->events->dispatch($after); - - return $result; - }); - } catch (SettingsException $exception) { - try { - $this->access->auditor()->record(AuditAction::ManageCategories, AuditOutcome::Failed, $subject, $actor, meta: $meta + ['error' => $exception::class]); - } catch (SettingsException) { - // The original failure is what the caller needs; it is rethrown below. - } - throw $exception; - } + return $work(new CategoryRepository($database, $store->name), $database); + }, + then: function () use ($after): void { + $this->events->dispatch($after); + }, + meta: $meta, + ); } } diff --git a/src/Actions/DiagnoseSettings.php b/src/Actions/DiagnoseSettings.php index 409d504..626066e 100644 --- a/src/Actions/DiagnoseSettings.php +++ b/src/Actions/DiagnoseSettings.php @@ -4,8 +4,6 @@ namespace Simtabi\Laranail\Settings\Actions; -use Throwable; -use Illuminate\Database\Query\Builder; use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Enums\IdType; use Simtabi\Laranail\Settings\Stores\Store; @@ -14,6 +12,7 @@ use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; +use Simtabi\Laranail\Settings\Database\SchemaInspector; use Simtabi\Laranail\Settings\Exceptions\SettingsException; use Simtabi\Laranail\Settings\Database\SchemaShapeRepository; use Simtabi\Laranail\Package\Tools\Services\Doctor\DoctorResult; @@ -150,12 +149,10 @@ private function drift(Store $store, DatabaseDriver $database): Finding $expected[$shape->names->definitions()] = self::DEFINITION_COLUMNS; } + $inspector = new SchemaInspector($database); + foreach ($expected as $table => $columns) { - try { - $present = $database->connection()->getSchemaBuilder()->getColumnListing($table); - } catch (Throwable) { - $present = []; - } + $present = $inspector->columns($table) ?? []; foreach (array_diff($columns, $present) as $column) { $missing[] = $table . '.' . $column; @@ -166,7 +163,7 @@ private function drift(Store $store, DatabaseDriver $database): Finding } } - $idType = $this->idTypeDrift($database, $database->tableFor($store->name), $shape->ids); + $idType = $this->idTypeDrift($inspector, $database->tableFor($store->name), $shape->ids); if ($missing !== []) { return new Finding("{$store->name}: schema", 'The tables have every column the recorded schema uses', DoctorResult::fail('Missing columns (publish and run the latest migrations): ' . implode(', ', $missing), ['missing' => $missing])); @@ -193,25 +190,17 @@ private function switchColumns(SchemaShape $shape, bool $dedicated, bool $softDe } /** A message when the table's `id` column is not of the recorded key type, else null. */ - private function idTypeDrift(DatabaseDriver $database, string $table, IdType $type): ?string + private function idTypeDrift(SchemaInspector $inspector, string $table, IdType $type): ?string { - try { - $columns = $database->connection()->getSchemaBuilder()->getColumns($table); - } catch (Throwable) { + $typeName = $inspector->idType($table); + + if ($typeName === null) { return null; } - foreach ($columns as $column) { - if (($column['name'] ?? null) !== 'id') { - continue; - } - - $integer = str_contains(strtolower((string) ($column['type_name'] ?? '')), 'int'); + $integer = str_contains(strtolower($typeName), 'int'); - return $integer === ($type === IdType::Bigint) ? null : sprintf('Table [%s] has an id of type [%s], but the recorded key type is [%s].', $table, $column['type_name'] ?? '?', $type->value); - } - - return null; + return $integer === ($type === IdType::Bigint) ? null : sprintf('Table [%s] has an id of type [%s], but the recorded key type is [%s].', $table, $typeName, $type->value); } private function scopes(Store $store, DatabaseDriver $database): Finding @@ -244,10 +233,7 @@ private function scopes(Store $store, DatabaseDriver $database): Finding private function categories(Store $store, DatabaseDriver $database): Finding { - $count = $database->attempt($store->name, static fn (): int => $database->connection()->table($database->tableFor($store->name)) - ->whereNotNull('category_id') - ->where(static fn (Builder $query): Builder => $query->whereNull('category_store')->orWhere('category_store', '!=', $store->name->value)) - ->count()); + $count = new SchemaInspector($database)->crossStoreCategoryLinks($store->name); return new Finding("{$store->name}: categories", 'Settings only use categories of their own store', $count === 0 ? DoctorResult::pass('Every category link stays inside the store.') diff --git a/src/Actions/FindForeignTables.php b/src/Actions/FindForeignTables.php index 0caa28c..1b26612 100644 --- a/src/Actions/FindForeignTables.php +++ b/src/Actions/FindForeignTables.php @@ -4,9 +4,9 @@ namespace Simtabi\Laranail\Settings\Actions; -use Throwable; use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; +use Simtabi\Laranail\Settings\Database\SchemaInspector; /** * The tables `install` would create that already exist and are not this package's (D-4). A bare @@ -45,15 +45,14 @@ public function handle(): array $database->names()->audit() => self::SIGNATURES['audit'], ]; + $inspector = new SchemaInspector($database); + foreach ($tables as $table => $signature) { - try { - $schema = $database->connection()->getSchemaBuilder(); + // Unreachable (null): nothing exists to collide with. + $columns = $inspector->hasTable($table) === true ? $inspector->columns($table) : null; - if ($schema->hasTable($table) && array_diff($signature, $schema->getColumnListing($table)) !== []) { - $foreign[$database->connectionName() . '.' . $table] = true; - } - } catch (Throwable) { - // Unreachable: nothing exists to collide with. + if ($columns !== null && array_diff($signature, $columns) !== []) { + $foreign[$database->connectionName() . '.' . $table] = true; } } } diff --git a/src/Actions/FindOrphans.php b/src/Actions/FindOrphans.php new file mode 100644 index 0000000..070c5ad --- /dev/null +++ b/src/Actions/FindOrphans.php @@ -0,0 +1,93 @@ +>, unmapped: list} + */ + public function handle(): array + { + $orphans = []; + $unmapped = []; + + foreach ($this->stores->all() as $name => $store) { + $database = $store->database(); + + if (! $database instanceof DatabaseDriver) { + continue; + } + + foreach ($store->owners as $alias) { + $model = ($this->models)($alias); + + if ($model === null || ! is_subclass_of($model, Model::class)) { + $unmapped[] = $alias; + + continue; + } + + $found = $this->orphansOf($store, $database, $alias, $model); + + if ($found !== []) { + $orphans[$name] = [...($orphans[$name] ?? []), ...$found]; + } + } + } + + return ['orphans' => $orphans, 'unmapped' => array_values(array_unique($unmapped))]; + } + + /** + * @param class-string $model + * + * @return list + */ + private function orphansOf(Store $store, DatabaseDriver $database, string $alias, string $model): array + { + $instance = new $model; + $integerKeys = $instance->getKeyType() === 'int'; + $orphans = []; + + foreach (array_chunk($database->scopesOf($store->name, $alias), 500) as $scopes) { + $ids = array_map(static fn (string $scope): string => substr($scope, strlen($alias) + 1), $scopes); + $keys = $integerKeys ? array_map(intval(...), array_filter($ids, ctype_digit(...))) : $ids; + + $existing = array_map( + static fn (mixed $key): string => is_scalar($key) ? (string) $key : '', + $instance->newQueryWithoutScopes()->whereKey($keys)->pluck($instance->getKeyName())->all(), + ); + + foreach (array_diff($ids, $existing) as $id) { + $orphans[] = new OwnerRef($alias, $id); + } + } + + return $orphans; + } +} diff --git a/src/Actions/PromoteStore.php b/src/Actions/PromoteStore.php index 61dd61f..5b37dd4 100644 --- a/src/Actions/PromoteStore.php +++ b/src/Actions/PromoteStore.php @@ -19,7 +19,6 @@ use Simtabi\Laranail\Settings\Enums\AuditAction; use Illuminate\Contracts\Cache\Factory as Caches; use Simtabi\Laranail\Settings\Drivers\JsonDriver; -use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Data\PromotionReport; use Simtabi\Laranail\Settings\Events\StorePromoted; use Simtabi\Laranail\Settings\Data\PromotionRequest; @@ -28,8 +27,8 @@ use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\PromotionLocked; +use Simtabi\Laranail\Settings\Support\AuditedTransaction; use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; -use Simtabi\Laranail\Settings\Exceptions\SettingsException; /** * Promote a store's runtime file into its database layer (design §7.4): needs `promote`. @@ -65,8 +64,7 @@ public function handle(Store $store, PromotionRequest $request = new PromotionRe $this->access->authorize($actor, Ability::Promote, $subject); - $database = $store->database() - ?? throw new StoreNotWritable(sprintf('Store [%s] has no active database layer to promote into.', $store->name)); + $database = $store->requireDatabase(' to promote into.'); $runtime = $this->runtime($store); if (! $runtime instanceof JsonDriver) { @@ -93,27 +91,18 @@ private function promote(Store $store, PromotionRequest $request, ?Actor $actor, $this->events->dispatch(new StorePromoting($store->name->value)); - try { - [$promoted, $skipped] = $store->transaction(function () use ($store, $request, $actor, $subject, $database, $records): array { - [$promoted, $skipped] = $this->copy($store, $request, $database, $records); - - $this->access->auditor()->record(AuditAction::Promote, AuditOutcome::Allowed, $subject, $actor, meta: [ - 'promoted' => count($promoted), - 'skipped' => count($skipped), - 'replayed' => $request->from, - ]); - - return [$promoted, $skipped]; - }); - } catch (SettingsException $exception) { - try { - $this->access->auditor()->record(AuditAction::Promote, AuditOutcome::Failed, $subject, $actor, meta: ['error' => $exception::class]); - } catch (SettingsException) { - // The original failure is rethrown below. - } - - throw $exception; - } + [$promoted, $skipped] = new AuditedTransaction($this->access)->run( + $store, + AuditAction::Promote, + $subject, + $actor, + fn (): array => $this->copy($store, $request, $database, $records), + static fn (array $result): array => ['meta' => [ + 'promoted' => count($result[0]), + 'skipped' => count($result[1]), + 'replayed' => $request->from, + ]], + ); $archive = $request->from === null ? $runtime->archive($store->name, CarbonImmutable::now()) : null; diff --git a/src/Actions/PruneAudit.php b/src/Actions/PruneAudit.php index 504d2ce..9504495 100644 --- a/src/Actions/PruneAudit.php +++ b/src/Actions/PruneAudit.php @@ -12,6 +12,7 @@ use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Database\AuditRepository; use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; @@ -54,11 +55,7 @@ public function handle(int $keepDays, ?Actor $actor = null): int $seen[$database->connectionName()] = true; - // Retention is one policy for the whole application, so it prunes every tenant's rows. - $removed += $database->attempt($store->name, static fn (): int => $database->connection() - ->table($database->names()->audit()) - ->where('occurred_at', '<', $cutoff) - ->delete()); + $removed += new AuditRepository($database)->prune($cutoff, $store->name); } $this->access->auditor()->record(AuditAction::Prune, AuditOutcome::Allowed, $subject, $actor, meta: ['target' => 'audit', 'keep_days' => $keepDays, 'removed' => $removed]); diff --git a/src/Actions/PruneOrphans.php b/src/Actions/PruneOrphans.php index 0127bec..fbc85ea 100644 --- a/src/Actions/PruneOrphans.php +++ b/src/Actions/PruneOrphans.php @@ -5,24 +5,17 @@ namespace Simtabi\Laranail\Settings\Actions; use Closure; -use Illuminate\Database\Eloquent\Model; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; -use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Authorization\AccessGuard; /** - * Find, and remove, 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. + * 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. @@ -44,38 +37,13 @@ public function __construct( /** * The orphaned owners per store, and the aliases no model answers for. * + * @deprecated 0.1 Use {@see FindOrphans::handle()}; this forwards to it and is removed in 1.0. + * * @return array{orphans: array>, unmapped: list} */ public function find(): array { - $orphans = []; - $unmapped = []; - - foreach ($this->stores->all() as $name => $store) { - $database = $store->database(); - - if (! $database instanceof DatabaseDriver) { - continue; - } - - foreach ($store->owners as $alias) { - $model = ($this->models)($alias); - - if ($model === null || ! is_subclass_of($model, Model::class)) { - $unmapped[] = $alias; - - continue; - } - - $found = $this->orphansOf($store, $database, $alias, $model); - - if ($found !== []) { - $orphans[$name] = [...($orphans[$name] ?? []), ...$found]; - } - } - } - - return ['orphans' => $orphans, 'unmapped' => array_values(array_unique($unmapped))]; + return $this->finder()->handle(); } /** @@ -88,7 +56,7 @@ public function handle(?Actor $actor = null): int $removed = 0; $flushed = 0; - foreach ($this->find()['orphans'] as $name => $owners) { + foreach ($this->finder()->handle()['orphans'] as $name => $owners) { $store = $this->stores->all()[$name]; foreach ($owners as $owner) { @@ -102,31 +70,8 @@ public function handle(?Actor $actor = null): int return $removed; } - /** - * @param class-string $model - * - * @return list - */ - private function orphansOf(Store $store, DatabaseDriver $database, string $alias, string $model): array + private function finder(): FindOrphans { - $instance = new $model; - $integerKeys = $instance->getKeyType() === 'int'; - $orphans = []; - - foreach (array_chunk($database->scopesOf($store->name, $alias), 500) as $scopes) { - $ids = array_map(static fn (string $scope): string => substr($scope, strlen($alias) + 1), $scopes); - $keys = $integerKeys ? array_map(intval(...), array_filter($ids, ctype_digit(...))) : $ids; - - $existing = array_map( - static fn (mixed $key): string => is_scalar($key) ? (string) $key : '', - $instance->newQueryWithoutScopes()->whereKey($keys)->pluck($instance->getKeyName())->all(), - ); - - foreach (array_diff($ids, $existing) as $id) { - $orphans[] = new OwnerRef($alias, $id); - } - } - - return $orphans; + return new FindOrphans($this->stores, $this->models); } } diff --git a/src/Actions/QueryAudit.php b/src/Actions/QueryAudit.php index 41708a7..b311e49 100644 --- a/src/Actions/QueryAudit.php +++ b/src/Actions/QueryAudit.php @@ -4,27 +4,18 @@ namespace Simtabi\Laranail\Settings\Actions; -use JsonException; -use Carbon\CarbonImmutable; use Illuminate\Pagination\Cursor; use Illuminate\Database\Query\Builder; use Illuminate\Support\LazyCollection; use Simtabi\Laranail\Settings\Data\Actor; -use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Subject; -use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; -use Simtabi\Laranail\Settings\Enums\Channel; use Simtabi\Laranail\Settings\Data\AuditPage; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\AuditEntry; -use Simtabi\Laranail\Settings\Enums\ActorType; use Simtabi\Laranail\Settings\Data\AuditFilter; -use Simtabi\Laranail\Settings\Enums\AuditAction; -use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Exceptions\DriverFailure; +use Simtabi\Laranail\Settings\Database\AuditRepository; use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\DriverUnavailable; @@ -79,99 +70,18 @@ private function query(AuditFilter $filter, ?Actor $actor): Builder $this->access->authorize($actor, Ability::ViewAudit, new Subject( $store->name, key: $filter->key, - owner: ! $filter->scope instanceof Scope || $filter->scope->isGlobal() ? null : new OwnerRef(...explode(':', $filter->scope->value, 2)), + owner: $filter->scope?->owner(), )); - $database = $store->database() ?? $this->stores->default()->database(); + $audit = AuditRepository::locate($this->stores, $store->name) + ?? throw new DriverUnavailable(sprintf('Store [%s] has no active database layer, so its audit trail went to the log and cannot be queried.', $store->name)); - if (! $database instanceof DatabaseDriver) { - throw new DriverUnavailable(sprintf('Store [%s] has no active database layer, so its audit trail went to the log and cannot be queried.', $store->name)); - } - - // In column-mode tenancy a tenant reads its own trail only. - $query = $database->scoped($database->connection()->table($database->names()->audit())); - - if ($filter->store instanceof StoreName) { - $query->where('store', $filter->store->value); - } - - foreach (['scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'action' => $filter->action?->value, 'outcome' => $filter->outcome?->value] as $column => $value) { - if ($value !== null) { - $query->where($column, $value); - } - } - - if ($filter->since instanceof CarbonImmutable) { - $query->where('occurred_at', '>=', $filter->since); - } - - if ($filter->until instanceof CarbonImmutable) { - $query->where('occurred_at', '<=', $filter->until); - } - - return $query->orderByDesc('occurred_at')->orderByDesc('id'); + return $audit->query($filter); } /** @param array $row */ private function entry(array $row): AuditEntry { - $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; - $number = static fn (string $column): ?int => is_numeric($row[$column] ?? null) ? (int) $row[$column] : null; - $id = $text('id'); - $occurred = $text('occurred_at'); - $action = AuditAction::tryFrom($text('action') ?? ''); - $outcome = AuditOutcome::tryFrom($text('outcome') ?? ''); - $actorType = ActorType::tryFrom($text('actor_type') ?? ''); - $channel = Channel::tryFrom($text('channel') ?? ''); - - if ($id === null || $occurred === null || ! $action instanceof AuditAction || ! $outcome instanceof AuditOutcome || ! $actorType instanceof ActorType || ! $channel instanceof Channel) { - throw new DriverFailure(sprintf('Audit row [%s] is malformed.', $id ?? '?')); - } - - return new AuditEntry( - id: $id, - occurredAt: CarbonImmutable::parse($occurred), - action: $action, - outcome: $outcome, - store: $text('store'), - scope: $text('scope'), - key: $text('key'), - locale: $text('locale'), - versionFrom: $number('version_from'), - versionTo: $number('version_to'), - actorType: $actorType, - actorAlias: $text('actor_alias'), - actorId: $text('actor_id'), - channel: $channel, - ip: $text('ip'), - userAgent: $text('user_agent'), - requestId: $text('request_id'), - reason: $text('reason'), - meta: $this->meta($text('meta')), - ); - } - - /** @return array */ - private function meta(?string $json): array - { - if ($json === null) { - return []; - } - - try { - $decoded = json_decode($json, true, 4, JSON_THROW_ON_ERROR); - } catch (JsonException) { - return []; - } - - $meta = []; - - foreach (is_array($decoded) ? $decoded : [] as $key => $value) { - if (is_scalar($value) || $value === null) { - $meta[(string) $key] = $value; - } - } - - return $meta; + return AuditRepository::entry($row); } } diff --git a/src/Actions/SyncDefinitions.php b/src/Actions/SyncDefinitions.php index 4def4d7..ade2de7 100644 --- a/src/Actions/SyncDefinitions.php +++ b/src/Actions/SyncDefinitions.php @@ -4,21 +4,16 @@ namespace Simtabi\Laranail\Settings\Actions; -use JsonException; -use Carbon\CarbonImmutable; use Simtabi\Laranail\Settings\Data\Actor; use Simtabi\Laranail\Settings\Data\Subject; -use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Enums\Ability; -use Simtabi\Laranail\Settings\Data\Definition; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Stores\StoreRegistry; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Enums\TranslationsMode; -use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Authorization\AccessGuard; +use Simtabi\Laranail\Settings\Database\DefinitionsRepository; use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; /** @@ -62,7 +57,8 @@ public function handle(?Actor $actor = null): array continue; } - $result = $database->attempt($store->name, fn (): array => $database->transaction(fn (): array => $this->sync($store, $database, $byStore[$name] ?? []), $store->name)); + $repository = new DefinitionsRepository($database, $this->encoder); + $result = $database->attempt($store->name, fn (): array => $database->transaction(fn (): array => $repository->sync($store->name, $byStore[$name] ?? []), $store->name)); $report['synced'] += $result['synced']; $report['removed'] += $result['removed']; $report['conflicts'] = [...$report['conflicts'], ...$result['conflicts']]; @@ -77,98 +73,4 @@ public function handle(?Actor $actor = null): array return $report; } - - /** - * @param list $definitions - * - * @return array{synced: int, removed: int, conflicts: list} - */ - private function sync(Store $store, DatabaseDriver $database, array $definitions): array - { - $table = static fn () => $database->connection()->table($database->names()->definitions())->where('store', $store->name->value); - $now = CarbonImmutable::now(); - $json = $database->shape()->translations === TranslationsMode::Json; - $synced = 0; - $conflicts = []; - $keys = []; - - foreach ($definitions as $definition) { - $keys[] = $definition->key->value; - $row = $table()->where('key', $definition->key->value)->first(['is_system']); - - if ($row !== null && ! in_array($row->is_system ?? false, [true, 1, '1'], true)) { - $conflicts[] = $store->name->value . '.' . $definition->key->value; - - continue; - } - - $columns = $this->columns($database, $store, $definition, $json) + ['updated_at' => $now]; - - if ($row === null) { - $table()->insert($columns + DatabaseDriver::newId($database->shape()->ids) + [ - 'store' => $store->name->value, - 'key' => $definition->key->value, - 'is_system' => true, - 'created_at' => $now, - ]); - } else { - $table()->where('key', $definition->key->value)->update($columns); - } - - $synced++; - } - - $removed = $table()->where('is_system', true)->whereNotIn('key', $keys === [] ? [''] : $keys)->delete(); - - return ['synced' => $synced, 'removed' => $removed, 'conflicts' => $conflicts]; - } - - /** @return array */ - private function columns(DatabaseDriver $database, Store $store, Definition $definition, bool $json): array - { - $category = null; - - if ($definition->category !== null) { - $categories = $database->connection()->table($database->names()->categories()); - - // Definitions are shared by every tenant, so they link to the central categories (''). - if ($database->shape()->tenancy->hasColumn()) { - $categories->where('tenant', ''); - } - - $category = $categories->where('store', $store->name->value)->where('slug', $definition->category)->value('id'); - } - - return [ - 'slug' => $definition->key->slug(), - 'group' => $definition->group(), - 'category_id' => is_int($category) || is_string($category) ? $category : null, - 'type' => $definition->type, - // An encrypted setting's default stays in code: the table must not hold a readable copy. - 'default' => $definition->hasDefault && ! $definition->encrypted ? $this->encoder->encode($definition->key, $definition->default) : null, - 'label' => $this->text($definition->label, $json), - 'description' => $this->text($definition->description, $json), - 'rules' => $this->encode($definition->rules), - 'is_encrypted' => $definition->encrypted, - 'is_public' => $definition->public, - 'is_locked' => $definition->locked, - 'inherits' => $definition->inherits, - 'overridable_by' => $this->encode($definition->overridableBy), - ]; - } - - private function text(?string $text, bool $json): ?string - { - return $text === null || ! $json ? $text : $this->encode(['' => $text]); - } - - /** @param array $value */ - private function encode(array $value): string - { - try { - return json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - } catch (JsonException $exception) { - throw new DriverFailure('A definition could not be encoded for the definitions table.', 0, $exception); - } - } } diff --git a/src/Actions/WriteGuard.php b/src/Actions/WriteGuard.php index 561300a..3c9beda 100644 --- a/src/Actions/WriteGuard.php +++ b/src/Actions/WriteGuard.php @@ -6,14 +6,13 @@ use Closure; use Simtabi\Laranail\Settings\Data\Actor; -use Simtabi\Laranail\Settings\Data\Subject; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Enums\AuditAction; use Simtabi\Laranail\Settings\Data\SettingTarget; use Simtabi\Laranail\Settings\Enums\AuditOutcome; use Simtabi\Laranail\Settings\Stores\SettingWriter; use Simtabi\Laranail\Settings\Authorization\AccessGuard; -use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Support\AuditedTransaction; use Simtabi\Laranail\Settings\Exceptions\ApprovalUnavailable; /** @@ -51,40 +50,16 @@ public function run(Ability $ability, SettingTarget $target, ?Actor $actor, bool $override = $respectsLocks && $this->mayOverrideLock($target, $actor); - try { - // The write and its audit row commit together: an audit failure rolls the write back. - $target->store->transaction(function () use ($write, $override, $action, $subject, $actor, $target): void { - [$before, $after] = $write($override); - - $this->access->auditor()->record( - $action, - AuditOutcome::Allowed, - $subject, - $actor, - $target->reason, - $before, - $after, - $override ? ['override_lock' => true] : [], - ); - }); - } catch (SettingsException $exception) { - $this->recordFailure($action, $subject, $actor, $target, $exception); - - throw $exception; - } - } - - /** - * Audit a failed write, outside the rolled-back transaction. When the audit itself is what - * failed, recording the failure may fail the same way; the original exception still wins. - */ - private function recordFailure(AuditAction $action, Subject $subject, ?Actor $actor, SettingTarget $target, SettingsException $exception): void - { - try { - $this->access->auditor()->record($action, AuditOutcome::Failed, $subject, $actor, $target->reason, meta: ['error' => $exception::class]); - } catch (SettingsException) { - // The caller is told about the original failure below; nothing else to do here. - } + // The write and its audit row commit together: an audit failure rolls the write back. + new AuditedTransaction($this->access)->run( + $target->store, + $action, + $subject, + $actor, + static fn (): array => $write($override), + static fn (array $versions): array => ['from' => $versions[0], 'to' => $versions[1], 'meta' => $override ? ['override_lock' => true] : []], + reason: $target->reason, + ); } /** diff --git a/src/Audit/DatabaseAuditSink.php b/src/Audit/DatabaseAuditSink.php index fa64c12..f62f0da 100644 --- a/src/Audit/DatabaseAuditSink.php +++ b/src/Audit/DatabaseAuditSink.php @@ -5,12 +5,11 @@ namespace Simtabi\Laranail\Settings\Audit; use Closure; -use JsonException; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\AuditEntry; use Simtabi\Laranail\Settings\Contracts\AuditSink; use Simtabi\Laranail\Settings\Stores\StoreRegistry; -use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Database\AuditRepository; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; /** @@ -29,58 +28,17 @@ public function __construct( /** Whether there is an active database layer to write this entry to. */ public function accepts(AuditEntry $entry): bool { - return $this->target($entry) instanceof DatabaseDriver; + return $this->target($entry) instanceof AuditRepository; } public function record(AuditEntry $entry): void { - $database = $this->target($entry) - ?? throw new DriverFailure(sprintf('The database audit sink has no active database layer for store [%s].', $entry->store ?? 'default')); - - $store = new StoreName($entry->store ?? 'audit'); - - $database->attempt($store, fn (): bool => $database->connection()->table($database->names()->audit())->insert([ - 'id' => $entry->id, - 'occurred_at' => $entry->occurredAt, - 'action' => $entry->action->value, - 'outcome' => $entry->outcome->value, - 'store' => $entry->store, - 'scope' => $entry->scope, - 'key' => $entry->key, - 'locale' => $entry->locale, - 'version_from' => $entry->versionFrom, - 'version_to' => $entry->versionTo, - 'change_request' => null, - 'actor_type' => $entry->actorType->value, - 'actor_alias' => $entry->actorAlias, - 'actor_id' => $entry->actorId, - 'channel' => $entry->channel->value, - 'ip' => $entry->ip, - 'user_agent' => $entry->userAgent, - 'request_id' => $entry->requestId, - 'reason' => $entry->reason, - 'meta' => $this->meta($entry), - ] + $database->tenantColumns())); + ($this->target($entry) ?? throw new DriverFailure(sprintf('The database audit sink has no active database layer for store [%s].', $entry->store ?? 'default'))) + ->insert($entry); } - private function target(AuditEntry $entry): ?DatabaseDriver + private function target(AuditEntry $entry): ?AuditRepository { - $stores = ($this->stores)(); - $store = $entry->store === null ? $stores->default() : $stores->get(new StoreName($entry->store)); - - return $store->database() ?? $stores->default()->database(); - } - - private function meta(AuditEntry $entry): ?string - { - if ($entry->meta === []) { - return null; - } - - try { - return json_encode($entry->meta, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); - } catch (JsonException $exception) { - throw new DriverFailure('An audit entry\'s meta could not be encoded.', 0, $exception); - } + return AuditRepository::locate(($this->stores)(), $entry->store === null ? null : new StoreName($entry->store)); } } diff --git a/src/Categories/CategoryManager.php b/src/Categories/CategoryManager.php index 5fef9be..981ba3d 100644 --- a/src/Categories/CategoryManager.php +++ b/src/Categories/CategoryManager.php @@ -15,7 +15,6 @@ use Simtabi\Laranail\Settings\Authorization\AccessGuard; use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; use Simtabi\Laranail\Settings\Database\CategoryRepository; -use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; @@ -79,9 +78,6 @@ private function repository(?string $category): CategoryRepository { $this->access->authorize($this->actor, Ability::View, new Subject($this->store->name, category: $category)); - $database = $this->store->database() - ?? throw new StoreNotWritable(sprintf('Store [%s] has no active database layer; categories are kept in the database.', $this->store->name)); - - return new CategoryRepository($database, $this->store->name); + return CategoryRepository::of($this->store); } } diff --git a/src/Console/PruneOrphansCommand.php b/src/Console/PruneOrphansCommand.php index 96e7a20..417227d 100644 --- a/src/Console/PruneOrphansCommand.php +++ b/src/Console/PruneOrphansCommand.php @@ -5,6 +5,7 @@ namespace Simtabi\Laranail\Settings\Console; use Simtabi\Laranail\Settings\Data\Actor; +use Simtabi\Laranail\Settings\Actions\FindOrphans; use Simtabi\Laranail\Settings\Actions\PruneOrphans; use Simtabi\Laranail\Console\Tools\Commands\Command; use Simtabi\Laranail\Settings\Exceptions\SettingsException; @@ -22,10 +23,10 @@ final class PruneOrphansCommand extends Command protected $description = 'Remove settings whose owner no longer exists'; - public function handle(PruneOrphans $prune): int + public function handle(PruneOrphans $prune, FindOrphans $find): int { try { - $found = $prune->find(); + $found = $find->handle(); foreach ($found['unmapped'] as $alias) { $this->warn(sprintf('Alias [%s] has no model in the morph map; its settings were not checked.', $alias)); diff --git a/src/Data/Scope.php b/src/Data/Scope.php index a7df723..29f0fe6 100644 --- a/src/Data/Scope.php +++ b/src/Data/Scope.php @@ -31,6 +31,40 @@ public static function forOwner(OwnerRef $owner): self return new self($owner->alias . ':' . $owner->id); } + /** The owner's scope, or `global` without one. */ + 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}. + */ + public static function fromString(string $value): ?self + { + if ($value === self::GLOBAL) { + return self::global(); + } + + $parts = explode(':', $value, 2); + + return count($parts) === 2 ? self::forOwner(new OwnerRef($parts[0], $parts[1])) : null; + } + + /** The owner this scope belongs to; null for `global`. */ + public function owner(): ?OwnerRef + { + if ($this->isGlobal()) { + return null; + } + + [$alias, $id] = explode(':', $this->value, 2); + + return new OwnerRef($alias, $id); + } + public function isGlobal(): bool { return $this->value === self::GLOBAL; diff --git a/src/Database/AuditRepository.php b/src/Database/AuditRepository.php new file mode 100644 index 0000000..fae0452 --- /dev/null +++ b/src/Database/AuditRepository.php @@ -0,0 +1,185 @@ +get($store) : $stores->default())->database() ?? $stores->default()->database(); + + return $database instanceof DatabaseDriver ? new self($database) : null; + } + + /** + * One row as an entry; a row missing a required column raises DriverFailure rather than + * inventing an entry. + * + * @param array $row + */ + public static function entry(array $row): AuditEntry + { + $text = static fn (string $column): ?string => is_string($row[$column] ?? null) ? $row[$column] : null; + $number = static fn (string $column): ?int => is_numeric($row[$column] ?? null) ? (int) $row[$column] : null; + $id = $text('id'); + $occurred = $text('occurred_at'); + $action = AuditAction::tryFrom($text('action') ?? ''); + $outcome = AuditOutcome::tryFrom($text('outcome') ?? ''); + $actorType = ActorType::tryFrom($text('actor_type') ?? ''); + $channel = Channel::tryFrom($text('channel') ?? ''); + + if ($id === null || $occurred === null || ! $action instanceof AuditAction || ! $outcome instanceof AuditOutcome || ! $actorType instanceof ActorType || ! $channel instanceof Channel) { + throw new DriverFailure(sprintf('Audit row [%s] is malformed.', $id ?? '?')); + } + + return new AuditEntry( + id: $id, + occurredAt: CarbonImmutable::parse($occurred), + action: $action, + outcome: $outcome, + store: $text('store'), + scope: $text('scope'), + key: $text('key'), + locale: $text('locale'), + versionFrom: $number('version_from'), + versionTo: $number('version_to'), + actorType: $actorType, + actorAlias: $text('actor_alias'), + actorId: $text('actor_id'), + channel: $channel, + ip: $text('ip'), + userAgent: $text('user_agent'), + requestId: $text('request_id'), + reason: $text('reason'), + meta: self::meta($text('meta')), + ); + } + + public function database(): DatabaseDriver + { + return $this->database; + } + + /** Write one entry. Its store names the store in an outage message only. */ + public function insert(AuditEntry $entry): void + { + $this->database->attempt(new StoreName($entry->store ?? 'audit'), fn (): bool => $this->table()->insert([ + 'id' => $entry->id, + 'occurred_at' => $entry->occurredAt, + 'action' => $entry->action->value, + 'outcome' => $entry->outcome->value, + 'store' => $entry->store, + 'scope' => $entry->scope, + 'key' => $entry->key, + 'locale' => $entry->locale, + 'version_from' => $entry->versionFrom, + 'version_to' => $entry->versionTo, + 'change_request' => null, + 'actor_type' => $entry->actorType->value, + 'actor_alias' => $entry->actorAlias, + 'actor_id' => $entry->actorId, + 'channel' => $entry->channel->value, + 'ip' => $entry->ip, + 'user_agent' => $entry->userAgent, + 'request_id' => $entry->requestId, + 'reason' => $entry->reason, + 'meta' => $entry->meta === [] ? null : Json::encode($entry->meta, 'An audit entry\'s meta'), + ] + $this->database->tenantColumns())); + } + + /** The current tenant's rows matching a filter, newest first. */ + public function query(AuditFilter $filter): Builder + { + $query = $this->database->scoped($this->table()); + + if ($filter->store instanceof StoreName) { + $query->where('store', $filter->store->value); + } + + foreach (['scope' => $filter->scope?->value, 'key' => $filter->key?->value, 'action' => $filter->action?->value, 'outcome' => $filter->outcome?->value] as $column => $value) { + if ($value !== null) { + $query->where($column, $value); + } + } + + if ($filter->since instanceof CarbonImmutable) { + $query->where('occurred_at', '>=', $filter->since); + } + + if ($filter->until instanceof CarbonImmutable) { + $query->where('occurred_at', '<=', $filter->until); + } + + 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. + */ + public function prune(CarbonImmutable $cutoff, StoreName $store): int + { + return $this->database->attempt($store, fn (): int => $this->table()->where('occurred_at', '<', $cutoff)->delete()); + } + + /** @return array */ + private static function meta(?string $json): array + { + if ($json === null) { + return []; + } + + try { + $decoded = json_decode($json, true, 4, JSON_THROW_ON_ERROR); + } catch (JsonException) { + return []; + } + + $meta = []; + + foreach (is_array($decoded) ? $decoded : [] as $key => $value) { + if (is_scalar($value) || $value === null) { + $meta[(string) $key] = $value; + } + } + + return $meta; + } + + private function table(): Builder + { + return $this->database->connection()->table($this->database->names()->audit()); + } +} diff --git a/src/Database/CategoryRepository.php b/src/Database/CategoryRepository.php index 0dbfc16..6adf077 100644 --- a/src/Database/CategoryRepository.php +++ b/src/Database/CategoryRepository.php @@ -4,18 +4,20 @@ namespace Simtabi\Laranail\Settings\Database; -use JsonException; use Carbon\CarbonImmutable; use Illuminate\Database\Query\Builder; +use Simtabi\Laranail\Settings\Stores\Store; use Simtabi\Laranail\Settings\Data\Category; use Simtabi\Laranail\Settings\Data\StoreName; use Simtabi\Laranail\Settings\Data\NewCategory; use Simtabi\Laranail\Settings\Data\CategorySlug; +use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; -use Simtabi\Laranail\Settings\Enums\TranslationsMode; +use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\CategoryCycle; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; use Simtabi\Laranail\Settings\Exceptions\UnknownCategory; +use Simtabi\Laranail\Settings\Exceptions\StoreNotWritable; use Simtabi\Laranail\Settings\Exceptions\CategoryStoreMismatch; /** @@ -35,6 +37,16 @@ public function __construct( private StoreName $store, ) {} + /** + * The categories of a store, on its active database layer. + * + * @throws StoreNotWritable when the store has none: categories are kept in the database + */ + public static function of(Store $store): self + { + return new self($store->requireDatabase('; categories are kept in the database.'), $store->name); + } + /** @throws UnknownCategory */ public function get(CategorySlug $slug): Category { @@ -67,13 +79,13 @@ public function all(): array id: $this->id($row['id'] ?? null), store: $this->store, slug: new CategorySlug($this->string($row['slug'] ?? null)), - title: $this->text($this->string($row['title'] ?? null)), + title: $this->translations()->text($this->string($row['title'] ?? null)), parent: isset($row['parent_id'], $slugs[$this->id($row['parent_id'])]) ? new CategorySlug($slugs[$this->id($row['parent_id'])]) : null, - description: is_string($row['description'] ?? null) ? $this->text($row['description']) : null, + description: is_string($row['description'] ?? null) ? $this->translations()->text($row['description']) : null, icon: is_string($row['icon'] ?? null) ? $row['icon'] : null, sortOrder: is_numeric($row['sort_order'] ?? null) ? (int) $row['sort_order'] : 0, - system: in_array($row['is_system'] ?? false, [true, 1, '1'], true), - titles: $this->texts($this->string($row['title'] ?? null)), + system: DatabaseValues::boolean($row['is_system'] ?? false), + titles: $this->translations()->texts($this->string($row['title'] ?? null)), ), $rows)); } @@ -87,8 +99,8 @@ public function create(NewCategory $category): Category $now = CarbonImmutable::now(); $columns = [ 'parent_id' => $parent, - 'title' => $this->encode($category->title, $category->translations), - 'description' => $category->description === null ? null : $this->encode($category->description), + 'title' => $this->translations()->store($category->title, $category->translations), + 'description' => $this->translations()->storeNullable($category->description), 'icon' => $category->icon, 'sort_order' => $category->sortOrder, 'is_system' => $category->system, @@ -116,7 +128,7 @@ public function create(NewCategory $category): Category /** @throws UnknownCategory */ public function rename(CategorySlug $slug, string $title): void { - $this->update($slug, ['title' => $this->encode($title, $this->get($slug)->titles)]); + $this->update($slug, ['title' => $this->translations()->store($title, $this->get($slug)->titles)]); } /** @@ -243,60 +255,10 @@ private function softDeletes(): bool return $this->database->shape()->categoriesSoftDeletes; } - private function json(): bool - { - return $this->database->shape()->translations === TranslationsMode::Json; - } - - /** - * A title or description as the column holds it: the text itself, or (json mode) a JSON map - * of locale to text with `''` for the text that applies to any locale. - * - * @param array $translations - */ - private function encode(string $text, array $translations = []): string + /** Titles and descriptions as `translations.mode` stores them (D-8). */ + private function translations(): Translations { - if (! $this->json()) { - return $text; - } - - try { - return json_encode(['' => $text] + $translations, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); - } catch (JsonException $exception) { - throw new DriverFailure('A category title could not be encoded.', 0, $exception); - } - } - - /** The text for any locale. */ - private function text(string $stored): string - { - $texts = $this->texts($stored); - - return $texts[''] ?? (string) reset($texts); - } - - /** @return array locale => text */ - private function texts(string $stored): array - { - if (! $this->json()) { - return ['' => $stored]; - } - - $decoded = json_decode($stored, true); - - if (! is_array($decoded) || $decoded === []) { - return ['' => $stored]; - } - - $texts = []; - - foreach ($decoded as $locale => $text) { - if (is_string($text)) { - $texts[(string) $locale] = $text; - } - } - - return $texts === [] ? ['' => $stored] : $texts; + return new Translations($this->database->shape()->translations); } /** The categories table, limited to the current tenant (column-mode tenancy). */ diff --git a/src/Database/DefinitionsRepository.php b/src/Database/DefinitionsRepository.php new file mode 100644 index 0000000..60550d9 --- /dev/null +++ b/src/Database/DefinitionsRepository.php @@ -0,0 +1,130 @@ +> + */ + public function runtimeRows(StoreName $store): array + { + $database = $this->database; + $names = $database->names(); + + return array_values($database->attempt($store, static fn (): array => $database->connection() + ->table($names->definitions() . ' as d') + ->leftJoin($names->categories() . ' as c', 'c.id', '=', 'd.category_id') + ->where('d.store', $store->value) + ->where('d.is_system', false) + ->get(['d.*', 'c.slug as category_slug']) + ->map(static fn (object $row): array => (array) $row) + ->all())); + } + + /** + * 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. + * + * @param list $definitions + * + * @return array{synced: int, removed: int, conflicts: list} + */ + public function sync(StoreName $store, array $definitions): array + { + $database = $this->database; + $table = static fn () => $database->connection()->table($database->names()->definitions())->where('store', $store->value); + $now = CarbonImmutable::now(); + $translations = new Translations($this->database->shape()->translations); + $synced = 0; + $conflicts = []; + $keys = []; + + foreach ($definitions as $definition) { + $keys[] = $definition->key->value; + $row = $table()->where('key', $definition->key->value)->first(['is_system']); + + if ($row !== null && ! DatabaseValues::boolean($row->is_system ?? false)) { + $conflicts[] = $store->value . '.' . $definition->key->value; + + continue; + } + + $columns = $this->columns($store, $definition, $translations) + ['updated_at' => $now]; + + if ($row === null) { + $table()->insert($columns + DatabaseDriver::newId($this->database->shape()->ids) + [ + 'store' => $store->value, + 'key' => $definition->key->value, + 'is_system' => true, + 'created_at' => $now, + ]); + } else { + $table()->where('key', $definition->key->value)->update($columns); + } + + $synced++; + } + + $removed = $table()->where('is_system', true)->whereNotIn('key', $keys === [] ? [''] : $keys)->delete(); + + return ['synced' => $synced, 'removed' => $removed, 'conflicts' => $conflicts]; + } + + /** @return array */ + private function columns(StoreName $store, Definition $definition, Translations $translations): array + { + $category = null; + + if ($definition->category !== null) { + $categories = $this->database->connection()->table($this->database->names()->categories()); + + // Definitions are shared by every tenant, so they link to the central categories (''). + if ($this->database->shape()->tenancy->hasColumn()) { + $categories->where('tenant', ''); + } + + $category = $categories->where('store', $store->value)->where('slug', $definition->category)->value('id'); + } + + return [ + 'slug' => $definition->key->slug(), + 'group' => $definition->group(), + 'category_id' => is_int($category) || is_string($category) ? $category : null, + 'type' => $definition->type, + // An encrypted setting's default stays in code: the table must not hold a readable copy. + 'default' => $definition->hasDefault && ! $definition->encrypted ? $this->encoder->encode($definition->key, $definition->default) : null, + 'label' => $translations->storeNullable($definition->label), + 'description' => $translations->storeNullable($definition->description), + 'rules' => Json::encode($definition->rules, 'A definition'), + 'is_encrypted' => $definition->encrypted, + 'is_public' => $definition->public, + 'is_locked' => $definition->locked, + 'inherits' => $definition->inherits, + 'overridable_by' => Json::encode($definition->overridableBy, 'A definition'), + ]; + } +} diff --git a/src/Database/SchemaInspector.php b/src/Database/SchemaInspector.php new file mode 100644 index 0000000..56518e9 --- /dev/null +++ b/src/Database/SchemaInspector.php @@ -0,0 +1,76 @@ +database->connection()->getSchemaBuilder()->hasTable($table); + } catch (Throwable) { + return null; + } + } + + /** + * The table's columns; null when the database could not be asked. + * + * @return list|null + */ + public function columns(string $table): ?array + { + try { + return array_values($this->database->connection()->getSchemaBuilder()->getColumnListing($table)); + } catch (Throwable) { + return null; + } + } + + /** The database type of the table's `id` column; null when there is none or it cannot be read. */ + public function idType(string $table): ?string + { + try { + $columns = $this->database->connection()->getSchemaBuilder()->getColumns($table); + } catch (Throwable) { + return null; + } + + foreach ($columns as $column) { + if (($column['name'] ?? null) === 'id') { + return (string) ($column['type_name'] ?? '?'); + } + } + + return null; + } + + /** Rows of a store's values table whose category link names another store (or none). */ + public function crossStoreCategoryLinks(StoreName $store): int + { + $database = $this->database; + + return $database->attempt($store, static fn (): int => $database->connection()->table($database->tableFor($store)) + ->whereNotNull('category_id') + ->where(static fn (Builder $query): Builder => $query->whereNull('category_store')->orWhere('category_store', '!=', $store->value)) + ->count()); + } +} diff --git a/src/Definitions/DatabaseDefinitions.php b/src/Definitions/DatabaseDefinitions.php index 8d00f05..44b581c 100644 --- a/src/Definitions/DatabaseDefinitions.php +++ b/src/Definitions/DatabaseDefinitions.php @@ -6,12 +6,16 @@ use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Stores\Store; +use Simtabi\Laranail\Settings\Support\Json; use Simtabi\Laranail\Settings\Data\Definition; +use Simtabi\Laranail\Settings\Support\Translations; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Simtabi\Laranail\Settings\Casting\CasterRegistry; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Enums\TranslationsMode; +use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Exceptions\InvalidDefinition; +use Simtabi\Laranail\Settings\Database\DefinitionsRepository; /** * The `database` definition source (D-6): rows of the optional definitions table that are not @@ -40,22 +44,14 @@ public function __construct( private readonly bool $enabled = true, ) {} - /** A label as text: itself, or (json mode) the entry for any locale, else the first one. */ + /** + * A label as text: itself, or (json mode) the entry for any locale, else the first one. + * + * @deprecated 0.1 Use {@see Translations::nullableText()}; this forwards to it and is removed in 1.0. + */ public static function localised(?string $stored, bool $json): ?string { - if ($stored === null || ! $json) { - return $stored; - } - - $decoded = json_decode($stored, true); - - if (! is_array($decoded)) { - return $stored; - } - - $text = $decoded[''] ?? reset($decoded); - - return is_string($text) ? $text : null; + return new Translations($json ? TranslationsMode::Json : TranslationsMode::Lang)->nullableText($stored); } public function find(Store $store, Key $key): ?Definition @@ -76,20 +72,12 @@ public function find(Store $store, Key $key): ?Definition /** @return array */ private function load(Store $store, DatabaseDriver $database): array { - $names = $database->names(); - $rows = $database->attempt($store->name, static fn (): array => $database->connection() - ->table($names->definitions() . ' as d') - ->leftJoin($names->categories() . ' as c', 'c.id', '=', 'd.category_id') - ->where('d.store', $store->name->value) - ->where('d.is_system', false) - ->get(['d.*', 'c.slug as category_slug']) - ->map(static fn (object $row): array => (array) $row) - ->all()); - $json = $database->shape()->translations === TranslationsMode::Json; + $rows = new DefinitionsRepository($database, $this->encoder)->runtimeRows($store->name); + $translations = new Translations($database->shape()->translations); $definitions = []; foreach ($rows as $row) { - $definition = $this->definition($store, $row, $json); + $definition = $this->definition($store, $row, $translations); $definitions[$definition->key->value] = $definition; } @@ -97,10 +85,10 @@ private function load(Store $store, DatabaseDriver $database): array } /** @param array $row */ - private function definition(Store $store, array $row, bool $json): Definition + private function definition(Store $store, array $row, Translations $translations): Definition { $text = static fn (string $column): ?string => is_string($row[$column] ?? null) && $row[$column] !== '' ? $row[$column] : null; - $flag = static fn (string $column): bool => in_array($row[$column] ?? false, [true, 1, '1'], true); + $flag = static fn (string $column): bool => DatabaseValues::boolean($row[$column] ?? false); $key = new Key($text('key') ?? throw new InvalidDefinition('A definitions row has no key.')); $type = $text('type'); @@ -121,10 +109,10 @@ private function definition(Store $store, array $row, bool $json): Definition encrypted: $flag('is_encrypted'), public: $flag('is_public'), locked: $flag('is_locked'), - inherits: $inherits === null ? null : in_array($inherits, [true, 1, '1'], true), - overridableBy: $this->strings($text('overridable_by')), - label: self::localised($text('label'), $json), - description: self::localised($text('description'), $json), + inherits: $inherits === null ? null : DatabaseValues::boolean($inherits), + overridableBy: Json::strings($text('overridable_by')), + label: $translations->nullableText($text('label')), + description: $translations->nullableText($text('description')), category: $text('category_slug'), group: $text('group'), ); @@ -134,16 +122,8 @@ private function definition(Store $store, array $row, bool $json): Definition private function rules(?string $json): array { return array_values(array_filter( - $this->strings($json), + Json::strings($json), fn (string $rule): bool => in_array(explode(':', $rule, 2)[0], $this->allowedRules, true), )); } - - /** @return list */ - private function strings(?string $json): array - { - $decoded = $json === null ? null : json_decode($json, true); - - return is_array($decoded) ? array_values(array_filter($decoded, is_string(...))) : []; - } } diff --git a/src/Drivers/DatabaseDriver.php b/src/Drivers/DatabaseDriver.php index eb0a84b..bea0c28 100644 --- a/src/Drivers/DatabaseDriver.php +++ b/src/Drivers/DatabaseDriver.php @@ -25,6 +25,7 @@ use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Database\StoreSchema; use Illuminate\Database\ConnectionResolverInterface; +use Simtabi\Laranail\Settings\Support\DatabaseValues; use Simtabi\Laranail\Settings\Contracts\DatabaseBacked; use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; @@ -392,12 +393,6 @@ public function attempt(StoreName $store, Closure $operation): mixed } } - /** Databases return booleans as bool, int or numeric string. */ - private function boolean(mixed $value): bool - { - return in_array($value, [true, 1, '1'], true); - } - /** 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 @@ -495,7 +490,8 @@ private function columns(StoreName $store, Record $record): array private function ownerColumns(StoreName $store, Scope $scope): array { $schema = $this->schemaOf($store); - [$alias, $id] = $scope->isGlobal() ? [null, null] : explode(':', $scope->value, 2); + $owner = $scope->owner(); + [$alias, $id] = $owner instanceof OwnerRef ? [$owner->alias, $owner->id] : [null, null]; if (! $schema->isDedicated()) { $shape = $this->shape(); @@ -619,27 +615,17 @@ private function record(array $row): Record locale: new Locale($locale), payload: $value, type: $type, - encrypted: $this->boolean($row['is_encrypted'] ?? false), - locked: $this->boolean($row['is_locked'] ?? false), + encrypted: DatabaseValues::boolean($row['is_encrypted'] ?? false), + locked: DatabaseValues::boolean($row['is_locked'] ?? false), version: (int) $version, writtenAt: is_string($updated) ? CarbonImmutable::parse($updated) : null, group: $group, - public: $this->boolean($row['is_public'] ?? false), + public: DatabaseValues::boolean($row['is_public'] ?? false), ); } private function scope(string $value): Scope { - if ($value === Scope::GLOBAL) { - return Scope::global(); - } - - $parts = explode(':', $value, 2); - - if (count($parts) !== 2) { - throw new DriverFailure(sprintf('A row in the settings table has a malformed scope [%s].', $value)); - } - - return new OwnerRef($parts[0], $parts[1])->scope(); + return Scope::fromString($value) ?? throw new DriverFailure(sprintf('A row in the settings table has a malformed scope [%s].', $value)); } } diff --git a/src/Providers/SettingsServiceProvider.php b/src/Providers/SettingsServiceProvider.php index aa862c6..3ed4f1f 100644 --- a/src/Providers/SettingsServiceProvider.php +++ b/src/Providers/SettingsServiceProvider.php @@ -40,6 +40,7 @@ use Simtabi\Laranail\Settings\Contracts\Settings; use Simtabi\Laranail\Settings\Contracts\Verifier; use Simtabi\Laranail\Settings\Enums\AuditOutcome; +use Simtabi\Laranail\Settings\Actions\FindOrphans; use Simtabi\Laranail\Settings\Audit\AutoAuditSink; use Simtabi\Laranail\Settings\Audit\NullAuditSink; use Simtabi\Laranail\Settings\Contracts\AuditSink; @@ -54,6 +55,7 @@ use Simtabi\Laranail\Settings\Database\SchemaShape; use Simtabi\Laranail\Settings\Stores\SettingWriter; use Simtabi\Laranail\Settings\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Support\ConfigValues; use Simtabi\Laranail\Settings\Support\ValueEncoder; use Illuminate\Contracts\Encryption\StringEncrypter; use Illuminate\Database\ConnectionResolverInterface; @@ -86,6 +88,7 @@ use Simtabi\Laranail\Package\Tools\Commands\InstallCommand; use Simtabi\Laranail\Settings\Authorization\GateAuthorizer; use Simtabi\Laranail\Settings\Exceptions\SettingsException; +use Simtabi\Laranail\Settings\Tenancy\TenantDiscriminators; use Simtabi\Laranail\Settings\Authorization\ChainAuthorizer; use Simtabi\Laranail\Settings\Contracts\TenantDiscriminator; use Simtabi\Laranail\Settings\Database\SchemaReadinessProbe; @@ -96,11 +99,9 @@ use Simtabi\Laranail\Settings\Definitions\DefinitionRegistry; use Simtabi\Laranail\Settings\Definitions\DatabaseDefinitions; use Simtabi\Laranail\Settings\Exceptions\InvalidConfiguration; -use Simtabi\Laranail\Settings\Tenancy\NullTenantDiscriminator; use Simtabi\Laranail\Settings\Authentication\GuardActorResolver; use Simtabi\Laranail\Settings\Actions\Categories\CategoryActions; use Simtabi\Laranail\Settings\Configuration\RuntimeConfiguration; -use Simtabi\Laranail\Settings\Tenancy\ClosureTenantDiscriminator; use Simtabi\Laranail\Settings\Authentication\SanctumActorResolver; use Simtabi\Laranail\Settings\Authorization\PermissionsAuthorizer; use Simtabi\Laranail\Settings\Verification\ActorTimestampVerifier; @@ -125,8 +126,6 @@ */ final class SettingsServiceProvider extends PackageServiceProvider { - private const string STANCL = 'Stancl\\Tenancy\\Tenancy'; - public function configurePackage(Package $package): void { $package @@ -339,6 +338,11 @@ static function (Store $store, Key $key, Scope $scope) use ($app): void { $app->make(AccessGuard::class), )); + $this->app->scoped(FindOrphans::class, static fn (Application $app): FindOrphans => new FindOrphans( + $app->make(StoreRegistry::class), + static fn (string $alias): ?string => Relation::getMorphedModel($alias), + )); + $this->app->scoped(PruneOrphans::class, static fn (Application $app): PruneOrphans => new PruneOrphans( $app->make(StoreRegistry::class), $app->make(StoreActions::class)->flush, @@ -488,58 +492,29 @@ private static function clock(): Closure private static function integer(Application $app, string $key, int $default): int { - $value = $app->make(Repository::class)->get($key, $default); - - return is_int($value) || (is_string($value) && ctype_digit($value)) ? (int) $value : $default; + return self::config($app)->integer($key, $default); } /** @return list */ private static function strings(Application $app, string $key): array { - return array_values(array_filter(self::array($app, $key), is_string(...))); + return self::config($app)->strings($key); } private static function string(Application $app, string $key, string $default): string { - $value = $app->make(Repository::class)->get($key, $default); - - return is_string($value) ? $value : $default; + return self::config($app)->string($key, $default); } /** @return array */ private static function array(Application $app, string $key): array { - $value = $app->make(Repository::class)->get($key, []); - - return is_array($value) ? $value : []; - } - - /** stancl/tenancy's current tenant key, or null when tenancy is not initialised. */ - private static function stanclTenant(Application $app): mixed - { - $tenancy = $app->make(self::STANCL); - - if (! is_object($tenancy) || ! property_exists($tenancy, 'initialized') || $tenancy->initialized !== true || ! property_exists($tenancy, 'tenant')) { - return null; - } - - $tenant = $tenancy->tenant; - - return is_object($tenant) && method_exists($tenant, 'getTenantKey') ? $tenant->getTenantKey() : null; + return self::config($app)->array($key); } - /** spatie/laravel-multitenancy's current tenant key (its container binding), or null. */ - private static function spatieTenant(Application $app): mixed + private static function config(Application $app): ConfigValues { - $binding = $app->make(Repository::class)->get('multitenancy.current_tenant_container_key', 'currentTenant'); - - if (! is_string($binding) || ! $app->bound($binding)) { - return null; - } - - $tenant = $app->make($binding); - - return is_object($tenant) && method_exists($tenant, 'getKey') ? $tenant->getKey() : null; + return new ConfigValues($app->make(Repository::class)); } /** @@ -551,25 +526,10 @@ private static function spatieTenant(Application $app): mixed private function registerTenancy(): void { $this->app->scoped(TenantDiscriminator::class, static function (Application $app): TenantDiscriminator { - $driver = $app->make(Repository::class)->get('laranail.settings.tenancy.discriminator', 'auto'); - $path = 'laranail.settings.tenancy.discriminator'; - - if ($driver === 'auto') { - $driver = match (true) { - class_exists(self::STANCL) => 'stancl', - class_exists('Spatie\\Multitenancy\\Models\\Tenant') => 'spatie', - default => 'null', - }; - } + $binding = $app->make(Repository::class)->get('multitenancy.current_tenant_container_key', 'currentTenant'); - return match ($driver) { - 'null', null => new NullTenantDiscriminator, - 'stancl' => class_exists(self::STANCL) - ? new ClosureTenantDiscriminator(static fn (): mixed => self::stanclTenant($app)) - : throw new InvalidConfiguration($path . ': [stancl] needs stancl/tenancy.'), - 'spatie' => new ClosureTenantDiscriminator(static fn (): mixed => self::spatieTenant($app)), - default => self::instance($app, $driver, TenantDiscriminator::class, $path), - }; + return new TenantDiscriminators($app, is_string($binding) ? $binding : 'currentTenant') + ->make($app->make(Repository::class)->get('laranail.settings.tenancy.discriminator', 'auto')); }); $app = $this->app; diff --git a/src/SettingsManager.php b/src/SettingsManager.php index 174ff61..91bed78 100644 --- a/src/SettingsManager.php +++ b/src/SettingsManager.php @@ -315,7 +315,7 @@ private function storeActions(): StoreActions private function scope(): Scope { - return $this->owner?->scope() ?? Scope::global(); + return Scope::of($this->owner); } /** diff --git a/src/Stores/SettingWriter.php b/src/Stores/SettingWriter.php index 8192c3a..206382a 100644 --- a/src/Stores/SettingWriter.php +++ b/src/Stores/SettingWriter.php @@ -283,6 +283,6 @@ private function ownerAllowed(Store $store, ?OwnerRef $owner, ?Definition $defin private function scope(?OwnerRef $owner): Scope { - return $owner?->scope() ?? Scope::global(); + return Scope::of($owner); } } diff --git a/src/Stores/Store.php b/src/Stores/Store.php index 3e825c5..3746ca8 100644 --- a/src/Stores/Store.php +++ b/src/Stores/Store.php @@ -63,6 +63,17 @@ public function database(): ?DatabaseDriver return null; } + /** + * 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`). + * + * @throws StoreNotWritable + */ + public function requireDatabase(string $why): DatabaseDriver + { + return $this->database() ?? throw new StoreNotWritable(sprintf('Store [%s] has no active database layer%s', $this->name, $why)); + } + /** * 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. diff --git a/src/Stores/StoreRegistry.php b/src/Stores/StoreRegistry.php index 63d361c..5059175 100644 --- a/src/Stores/StoreRegistry.php +++ b/src/Stores/StoreRegistry.php @@ -12,6 +12,7 @@ use Simtabi\Laranail\Settings\Enums\DriverType; use Simtabi\Laranail\Settings\Database\SchemaNames; use Simtabi\Laranail\Settings\Database\StoreSchema; +use Simtabi\Laranail\Settings\Support\ConfigValues; use Simtabi\Laranail\Settings\Drivers\DriverFactory; use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; use Simtabi\Laranail\Settings\Exceptions\UnknownStore; @@ -259,16 +260,6 @@ private function locksOverridable(mixed $locks, string $path): bool /** @return list */ private function strings(mixed $value, string $path): array { - if (! is_array($value)) { - throw new InvalidConfiguration($path . ': a list of strings is required.'); - } - - $strings = array_values(array_filter($value, is_string(...))); - - if (count($strings) !== count($value)) { - throw new InvalidConfiguration($path . ': a list of strings is required.'); - } - - return $strings; + return ConfigValues::listOfStrings($value, $path); } } diff --git a/src/Support/AuditedTransaction.php b/src/Support/AuditedTransaction.php new file mode 100644 index 0000000..2d8de6c --- /dev/null +++ b/src/Support/AuditedTransaction.php @@ -0,0 +1,84 @@ +})|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 + * + * @return T + */ + public function run( + Store $store, + AuditAction $action, + Subject $subject, + ?Actor $actor, + Closure $work, + ?Closure $allowed = null, + ?Closure $then = null, + array $meta = [], + ?string $reason = null, + ): mixed { + try { + return $store->transaction(function () use ($work, $allowed, $then, $action, $subject, $actor, $meta, $reason): mixed { + $result = $work(); + $details = $allowed instanceof Closure ? $allowed($result) : []; + + $this->access->auditor()->record( + $action, + AuditOutcome::Allowed, + $subject, + $actor, + $reason, + $details['from'] ?? null, + $details['to'] ?? null, + $meta + ($details['meta'] ?? []), + ); + + if ($then instanceof Closure) { + $then($result); + } + + return $result; + }); + } catch (SettingsException $exception) { + try { + $this->access->auditor()->record($action, AuditOutcome::Failed, $subject, $actor, $reason, meta: $meta + ['error' => $exception::class]); + } catch (SettingsException) { + // The caller is told about the original failure below; nothing else to do here. + } + + throw $exception; + } + } +} diff --git a/src/Support/ConfigValues.php b/src/Support/ConfigValues.php new file mode 100644 index 0000000..2b82a93 --- /dev/null +++ b/src/Support/ConfigValues.php @@ -0,0 +1,69 @@ + + */ + public static function listOfStrings(mixed $value, string $path): array + { + if (! is_array($value)) { + throw new InvalidConfiguration($path . ': a list of strings is required.'); + } + + $strings = array_values(array_filter($value, is_string(...))); + + if (count($strings) !== count($value)) { + throw new InvalidConfiguration($path . ': a list of strings is required.'); + } + + return $strings; + } + + public function string(string $key, string $default): string + { + $value = $this->config->get($key, $default); + + return is_string($value) ? $value : $default; + } + + /** An integer, or a string of digits; anything else is the default. */ + public function integer(string $key, int $default): int + { + $value = $this->config->get($key, $default); + + return is_int($value) || (is_string($value) && ctype_digit($value)) ? (int) $value : $default; + } + + /** @return array the array at `$key`, or [] */ + public function array(string $key): array + { + $value = $this->config->get($key, []); + + return is_array($value) ? $value : []; + } + + /** @return list the strings of the array at `$key` (other entries dropped) */ + public function strings(string $key): array + { + return array_values(array_filter($this->array($key), is_string(...))); + } +} diff --git a/src/Support/DatabaseValues.php b/src/Support/DatabaseValues.php new file mode 100644 index 0000000..0771ede --- /dev/null +++ b/src/Support/DatabaseValues.php @@ -0,0 +1,17 @@ + $value + * @param string $what what is being encoded, for the error (`A definition`, `An audit entry's meta`) + * + * @throws DriverFailure + */ + public static function encode(array $value, string $what): string + { + try { + return json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + } catch (JsonException $exception) { + throw new DriverFailure($what . ' could not be encoded.', 0, $exception); + } + } + + /** + * A JSON list of strings, or [] for null, invalid JSON or anything that is not a list of + * strings (non-string entries are dropped). + * + * @return list + */ + public static function strings(?string $json): array + { + $decoded = $json === null ? null : json_decode($json, true); + + return is_array($decoded) ? array_values(array_filter($decoded, is_string(...))) : []; + } +} diff --git a/src/Support/RecordSerializer.php b/src/Support/RecordSerializer.php index cc6c32a..569c3d2 100644 --- a/src/Support/RecordSerializer.php +++ b/src/Support/RecordSerializer.php @@ -9,13 +9,12 @@ use Simtabi\Laranail\Settings\Data\Scope; use Simtabi\Laranail\Settings\Data\Locale; use Simtabi\Laranail\Settings\Data\Record; -use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Exceptions\DriverFailure; /** * Converts records to and from the plain arrays file layers store. */ -final class RecordSerializer +final readonly class RecordSerializer { /** @return array */ public function toArray(Record $record): array @@ -64,16 +63,6 @@ public function fromArray(array $row, string $source): Record private function scope(string $value, string $source): Scope { - if ($value === Scope::GLOBAL) { - return Scope::global(); - } - - $parts = explode(':', $value, 2); - - if (count($parts) !== 2) { - throw new DriverFailure(sprintf('A record in [%s] has a malformed scope.', $source)); - } - - return new OwnerRef($parts[0], $parts[1])->scope(); + return Scope::fromString($value) ?? throw new DriverFailure(sprintf('A record in [%s] has a malformed scope.', $source)); } } diff --git a/src/Support/Translations.php b/src/Support/Translations.php new file mode 100644 index 0000000..43deec1 --- /dev/null +++ b/src/Support/Translations.php @@ -0,0 +1,87 @@ +mode === TranslationsMode::Json; + } + + /** + * The text as the column holds it. + * + * @param array $translations locale => text (json mode only) + */ + public function store(string $text, array $translations = []): string + { + return $this->isJson() ? Json::encode(['' => $text] + $translations, 'A title or description') : $text; + } + + /** {@see store()} for a nullable column: null stays null. */ + public function storeNullable(?string $text): ?string + { + return $text === null ? null : $this->store($text); + } + + /** The text for any locale: the `''` entry, else the first text, else the stored value as is. */ + public function text(string $stored): string + { + $texts = $this->texts($stored); + + if (isset($texts[''])) { + return $texts['']; + } + + foreach ($texts as $text) { + return $text; + } + + return $stored; + } + + /** {@see text()} for a nullable column: null stays null. */ + public function nullableText(?string $stored): ?string + { + return $stored === null ? null : $this->text($stored); + } + + /** + * Every text by locale; `['' => stored]` under `lang`, or when the stored value is not a + * JSON map with at least one text. + * + * @return array + */ + public function texts(string $stored): array + { + if (! $this->isJson()) { + return ['' => $stored]; + } + + $decoded = json_decode($stored, true); + $texts = []; + + foreach (is_array($decoded) ? $decoded : [] as $locale => $text) { + if (is_string($text)) { + $texts[(string) $locale] = $text; + } + } + + return $texts === [] ? ['' => $stored] : $texts; + } +} diff --git a/src/Support/ValueEncoder.php b/src/Support/ValueEncoder.php index 7cba23b..09533e1 100644 --- a/src/Support/ValueEncoder.php +++ b/src/Support/ValueEncoder.php @@ -12,7 +12,7 @@ * Encodes values as JSON for storage. A stored null becomes the string `null`, which keeps it * distinct from "no value" (a null payload). */ -final class ValueEncoder +final readonly class ValueEncoder { private const int FLAGS = JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; diff --git a/src/Tenancy/TenantDiscriminators.php b/src/Tenancy/TenantDiscriminators.php new file mode 100644 index 0000000..8e2a753 --- /dev/null +++ b/src/Tenancy/TenantDiscriminators.php @@ -0,0 +1,87 @@ + 'stancl', + class_exists(self::SPATIE) => 'spatie', + default => 'null', + }; + } + + return match ($driver) { + 'null', null => new NullTenantDiscriminator, + 'stancl' => class_exists(self::STANCL) + ? new ClosureTenantDiscriminator(fn (): mixed => $this->stancl()) + : throw new InvalidConfiguration(self::PATH . ': [stancl] needs stancl/tenancy.'), + 'spatie' => new ClosureTenantDiscriminator(fn (): mixed => $this->spatie()), + default => $this->custom($driver), + }; + } + + /** stancl/tenancy's current tenant key, or null when tenancy is not initialised. */ + private function stancl(): mixed + { + $tenancy = $this->container->make(self::STANCL); + + if (! is_object($tenancy) || ! property_exists($tenancy, 'initialized') || $tenancy->initialized !== true || ! property_exists($tenancy, 'tenant')) { + return null; + } + + $tenant = $tenancy->tenant; + + return is_object($tenant) && method_exists($tenant, 'getTenantKey') ? $tenant->getTenantKey() : null; + } + + /** spatie/laravel-multitenancy's current tenant key (its container binding), or null. */ + private function spatie(): mixed + { + if (! $this->container->bound($this->spatieBinding)) { + return null; + } + + $tenant = $this->container->make($this->spatieBinding); + + return is_object($tenant) && method_exists($tenant, 'getKey') ? $tenant->getKey() : null; + } + + private function custom(mixed $class): TenantDiscriminator + { + if (! is_string($class) || ! class_exists($class) || ! is_subclass_of($class, TenantDiscriminator::class)) { + throw new InvalidConfiguration(sprintf('%s: [%s] is not a built-in name or a class implementing %s.', self::PATH, is_scalar($class) ? $class : get_debug_type($class), TenantDiscriminator::class)); + } + + $instance = $this->container->make($class); + + return $instance instanceof TenantDiscriminator ? $instance : throw new InvalidConfiguration(sprintf('%s: [%s] did not build a %s.', self::PATH, $class, TenantDiscriminator::class)); + } +} diff --git a/tests/Arch/LayeringTest.php b/tests/Arch/LayeringTest.php new file mode 100644 index 0000000..4522246 --- /dev/null +++ b/tests/Arch/LayeringTest.php @@ -0,0 +1,119 @@ + path relative to src/ => contents, for the PHP files under a src/ directory */ +function sourceFiles(string $directory): array +{ + $root = dirname(__DIR__, 2) . '/src/'; + $files = []; + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root . $directory, FilesystemIterator::SKIP_DOTS)); + + foreach ($iterator as $file) { + if ($file instanceof SplFileInfo && $file->getExtension() === 'php') { + $files[substr($file->getPathname(), strlen($root))] = (string) file_get_contents($file->getPathname()); + } + } + + ksort($files); + + return $files; +} + +/** @return class-string the class a src/ file declares */ +function classOf(string $path): string +{ + return 'Simtabi\\Laranail\\Settings\\' . str_replace(['/', '.php'], ['\\', ''], $path); +} + +/** Actions with more than handle() public, and why. */ +const ACTION_EXEMPTIONS = [ + 'Actions\\WriteGuard' => 'run(): the guard every write action runs through; not an intent of its own', + 'Actions\\Categories\\CategoryGuard' => 'run(): the guard every category action runs through', + 'Actions\\SettingActions' => 'a bundle of the write actions for entry points (using())', + 'Actions\\StoreActions' => 'a bundle of the store actions for entry points', + 'Actions\\Categories\\CategoryActions' => 'a bundle of the category actions for entry points (using())', + 'Actions\\QueryAudit' => 'get(), cursor(), paginate(): one authorized read in three result shapes, part of the public API', + 'Actions\\PruneOrphans' => 'find(): deprecated in 0.1, forwards to FindOrphans, removed in 1.0', +]; + +it('gives every action handle() as its only public method', function (): void { + $files = sourceFiles('Actions'); + $offenders = []; + + foreach (array_keys($files) as $path) { + $class = new ReflectionClass(classOf($path)); + $public = array_values(array_filter( + array_map(static fn (ReflectionMethod $method): string => $method->getName(), $class->getMethods(ReflectionMethod::IS_PUBLIC)), + static fn (string $name): bool => $name !== '__construct' && ! str_starts_with($name, '__'), + )); + $name = substr($class->getName(), strlen('Simtabi\\Laranail\\Settings\\')); + + if ($public !== ['handle']) { + $offenders[$name] = $public; + } + } + + expect(count($files))->toBeGreaterThanOrEqual(23) + ->and(array_keys(array_diff_key($offenders, ACTION_EXEMPTIONS)))->toBe([]) + // An exemption that no longer needs to be one is stale. + ->and(array_keys(array_diff_key(ACTION_EXEMPTIONS, $offenders)))->toBe([]); +}); + +it('keeps database access out of actions', function (): void { + $files = sourceFiles('Actions'); + $offenders = array_keys(array_filter($files, static fn (string $code): bool => preg_match('/->connection\(\)|getSchemaBuilder\(|DB::/', $code) === 1)); + + expect(count($files))->toBeGreaterThanOrEqual(23) + ->and($offenders)->toBe([]); +}); + +it('lets only entry points depend on actions', function (): void { + $entryPoints = ['SettingsManager.php', 'Providers/', 'Facades/', 'Console/', 'Categories/CategoryManager.php', 'Audit/AuditQuery.php']; + $files = sourceFiles(''); + $offenders = []; + + foreach ($files as $path => $code) { + if (str_starts_with($path, 'Actions/') || array_any($entryPoints, static fn (string $entry): bool => str_starts_with($path, $entry))) { + continue; + } + + if (str_contains($code, 'use Simtabi\\Laranail\\Settings\\Actions\\')) { + $offenders[] = $path; + } + } + + expect(count($files))->toBeGreaterThanOrEqual(200) + ->and($offenders)->toBe([]); +}); + +it('keeps support classes free of mutable state', function (): void { + $exempt = ['Support\\LaravelValueEncrypter' => 'resolves the application encrypter lazily and keeps it (a contract adapter)']; + $files = sourceFiles('Support'); + $mutable = []; + + foreach (array_keys($files) as $path) { + $class = new ReflectionClass(classOf($path)); + + if (! $class->isReadOnly()) { + $mutable[] = substr($class->getName(), strlen('Simtabi\\Laranail\\Settings\\')); + } + } + + expect(count($files))->toBeGreaterThanOrEqual(10) + ->and(array_values(array_diff($mutable, array_keys($exempt))))->toBe([]) + ->and(array_values(array_diff(array_keys($exempt), $mutable)))->toBe([]); +}); diff --git a/tests/Feature/Database/CommandsTest.php b/tests/Feature/Database/CommandsTest.php index 122be35..4a016da 100644 --- a/tests/Feature/Database/CommandsTest.php +++ b/tests/Feature/Database/CommandsTest.php @@ -15,7 +15,9 @@ // 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. -pest()->group('shared-app'); +// mutation-excluded: Pest's parallel runner honours only the first --exclude-group, so every group +// the mutation job leaves out also carries this one. +pest()->group('shared-app', 'mutation-excluded'); /** @return list */ function settingsMigrations(): array diff --git a/tests/Feature/Database/MigrationTest.php b/tests/Feature/Database/MigrationTest.php index 513fbe8..cd26450 100644 --- a/tests/Feature/Database/MigrationTest.php +++ b/tests/Feature/Database/MigrationTest.php @@ -5,6 +5,11 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Migrations\Migration; +use Simtabi\Laranail\Settings\Database\SchemaNames; +use Simtabi\Laranail\Settings\Stores\StoreRegistry; +use Simtabi\Laranail\Settings\Drivers\DatabaseDriver; +use Simtabi\Laranail\Settings\Contracts\ReadinessProbe; +use Simtabi\Laranail\Settings\Database\SchemaInspector; /* * The package's one migration: every table, in dependency order, for every recorded database @@ -86,3 +91,25 @@ function packageMigration(): Migration expect(Schema::hasTable('settings_definitions'))->toBeFalse() ->and(Schema::hasTable('settings_categories'))->toBeFalse(); }); + +it('reports nothing it cannot look at, rather than a finding', function (): void { + config()->set('database.connections.unreachable', ['driver' => 'sqlite', 'database' => sys_get_temp_dir() . '/laranail-missing-' . bin2hex(random_bytes(4)) . '/db.sqlite', 'prefix' => '']); + useDatabase(); + $inspector = new SchemaInspector(new DatabaseDriver( + app('db'), + 'unreachable', + new SchemaNames, + null, + true, + static fn (): ReadinessProbe => app(ReadinessProbe::class), + )); + $live = new SchemaInspector(app(StoreRegistry::class)->default()->requireDatabase('')); + + expect($inspector->hasTable('settings'))->toBeNull() + ->and($inspector->columns('settings'))->toBeNull() + ->and($inspector->idType('settings'))->toBeNull() + ->and($live->hasTable('settings'))->toBeTrue() + ->and($live->idType('settings'))->not->toBeNull() + ->and($live->idType('settings_audit'))->not->toBeNull() + ->and($live->idType('no_such_table'))->toBeNull(); +}); diff --git a/tests/Feature/Database/OwnersTest.php b/tests/Feature/Database/OwnersTest.php index 913898f..5a4de87 100644 --- a/tests/Feature/Database/OwnersTest.php +++ b/tests/Feature/Database/OwnersTest.php @@ -9,6 +9,7 @@ use Simtabi\Laranail\Settings\Data\OwnerRef; use Simtabi\Laranail\Settings\Enums\Ability; use Simtabi\Laranail\Settings\Actions\PruneAudit; +use Simtabi\Laranail\Settings\Actions\FindOrphans; use Simtabi\Laranail\Settings\Actions\PruneOrphans; use Illuminate\Database\Eloquent\Relations\Relation; use Simtabi\Laranail\Settings\Exceptions\AccessDenied; @@ -142,6 +143,18 @@ ->and(DB::table('settings_audit')->where('action', 'prune')->where('outcome', 'denied')->count())->toBe(1); }); +it('finds orphans with FindOrphans, and through the deprecated PruneOrphans::find()', function (): void { + $gone = SettingsOwner::query()->create(); + $gone->settings()->set('ui.theme', 'dark'); + SettingsOwner::query()->whereKey($gone->id)->delete(); + + $found = app(FindOrphans::class)->handle(); + + expect(array_map(static fn (OwnerRef $owner): string => $owner->scope()->value, $found['orphans']['settings'] ?? []))->toBe(['owner:' . $gone->id]) + ->and(app(PruneOrphans::class)->find())->toEqual($found) + ->and(DB::table('settings')->count())->toBe(1); +}); + it('needs prune to prune the audit trail with an actor', function (): void { $prune = app(PruneAudit::class); $actor = Actor::user(user()); diff --git a/tests/Feature/Database/SchemaMatrixTest.php b/tests/Feature/Database/SchemaMatrixTest.php index 67a326e..69e114b 100644 --- a/tests/Feature/Database/SchemaMatrixTest.php +++ b/tests/Feature/Database/SchemaMatrixTest.php @@ -67,7 +67,7 @@ function switchShapes(): array expect(count($shapes))->toBe(getenv('LARANAIL_SETTINGS_MATRIX') === 'full' ? 1152 : 10) ->and(count($all))->toBe(177) ->and(array_diff_key($all, $covered))->toBe([]); -})->group('matrix'); +})->group('matrix', 'mutation-excluded'); it('runs every shape end to end and reports no drift', function (array $shape): void { $dedicated = $shape['mode'] === 'dedicated'; @@ -142,4 +142,4 @@ function switchShapes(): array })->with(fn (): array => array_map( static fn (array $shape): array => [$shape], array_combine(array_map(static fn (array $shape): string => implode(',', array_map(static fn (mixed $value): string => is_bool($value) ? ($value ? 'on' : 'off') : $value, $shape)), switchShapes()), switchShapes()), -))->group('matrix'); +))->group('matrix', 'mutation-excluded'); diff --git a/tests/Feature/Database/SchemaShapeTest.php b/tests/Feature/Database/SchemaShapeTest.php index 78e4cb5..2fdc046 100644 --- a/tests/Feature/Database/SchemaShapeTest.php +++ b/tests/Feature/Database/SchemaShapeTest.php @@ -15,7 +15,9 @@ // 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. -pest()->group('shared-app'); +// mutation-excluded: Pest's parallel runner honours only the first --exclude-group, so every group +// the mutation job leaves out also carries this one. +pest()->group('shared-app', 'mutation-excluded'); function shapes(): SchemaShapeRepository { diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index 8d698e2..d588a3f 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -6,7 +6,9 @@ // 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. -pest()->group('shared-app'); +// mutation-excluded: Pest's parallel runner honours only the first --exclude-group, so every group +// the mutation job leaves out also carries this one. +pest()->group('shared-app', 'mutation-excluded'); beforeEach(function (): void { File::delete(config_path('laranail/settings.php')); diff --git a/tests/Unit/SupportTest.php b/tests/Unit/SupportTest.php new file mode 100644 index 0000000..93a5c10 --- /dev/null +++ b/tests/Unit/SupportTest.php @@ -0,0 +1,81 @@ +store('Mail', ['fr' => 'Courrier']))->toBe('Mail') + ->and($lang->texts('Mail'))->toBe(['' => 'Mail']) + ->and($lang->isJson())->toBeFalse() + ->and($json->store('Mail/É', ['fr' => 'Courrier']))->toBe('{"":"Mail/É","fr":"Courrier"}') + ->and($json->text('{"":"Mail","fr":"Courrier"}'))->toBe('Mail') + ->and($json->text('{"fr":"Courrier","de":"Post"}'))->toBe('Courrier') + ->and($json->texts('{"":"Mail","fr":3}'))->toBe(['' => 'Mail']) + ->and($json->text('not json'))->toBe('not json') + ->and($json->text('{"fr":3}'))->toBe('{"fr":3}') + ->and($json->storeNullable(null))->toBeNull() + ->and($json->nullableText(null))->toBeNull() + ->and($json->nullableText('{"":"Mail"}'))->toBe('Mail') + // The deprecated helper forwards. + ->and(DatabaseDefinitions::localised('{"":"Mail"}', true))->toBe('Mail') + ->and(DatabaseDefinitions::localised('{"":"Mail"}', false))->toBe('{"":"Mail"}'); +}); + +it('encodes JSON with one set of flags and names what failed', function (): void { + expect(Json::encode(['a/b' => 'É'], 'A thing'))->toBe('{"a/b":"É"}') + ->and(fn (): string => Json::encode(['x' => NAN], 'A definition'))->toThrow(DriverFailure::class, 'A definition could not be encoded.') + ->and(Json::strings('["a",1,"b"]'))->toBe(['a', 'b']) + ->and(Json::strings('{"x":"a"}'))->toBe(['a']) + ->and(Json::strings('oops'))->toBe([]) + ->and(Json::strings(null))->toBe([]); +}); + +it('reads boolean columns however the driver returns them', function (mixed $value, bool $expected): void { + expect(DatabaseValues::boolean($value))->toBe($expected); +})->with([[true, true], [1, true], ['1', true], [false, false], [0, false], ['0', false], [null, false], ['true', false]]); + +it('parses stored scopes and names their owner', function (): void { + $owner = new OwnerRef('user', 42); + + expect(Scope::of(null)->value)->toBe('global') + ->and(Scope::of($owner)->value)->toBe('user:42') + ->and(Scope::fromString('global')?->isGlobal())->toBeTrue() + ->and(Scope::fromString('user:42')?->owner()?->alias)->toBe('user') + ->and(Scope::fromString('user:42')?->owner()?->id)->toBe('42') + ->and(Scope::fromString('nocolon'))->toBeNull() + ->and(Scope::global()->owner())->toBeNull() + ->and(fn (): ?Scope => Scope::fromString('App\\Models\\User:1'))->toThrow(InvalidIdentifier::class); +}); + +it('reads configuration leniently, and lists strictly', function (): void { + $config = new ConfigValues(new Repository([ + 'a' => ['name' => 'x', 'n' => '12', 'bad' => 1.5, 'list' => ['x', 2, 'y'], 'scalar' => 'no'], + ])); + + expect($config->string('a.name', 'd'))->toBe('x') + ->and($config->string('a.n', 'd'))->toBe('12') + ->and($config->string('a.bad', 'd'))->toBe('d') + ->and($config->integer('a.n', 0))->toBe(12) + ->and($config->integer('a.bad', 7))->toBe(7) + ->and($config->integer('a.missing', 7))->toBe(7) + ->and($config->array('a.scalar'))->toBe([]) + ->and($config->strings('a.list'))->toBe(['x', 'y']) + ->and(ConfigValues::listOfStrings(['x', 'y'], 'p'))->toBe(['x', 'y']) + ->and(fn (): array => ConfigValues::listOfStrings(['x', 2], 'p.q'))->toThrow(InvalidConfiguration::class, 'p.q: a list of strings is required.') + ->and(fn (): array => ConfigValues::listOfStrings('x', 'p.q'))->toThrow(InvalidConfiguration::class, 'p.q'); +});