From be51f0506746847cec5e4c01dc9a8c768cd97344 Mon Sep 17 00:00:00 2001 From: Imani Manyara <19682005+imanimanyara@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:03:37 -0500 Subject: [PATCH] Throw SettingsMisuse for calls the package cannot serve The five plain LogicException throws become SettingsMisuse, which still extends LogicException, so existing catch blocks keep working. A new SettingsError interface, implemented by SettingsMisuse and SettingsException, lets one catch take every settings exception. A source scan keeps bare LogicException out of src; it failed on the old code first. --- CHANGELOG.md | 10 +++ docs/tools/exceptions.md | 21 +++++- docs/tools/settings-api.md | 4 +- src/Data/Lookup.php | 8 +- src/Exceptions/SettingsError.php | 14 ++++ src/Exceptions/SettingsException.php | 7 +- src/Exceptions/SettingsMisuse.php | 16 ++++ src/Facades/Settings.php | 4 +- src/SettingsManager.php | 4 +- src/Typed/SettingsMigration.php | 4 +- tests/Feature/MisuseTest.php | 106 +++++++++++++++++++++++++++ 11 files changed, 179 insertions(+), 19 deletions(-) create mode 100644 src/Exceptions/SettingsError.php create mode 100644 src/Exceptions/SettingsMisuse.php create mode 100644 tests/Feature/MisuseTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d3ec03f..b099f70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 still applies. An architecture test now refuses `now()` and `today()` outside the providers and facades. +### Added + +- `SettingsError`, an interface every exception the package throws implements, so one + `catch (SettingsError $e)` takes them all. +- `SettingsMisuse`, a `LogicException` that also implements `SettingsError`, for a call the package + cannot serve: `value()` on a missing or redacted lookup, `flush()` without `for($owner)`, + `Settings::fake()` with no application, and a settings migration before the provider is + registered. These threw a plain `LogicException` before; a `catch (LogicException $e)` still + catches them, and the messages are unchanged. + ## [0.1.0] - 2026-11-14 The first public release. `Added` describes the package; `Changed`, `Removed`, `Fixed` and diff --git a/docs/tools/exceptions.md b/docs/tools/exceptions.md index 6f99192..9ce2a7d 100644 --- a/docs/tools/exceptions.md +++ b/docs/tools/exceptions.md @@ -1,6 +1,6 @@ # Exceptions -Thirty exception classes in `Simtabi\Laranail\Settings\Exceptions`, all extending `SettingsException`, with when each is raised and how the REST API answers it. +Thirty-one exception classes in `Simtabi\Laranail\Settings\Exceptions`, with when each is raised and how the REST API answers it. Thirty extend `SettingsException` (a `RuntimeException`) and report run-time failures; `SettingsMisuse` (a `LogicException`) reports a call the package cannot serve. All of them implement `SettingsError`, so one catch takes them all. ## Catching them @@ -22,13 +22,28 @@ try { } ``` +`SettingsException` covers run-time failures only. To catch every settings exception, the misuse +one included, catch the interface: + +```php +use Simtabi\Laranail\Settings\Exceptions\SettingsError; + +try { + $value = $settings->lookup('mail.host')->value(); +} catch (SettingsError $e) { + report($e); +} +``` + Messages name the store, key, scope and ability involved, never a value, so they are safe to log and to show an administrator. A write that opens a change request does not throw; it returns normally (PHP) or answers `202` (REST). ## Reference | Exception | Extends | Raised when | REST | |---|---|---|---| -| `SettingsException` | `RuntimeException` | the base of every exception below; catch it to catch them all | `500 settings-error` for a subtype not listed | +| `SettingsError` | `Throwable` (interface) | implemented by every exception on this page; catch it to catch them all | as the exception | +| `SettingsException` | `RuntimeException` | the base of every run-time failure below; catch it to catch those | `500 settings-error` for a subtype not listed | +| `SettingsMisuse` | `LogicException` | the package was called in a way it cannot serve: `value()` on a lookup that found nothing or is redacted, `flush()` without `for($owner)`, `Settings::fake()` with no application, a settings migration before the provider is registered. Fix the calling code | `500 settings-error` (never raised by a REST route) | | `AccessDenied` | `SettingsException` | an actor may not perform the ability on the subject; carries the ability, store and key | `403 access-denied` | | `ActorRequired` | `SettingsException` | a call has no actor while `authorization.require_actor` is on, or `asCurrentActor()` finds nobody | `401 actor-required` | | `VerificationRequired` | `SettingsException` | the actor is allowed but must verify again (step-up), for an ability in `verification.abilities` or a definition that `requiresVerification()` | `428 verification-required` | @@ -59,8 +74,6 @@ Messages name the store, key, scope and ability involved, never a value, so they | `DriverUnavailable` | `SettingsException` | a required layer is unreachable (the database is down, its table missing) and no bootstrap evidence lets the store skip it; never a silent fall back to defaults | `503 unavailable` | | `DriverFailure` | `SettingsException` | a storage layer failed; the underlying exception is the previous one | `500 settings-error` | -`LogicException` (PHP's own) is thrown for a programming error rather than a runtime condition: `flush()` without `for($owner)`. - Each exception names its HTTP status and problem type itself (`STATUS` and `TYPE` constants), and `Http\Support\Problems` renders them; anything without its own is a `500 settings-error`; [Problem types](#problem-types) below lists every problem type. ## Problem types diff --git a/docs/tools/settings-api.md b/docs/tools/settings-api.md index d7b83b3..392368a 100644 --- a/docs/tools/settings-api.md +++ b/docs/tools/settings-api.md @@ -141,7 +141,7 @@ public function lookup(string $key): Lookup $lookup = $settings->lookup('site.name'); $lookup->isFound(); // true when stored or defaulted -$lookup->value(); // throws when not found +$lookup->value(); // throws SettingsMisuse when not found or redacted $lookup->valueOr('x'); $lookup->layer(); // 'database', 'runtime', 'shipped', 'default' … $lookup->scope(); // the scope the value came from (an owner, a parent, global) @@ -315,7 +315,7 @@ public function flush(): void $settings->for($user)->asSystem('account closed')->flush(); ``` -Removes every value the handle's owner holds in its store, as when an owner is deleted (`HasSettings` does this for you). Needs `for($owner)` (a `LogicException` otherwise) and `forget`. Throws `AccessDenied`, `StoreNotWritable`. Fires `ScopeFlushing` and `ScopeFlushed`. +Removes every value the handle's owner holds in its store, as when an owner is deleted (`HasSettings` does this for you). Needs `for($owner)` (a `SettingsMisuse` otherwise) and `forget`. Throws `AccessDenied`, `StoreNotWritable`. Fires `ScopeFlushing` and `ScopeFlushed`. ## Runtime overrides diff --git a/src/Data/Lookup.php b/src/Data/Lookup.php index cf3762b..a100176 100644 --- a/src/Data/Lookup.php +++ b/src/Data/Lookup.php @@ -4,7 +4,7 @@ namespace Simtabi\Laranail\Settings\Data; -use LogicException; +use Simtabi\Laranail\Settings\Exceptions\SettingsMisuse; /** The result of a read: found (the value may be null) or missing. */ final readonly class Lookup @@ -56,15 +56,15 @@ public function isFound(): bool return $this->found; } - /** @throws LogicException when nothing was found; check {@see isFound()} or use {@see valueOr()} */ + /** @throws SettingsMisuse when nothing was found; check {@see isFound()} or use {@see valueOr()} */ public function value(): mixed { if (! $this->found) { - throw new LogicException('The setting was not found; call isFound() or valueOr() first.'); + throw new SettingsMisuse('The setting was not found; call isFound() or valueOr() first.'); } if ($this->redacted) { - throw new LogicException('The value is redacted: the actor may not view this setting.'); + throw new SettingsMisuse('The value is redacted: the actor may not view this setting.'); } return $this->value; diff --git a/src/Exceptions/SettingsError.php b/src/Exceptions/SettingsError.php new file mode 100644 index 0000000..2fd18fc --- /dev/null +++ b/src/Exceptions/SettingsError.php @@ -0,0 +1,14 @@ +make(StoreRegistry::class)->withEveryLayer(new ArrayDriver); diff --git a/src/SettingsManager.php b/src/SettingsManager.php index 641e69a..efa7e31 100644 --- a/src/SettingsManager.php +++ b/src/SettingsManager.php @@ -4,7 +4,6 @@ namespace Simtabi\Laranail\Settings; -use LogicException; use Illuminate\Http\Request; use Simtabi\Laranail\Settings\Data\Key; use Simtabi\Laranail\Settings\Data\Actor; @@ -54,6 +53,7 @@ use Simtabi\Laranail\Settings\Exceptions\TypeMismatch; use Simtabi\Laranail\Settings\Actions\PromoteWhenReady; use Simtabi\Laranail\Settings\Exceptions\ActorRequired; +use Simtabi\Laranail\Settings\Exceptions\SettingsMisuse; use Simtabi\Laranail\Settings\Exceptions\UnknownSetting; use Simtabi\Laranail\Settings\Actions\Transfer\DiffStore; use Simtabi\Laranail\Settings\Categories\CategoryManager; @@ -434,7 +434,7 @@ public function unlock(string $key): void public function flush(): void { $store = $this->targetStore(); - $owner = $this->owner ?? throw new LogicException('flush() removes one owner\'s values; call for($owner) first.'); + $owner = $this->owner ?? throw new SettingsMisuse('flush() removes one owner\'s values; call for($owner) first.'); try { $this->flushScope->handle($store, $owner, $this->actingAs); diff --git a/src/Typed/SettingsMigration.php b/src/Typed/SettingsMigration.php index 9a2d66e..1878de7 100644 --- a/src/Typed/SettingsMigration.php +++ b/src/Typed/SettingsMigration.php @@ -5,8 +5,8 @@ namespace Simtabi\Laranail\Settings\Typed; use Closure; -use LogicException; use Illuminate\Database\Migrations\Migration; +use Simtabi\Laranail\Settings\Exceptions\SettingsMisuse; /** * A migration that changes settings rather than tables: renames, moves, deletions and new @@ -41,6 +41,6 @@ public static function resolveMigratorUsing(Closure $migrator): void protected function settings(): SettingsMigrator { - return (self::$migrator ?? throw new LogicException('Settings migrations need laranail/settings\' service provider to be registered.'))(); + return (self::$migrator ?? throw new SettingsMisuse('Settings migrations need laranail/settings\' service provider to be registered.'))(); } } diff --git a/tests/Feature/MisuseTest.php b/tests/Feature/MisuseTest.php new file mode 100644 index 0000000..8891844 --- /dev/null +++ b/tests/Feature/MisuseTest.php @@ -0,0 +1,106 @@ +toBeInstanceOf(SettingsMisuse::class) + ->toBeInstanceOf(LogicException::class) + ->toBeInstanceOf(SettingsError::class) + ->and($thrown->getMessage())->toContain($message); + + return; + } + + test()->fail('Expected SettingsMisuse: ' . $message); +} + +it('throws SettingsMisuse when a missing or redacted lookup is read', function (): void { + expectMisuse(static fn (): mixed => Lookup::missing()->value(), 'call isFound() or valueOr() first'); + expectMisuse(static fn (): mixed => Lookup::found('x', 'runtime', Scope::global())->redacted()->value(), 'redacted'); +}); + +it('throws SettingsMisuse when flush() has no owner', function (): void { + expectMisuse(static fn () => settings()->flush(), 'call for($owner) first'); +}); + +it('throws SettingsMisuse when Settings::fake() has no application', function (): void { + $app = Facade::getFacadeApplication(); + Facade::setFacadeApplication(null); + + try { + expectMisuse(static fn (): mixed => Settings::fake(), 'needs a booted application'); + } finally { + Facade::setFacadeApplication($app); + } +}); + +it('throws SettingsMisuse when a settings migration runs without the provider', function (): void { + $property = new ReflectionProperty(SettingsMigration::class, 'migrator'); + $migrator = $property->getValue(); + $property->setValue(null, null); + $migration = new class extends SettingsMigration + { + public function up(): void + { + $this->settings(); + } + }; + + try { + expectMisuse(static fn () => $migration->up(), 'service provider to be registered'); + } finally { + $property->setValue(null, $migrator); + } +}); + +it('never throws a bare LogicException from the source', function (): void { + $root = dirname(__DIR__, 2) . '/src'; + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)); + $inspected = 0; + $offending = []; + + foreach ($files as $file) { + if (! $file instanceof SplFileInfo || $file->getExtension() !== 'php' || str_contains($file->getPathname(), '/Exceptions/')) { + continue; + } + + $inspected++; + + // Pest's arch expectations do not see global classes, so read the source. + if (preg_match('/\bLogicException\b/', (string) file_get_contents($file->getPathname())) === 1) { + $offending[] = substr($file->getPathname(), strlen($root) + 1); + } + } + + expect($inspected)->toBeGreaterThanOrEqual(300) + ->and($offending)->toBe([]); +}); + +it('lets one catch take every settings exception', function (): void { + $classes = array_map( + static fn (string $file): string => 'Simtabi\\Laranail\\Settings\\Exceptions\\' . basename($file, '.php'), + glob(dirname(__DIR__, 2) . '/src/Exceptions/*.php') ?: [], + ); + $throwables = array_values(array_filter($classes, static fn (string $class): bool => is_a($class, Throwable::class, true))); + + expect(count($throwables))->toBeGreaterThanOrEqual(31) + ->and(array_values(array_filter($throwables, static fn (string $class): bool => ! is_a($class, SettingsError::class, true))))->toBe([]) + ->and(is_a(SettingsException::class, RuntimeException::class, true))->toBeTrue(); +});