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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions .github/workflows/static-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 2 additions & 6 deletions database/factories/SettingCategoryFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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<string, mixed> */
Expand Down
16 changes: 16 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
35 changes: 15 additions & 20 deletions src/Actions/Categories/CategoryGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
);
}
}
38 changes: 12 additions & 26 deletions src/Actions/DiagnoseSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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]));
Expand All @@ -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
Expand Down Expand Up @@ -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.')
Expand Down
15 changes: 7 additions & 8 deletions src/Actions/FindForeignTables.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
}
}
Expand Down
93 changes: 93 additions & 0 deletions src/Actions/FindOrphans.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Actions;

use Closure;
use Illuminate\Database\Eloquent\Model;
use Simtabi\Laranail\Settings\Stores\Store;
use Simtabi\Laranail\Settings\Data\OwnerRef;
use Simtabi\Laranail\Settings\Stores\StoreRegistry;
use Simtabi\Laranail\Settings\Drivers\DatabaseDriver;

/**
* Find the settings of owners that no longer exist (G-7): rows left by bulk deletes, which fire
* no model events. For each store's owner aliases it lists the owner scopes in the database
* layer and asks the aliased model which ids still exist, soft-deleted ones included (a
* soft-deleted owner keeps its settings for a restore). An alias with no model in the morph map
* is reported, never guessed at. Read-only; {@see PruneOrphans} removes what it finds.
*/
final readonly class FindOrphans
{
/** @param Closure(string): ?string $models the model class of a morph alias (the morph map) */
public function __construct(
private StoreRegistry $stores,
private Closure $models,
) {}

/**
* The orphaned owners per store, and the aliases no model answers for.
*
* @return array{orphans: array<string, list<OwnerRef>>, unmapped: list<string>}
*/
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> $model
*
* @return list<OwnerRef>
*/
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;
}
}
Loading
Loading