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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 17 additions & 4 deletions docs/tools/exceptions.md
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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` |
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/tools/settings-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions src/Data/Lookup.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down
14 changes: 14 additions & 0 deletions src/Exceptions/SettingsError.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Exceptions;

use Throwable;

/**
* Implemented by everything this package throws, so one `catch (SettingsError $e)` takes every
* settings failure: a {@see SettingsException} at run time, or a {@see SettingsMisuse} for a call
* the package cannot serve.
*/
interface SettingsError extends Throwable {}
7 changes: 4 additions & 3 deletions src/Exceptions/SettingsException.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
use RuntimeException;

/**
* Base of every exception this package throws. Messages name the store, key and scope, never a
* value.
* Base of every run-time failure this package throws. Messages name the store, key and scope, never
* a value. A call the package cannot serve throws {@see SettingsMisuse} instead; catch
* {@see SettingsError} for both.
*/
abstract class SettingsException extends RuntimeException
abstract class SettingsException extends RuntimeException implements SettingsError
{
/** The HTTP status the REST API answers with. */
public const int STATUS = 500;
Expand Down
16 changes: 16 additions & 0 deletions src/Exceptions/SettingsMisuse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Simtabi\Laranail\Settings\Exceptions;

use LogicException;

/**
* The package was called in a way it cannot serve: reading a lookup that found nothing or is
* redacted, `flush()` with no owner, `Settings::fake()` with no application, or a settings
* migration before the provider is registered. Fix the calling code; retrying will not help.
*
* A `LogicException`, so existing catch blocks keep working, and a {@see SettingsError}.
*/
final class SettingsMisuse extends LogicException implements SettingsError {}
4 changes: 2 additions & 2 deletions src/Facades/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

namespace Simtabi\Laranail\Settings\Facades;

use LogicException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Facade;
use Simtabi\Laranail\Settings\Data\Actor;
Expand Down Expand Up @@ -35,6 +34,7 @@
use Simtabi\Laranail\Settings\Audit\InMemoryAuditSink;
use Simtabi\Laranail\Settings\Data\PromotionSelection;
use Simtabi\Laranail\Settings\Data\Transfer\StoreDiff;
use Simtabi\Laranail\Settings\Exceptions\SettingsMisuse;
use Simtabi\Laranail\Settings\Categories\CategoryManager;
use Simtabi\Laranail\Settings\Data\Transfer\ImportReport;
use Simtabi\Laranail\Settings\Services\Access\AccessGuard;
Expand Down Expand Up @@ -122,7 +122,7 @@ public static function fake(): SettingsFake
$app = self::getFacadeApplication();

if ($app === null) {
throw new LogicException('Settings::fake() needs a booted application.');
throw new SettingsMisuse('Settings::fake() needs a booted application.');
}

$stores = $app->make(StoreRegistry::class)->withEveryLayer(new ArrayDriver);
Expand Down
4 changes: 2 additions & 2 deletions src/SettingsManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/Typed/SettingsMigration.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.'))();
}
}
106 changes: 106 additions & 0 deletions tests/Feature/MisuseTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Facade;
use Simtabi\Laranail\Settings\Data\Scope;
use Simtabi\Laranail\Settings\Data\Lookup;
use Simtabi\Laranail\Settings\Facades\Settings;
use Simtabi\Laranail\Settings\Typed\SettingsMigration;
use Simtabi\Laranail\Settings\Exceptions\SettingsError;
use Simtabi\Laranail\Settings\Exceptions\SettingsMisuse;
use Simtabi\Laranail\Settings\Exceptions\SettingsException;

/**
* Calling the package wrongly throws SettingsMisuse: still a LogicException, so existing catch
* blocks keep working, and a SettingsError, so one catch covers every settings failure.
*/
function expectMisuse(Closure $call, string $message): void
{
try {
$call();
} catch (Throwable $thrown) {
expect($thrown)->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();
});
Loading