diff --git a/README.md b/README.md index 18dc27b..a741f28 100644 --- a/README.md +++ b/README.md @@ -61,12 +61,12 @@ class names are also made relative when they point inside the application direct The exception's origin and every frame carry one `source` string: the source line at the reported `line`, trimmed of surrounding whitespace. A blank line is an empty string. Unavailable source is omitted. Traces are capped at -30 frames (`traceLimit`), keeping the frames nearest the throw; a capped trace is flagged with `traceTruncated`. +30 frames (`traceLimit`), keeping the frames nearest the throw; a capped trace is flagged with `truncated`. -Frame arguments are included, truncated to depth 5, 50 items, and 500 bytes per string. Objects are reduced to a -class name plus at most 50 public properties, with the remainder reported by the same `"*truncated*": "N more -items"` marker used for maps. `#[\SensitiveParameter]` values are redacted, and `__toString()` is never called. -A frame whose arguments PHP did not report carries no `args` member at all. +Frame arguments are reduced to their types, never their values: `args` is a list of type names such as `int`, +`string`, `bool`, `null`, `float`, `Closure`, a class name, or `resource (stream)`. An array is `vec` when it is a +list and `dict` otherwise. A `#[\SensitiveParameter]` argument reports the type of the protected value, never the +value. A frame whose arguments PHP did not report carries no `args` member at all. **Arguments require `zend.exception_ignore_args=Off`.** It defaults to `Off`, and `php.ini-development` sets `Off`, but `php.ini-production` sets `On`, which removes arguments from every trace PHP produces. An application @@ -105,20 +105,21 @@ After running `composer install` (including development dependencies), start the php -S localhost:8000 demo/index.php ``` -Open for a centered grid of links. The same router serves all four demos, each intentionally +Open for a centered grid of links. The same router serves all five demos, each intentionally returning a 500 `application/problem+json` response through `ExceptionMiddleware`: - `/minimal`: production-style output without the exception message, source, or trace. - `/full`: the same exception with development details. -- `/recursion`: bounded recursive object calls with cyclic public properties and a truncated trace. -- `/sensitive`: redacted parameter arguments and public properties wrapped in `SensitiveParameterValue`. +- `/recursion`: bounded recursive calls that produce a truncated trace. +- `/sensitive`: a `#[\SensitiveParameter]` argument reduced to its type, never its value. +- `/types`: a call with scalar, `vec`, `dict`, object, enum, and closure arguments, each shown as its type. You can also request a demo directly, for example with `curl -i http://localhost:8000/full`. Development demos enable exception arguments regardless of your `php.ini`. The sensitive demo accepts optional -`DEMO_PASSWORD` and `DEMO_TOKEN` environment variables; its defaults are fake credentials. `#[SensitiveParameter]` -protects trace arguments, not stored properties, exception messages, or source code. Use `SensitiveParameterValue` -for sensitive public properties and never put real secrets in messages or source files. +`DEMO_PASSWORD` and `DEMO_TOKEN` environment variables; its defaults are fake credentials. Because traces carry +argument types only, no argument value ever reaches the response; `#[\SensitiveParameter]` is still respected. +Never put real secrets in exception messages or source files. ## Development diff --git a/demo/index.php b/demo/index.php index 98bb783..81baef3 100644 --- a/demo/index.php +++ b/demo/index.php @@ -16,6 +16,7 @@ '/full' => 'full.php', '/recursion' => 'recursion.php', '/sensitive' => 'sensitive.php', + '/types' => 'types.php', default => null, }; @@ -89,6 +90,7 @@ full recursion sensitive + types diff --git a/demo/recursion.php b/demo/recursion.php index 3bbcfa5..2fecec0 100644 --- a/demo/recursion.php +++ b/demo/recursion.php @@ -14,13 +14,9 @@ */ final class RecursiveNode { - public self $next; - public function __construct( public readonly string $name, - ) { - $this->next = $this; - } + ) {} public function visit(self $node, int $remaining): never { @@ -35,8 +31,6 @@ public function visit(self $node, int $remaining): never namespace\run_demo(Mode::Full, static function (): never { $first = new RecursiveNode('first'); $second = new RecursiveNode('second'); - $first->next = $second; - $second->next = $first; $first->visit($second, 35); }); diff --git a/demo/types.php b/demo/types.php new file mode 100644 index 0000000..a44c2ea --- /dev/null +++ b/demo/types.php @@ -0,0 +1,62 @@ + $items + * @param array $counts + */ + // @mago-ignore lint:excessive-parameter-list + public function call( + int $count, + string $label, + // @mago-ignore lint:no-boolean-flag-parameter + bool $enabled, + ?string $note, + float $ratio, + array $items, + array $counts, + stdClass $payload, + Mode $mode, + Closure $callback, + ): never { + $callback(); + + $summary = $label . ':' . $count . ':' . count($items) . ':' . count($counts); + $summary .= ':' . $payload::class . ':' . $mode->name; + $summary .= ':' . ($enabled ? 'on' : 'off') . ':' . ($note ?? 'none') . ':' . $ratio; + + throw new RuntimeException('The typed-arguments demo always fails: ' . $summary); + } +} + +namespace\run_demo(Mode::Full, static function (): never { + new TypedCaller()->call( + count: 3, + label: 'demo', + enabled: true, + note: null, + ratio: 0.5, + items: [1, 2, 3], + counts: ['a' => 1, 'b' => 2], + payload: new stdClass(), + mode: Mode::Full, + callback: static fn(): int => 1, + ); +}); diff --git a/docs/superpowers/plans/2026-09-30-errata-exception-handler.md b/docs/superpowers/plans/2026-09-30-errata-exception-handler.md index 13afa9e..077cff3 100644 --- a/docs/superpowers/plans/2026-09-30-errata-exception-handler.md +++ b/docs/superpowers/plans/2026-09-30-errata-exception-handler.md @@ -4,7 +4,7 @@ **Goal:** Build a PHP 8.4 library that turns any uncaught `Throwable` into an RFC 9457 `application/problem+json` document, logs it via PSR-3, and exposes it through a PSR-15 middleware — with full and minimal modes. -**Architecture:** Ten focused units. Value objects in `Errata\Document\` own the JSON contract; `Errata\Trace\` holds the plumbing that reads source lines, sanitizes arguments, and assembles frames; `Errata\Path\PathRelativizer` turns absolute paths into project-relative ones; `Errata\ExceptionHandler` maps a `Throwable` to a `Problem`; `Errata\Middleware\ExceptionMiddleware` catches, logs, encodes, and responds. Every unit is independently testable, which the 100% coverage gate requires. +**Architecture:** Ten focused units. Value objects in `Errata\Document\` own the JSON contract; `Errata\Trace\` holds the plumbing that reads source lines, types arguments, and assembles frames; `Errata\Path\PathRelativizer` turns absolute paths into project-relative ones; `Errata\ExceptionHandler` maps a `Throwable` to a `Problem`; `Errata\Middleware\ExceptionMiddleware` catches, logs, encodes, and responds. Every unit is independently testable, which the 100% coverage gate requires. **Tech Stack:** PHP 8.4, PSR-7 (`psr/http-factory`), PSR-15 (`psr/http-server-middleware`), PSR-3 (`psr/log`), `composer-runtime-api` (`Composer\InstalledVersions`), `codeinc/http-reason-phrase-lookup` (`CodeInc\HttpReasonPhraseLookup\HttpReasonPhraseLookup`), PHPUnit 13.3, Mago for lint/analyze/format, `nyholm/psr7` for PSR-7 test doubles. @@ -492,358 +492,103 @@ git commit -m "feat: read the five-line source window around a line" --- -### Task 3: Argument sanitizer +### Task 3: Argument typer **Files:** -- Create: `src/Document/SanitizedObject.php` -- Create: `src/Document/SanitizedMap.php` -- Create: `src/Trace/ArgumentSanitizer.php` -- Test: `tests/Document/SanitizedObjectTest.php` -- Test: `tests/Document/SanitizedMapTest.php` -- Test: `tests/Trace/ArgumentSanitizerTest.php` +- Create: `src/Trace/ArgumentTyper.php` +- Test: `tests/Trace/ArgumentTyperTest.php` **Interfaces:** - Consumes: nothing. -- Produces: - - `Errata\Document\SanitizedObject` — `__construct(public string $class, public array $properties)`, serializes to `['@class' => string, 'props' => array]`. - - `Errata\Document\SanitizedMap` — `__construct(public array $entries)`, serializes to its entries (a JSON object). - - `Errata\Trace\ArgumentSanitizer` — `sanitize(mixed $value): mixed`, total (never throws), limits depth 5 / 50 items / 500 bytes. - - `sanitize()` returns: scalars verbatim; strings truncated with `...`; lists as `list`; maps as `SanitizedMap`; plain objects as `SanitizedObject` with at most 50 public properties and a `*truncated*` marker for the remainder; `Closure` as `'Closure'`; enums as `'FQCN::CASE'`; resources as `'resource(type)'`; `SensitiveParameterValue` as `'*redacted*'`; anything past depth 5 as `'*depth limit*'`; a closed resource as `'resource(closed)'`. - -- [ ] **Step 1: Write the failing tests** - -`tests/Document/SanitizedObjectTest.php`: - -```php -assertSame( - ['@class' => 'App\Thing', 'props' => ['id' => 1]], - (new SanitizedObject('App\Thing', ['id' => 1]))->jsonSerialize(), - ); - } -} -``` +- [ ] **Step 1: Write the failing test** -`tests/Document/SanitizedMapTest.php`: +`tests/Trace/ArgumentTyperTest.php`: ```php -assertSame( - ['alpha' => 1, 'beta' => 'two'], - (new SanitizedMap(['alpha' => 1, 'beta' => 'two']))->jsonSerialize(), - ); - } -} -``` - -`tests/Trace/ArgumentSanitizerTest.php`: +sanitizer = new ArgumentSanitizer(); + $this->typer = new ArgumentTyper(); } - public function testItPassesScalarsThroughUnchanged(): void + public function testItNamesScalars(): void { - $this->assertNull($this->sanitizer->sanitize(null)); - $this->assertTrue($this->sanitizer->sanitize(true)); - $this->assertSame(7, $this->sanitizer->sanitize(7)); - $this->assertSame(1.5, $this->sanitizer->sanitize(1.5)); - $this->assertSame('short', $this->sanitizer->sanitize('short')); + $this->assertSame('null', $this->typer->type(null)); + $this->assertSame('bool', $this->typer->type(true)); + $this->assertSame('int', $this->typer->type(7)); + $this->assertSame('float', $this->typer->type(1.5)); + $this->assertSame('string', $this->typer->type('plain')); } - public function testItTruncatesLongStrings(): void + public function testItSplitsArraysIntoVecAndDict(): void { - $sanitized = $this->sanitizer->sanitize(str_repeat('a', 501)); - - $this->assertIsString($sanitized); - $this->assertSame(503, strlen($sanitized)); - $this->assertStringEndsWith('...', $sanitized); + $this->assertSame('vec', $this->typer->type([1, 2])); + $this->assertSame('vec', $this->typer->type([])); + $this->assertSame('dict', $this->typer->type(['key' => 'value'])); + $this->assertSame('dict', $this->typer->type([0 => 'a', 2 => 'b'])); } - public function testItKeepsListsAsLists(): void + public function testItNamesObjectsClosuresAndEnums(): void { - $this->assertSame([1, 'two'], $this->sanitizer->sanitize([1, 'two'])); + $this->assertSame(stdClass::class, $this->typer->type(new stdClass())); + $this->assertSame('Closure', $this->typer->type(static fn(): int => 1)); + $this->assertSame(Mode::class, $this->typer->type(Mode::Full)); } - public function testItTreatsNonSequentialKeysAsAMap(): void + public function testItNamesResources(): void { - $sanitized = $this->sanitizer->sanitize([0 => 'a', 2 => 'b']); - - $this->assertInstanceOf(SanitizedMap::class, $sanitized); - $this->assertSame('{"0":"a","2":"b"}', json_encode($sanitized)); - } + $handle = fopen(filename: 'php://memory', mode: 'r'); - public function testItMarksATruncatedList(): void - { - $json = json_encode($this->sanitizer->sanitize(range(1, 60))); - - $this->assertIsString($json); - $this->assertStringEndsWith(',"... (10 more items)"]', $json); - $this->assertSame(51, substr_count($json, ',') + 1); - } - - public function testItMarksATruncatedMap(): void - { - $entries = []; - - for ($i = 0; $i < 60; $i++) { - $entries['key' . $i] = $i; + try { + $this->assertSame('resource (stream)', $this->typer->type($handle)); + } finally { + fclose($handle); } - $sanitized = $this->sanitizer->sanitize($entries); - - $this->assertInstanceOf(SanitizedMap::class, $sanitized); - $this->assertSame(51, count($sanitized->entries)); - $this->assertSame(['*truncated*' => '10 more items'], array_slice($sanitized->entries, -1, null, true)); + $this->assertSame('resource (closed)', $this->typer->type($handle)); } - public function testItStopsAtTheDepthLimit(): void + public function testItUnwrapsSensitiveParametersToTheProtectedType(): void { - $nested = ['end']; - - for ($i = 0; $i < 10; $i++) { - $nested = [$nested]; - } - - $json = json_encode($this->sanitizer->sanitize($nested)); - - $this->assertIsString($json); - $this->assertStringContainsString('*depth limit*', $json); - $this->assertSame(5, substr_count($json, '[')); - } - - public function testItEmptiesARepeatedObjectInsteadOfRecursing(): void - { - $node = new stdClass(); - $node->self = $node; - - $this->assertSame( - '{"@class":"stdClass","props":{"self":{"@class":"stdClass","props":[]}}}', - json_encode($this->sanitizer->sanitize($node)), - ); - } - - public function testItKeepsPublicPropertiesOnly(): void - { - $json = json_encode($this->sanitizer->sanitize(new ArgumentSanitizerFixture())); - - $this->assertIsString($json); - $this->assertStringContainsString('"props":{"public":"yes"}', $json); - $this->assertStringNotContainsString('protected', $json); - $this->assertStringNotContainsString('private', $json); - } - - public function testItNeverCallsToString(): void - { - $sanitized = $this->sanitizer->sanitize(new ArgumentSanitizerHostileFixture()); - - $this->assertInstanceOf(SanitizedObject::class, $sanitized); - $this->assertSame([], $sanitized->properties); - } - - public function testItRedactsSensitiveParameters(): void - { - $this->assertSame('*redacted*', $this->sanitizer->sanitize(new SensitiveParameterValue('hunter2'))); - } - - public function testItNamesClosuresAndEnums(): void - { - $this->assertSame('Closure', $this->sanitizer->sanitize(static fn (): int => 1)); - $this->assertSame( - 'Errata\Tests\Trace\ArgumentSanitizerEnum::Second', - $this->sanitizer->sanitize(ArgumentSanitizerEnum::Second), - ); - } - - public function testItDescribesResources(): void - { - $handle = fopen('php://memory', 'r'); - - $this->assertSame('resource(stream)', $this->sanitizer->sanitize($handle)); - - fclose($handle); - - $this->assertSame('resource(closed)', $this->sanitizer->sanitize($handle)); - } - - public function testItSanitizesPropertiesRecursively(): void - { - $payload = new stdClass(); - $payload->token = new SensitiveParameterValue('hunter2'); - $payload->nested = ['a' => str_repeat('b', 501)]; - - $json = json_encode($this->sanitizer->sanitize($payload)); - - $this->assertIsString($json); - $this->assertStringContainsString('"token":"*redacted*"', $json); - $this->assertStringContainsString('"nested":{"a":"' . str_repeat('b', 500) . '..."}', $json); - } -} - -enum ArgumentSanitizerEnum -{ - case First; - case Second; -} - -final class ArgumentSanitizerFixture -{ - public string $public = 'yes'; - - protected string $protected = 'no'; - - private string $private = 'no'; - - /** - * Reads every property, so the fixture has no unused members. - * - * @return list - */ - public function values(): array - { - return [$this->public, $this->protected, $this->private]; - } -} - -final class ArgumentSanitizerHostileFixture implements Stringable -{ - #[Override] - public function __toString(): string - { - throw new RuntimeException('__toString must not be called'); + $this->assertSame('string', $this->typer->type(new SensitiveParameterValue('hunter2'))); + $this->assertSame('vec', $this->typer->type(new SensitiveParameterValue([1, 2]))); + $this->assertSame('dict', $this->typer->type(new SensitiveParameterValue(['a' => 1]))); } } ``` -- [ ] **Step 2: Run the tests to verify they fail** +- [ ] **Step 2: Run the test to verify it fails** -Run: `vendor/bin/phpunit tests/Document/SanitizedObjectTest.php tests/Document/SanitizedMapTest.php tests/Trace/ArgumentSanitizerTest.php` -Expected: FAIL — `Class "Errata\Document\SanitizedObject" not found`. +Run: `vendor/bin/phpunit tests/Trace/ArgumentTyperTest.php` +Expected: FAIL — `Class "Errata\Trace\ArgumentTyper" not found`. - [ ] **Step 3: Write the implementation** -`src/Document/SanitizedObject.php`: - -```php - $properties - */ - public function __construct( - public string $class, - public array $properties, - ) {} - - /** - * @return array - */ - #[Override] - public function jsonSerialize(): array - { - return ['@class' => $this->class, 'props' => $this->properties]; - } -} -``` - -`src/Document/SanitizedMap.php`: - -```php - $entries - */ - public function __construct( - public array $entries, - ) {} - - /** - * @return array - */ - #[Override] - public function jsonSerialize(): array - { - return $this->entries; - } -} -``` - -`src/Trace/ArgumentSanitizer.php`: +`src/Trace/ArgumentTyper.php`: ```php + * Arrays are split into `vec` (a list) and `dict` (anything else); + * every other value is named by `get_debug_type()`. A + * `SensitiveParameterValue` is unwrapped so the trace reports the + * type of the protected value without ever exposing the value. */ - private SplObjectStorage $processing; - - public function __construct() + public function type(mixed $value): string { - /** @var SplObjectStorage $processing */ - $processing = new SplObjectStorage(); - - $this->processing = $processing; - } - - public function sanitize(mixed $value): mixed - { - return $this->sanitizeValue($value, 0); - } - - private function sanitizeValue(mixed $value, int $depth): mixed - { - return match (true) { - $depth >= self::MAX_DEPTH => '*depth limit*', - $value === null, is_bool($value), is_int($value) => $value, - is_float($value) => self::float($value), - is_string($value) => $this->sanitizeString($value), - is_array($value) => $this->sanitizeArray($value, $depth), - $value instanceof SensitiveParameterValue => '*redacted*', - $value instanceof Closure => 'Closure', - $value instanceof UnitEnum => $value::class . '::' . $value->name, - is_object($value) => $this->sanitizeObject($value, $depth), - is_resource($value) => 'resource(' . get_resource_type($value) . ')', - default => 'resource(closed)', - }; - } - - /** - * `json_encode()` refuses INF and NAN, and a document that cannot be - * encoded is a document that cannot be reported, so non-finite - * floats become their names. - */ - private static function float(float $value): float|string - { - if (is_finite($value)) { - return $value; - } - - if (is_nan($value)) { - return 'NAN'; - } - - return $value > 0.0 ? 'INF' : '-INF'; - } - - private function sanitizeString(string $value): string - { - if (strlen($value) <= self::MAX_STRING_LENGTH) { - return $value; - } - - return substr(string: $value, offset: 0, length: self::MAX_STRING_LENGTH) . '...'; - } - - /** - * A list stays a list; anything else becomes a SanitizedMap. - * - * @param array $value - * - * @return list|SanitizedMap - */ - private function sanitizeArray(array $value, int $depth): array|SanitizedMap - { - $total = count($value); - $slice = array_slice(array: $value, offset: 0, length: self::MAX_ITEMS, preserve_keys: true); - - if (array_is_list($value)) { - $items = []; - - /** @var mixed $item */ - foreach ($slice as $item) { - $items[] = $this->sanitizeValue($item, $depth + 1); - } - - if ($total > self::MAX_ITEMS) { - $items[] = sprintf('... (%d more items)', $total - self::MAX_ITEMS); - } - - return $items; - } - - return new SanitizedMap($this->sanitizeEntries($slice, $depth, $total)); - } - - /** - * Sanitizes a capped slice of entries, appending the truncation marker - * when the source held more items than the cap. - * - * @param array $slice - * - * @return array - */ - private function sanitizeEntries(array $slice, int $depth, int $total): array - { - $entries = []; - - /** @var mixed $item */ - foreach ($slice as $key => $item) { - $entries[(string) $key] = $this->sanitizeValue($item, $depth + 1); + if ($value instanceof SensitiveParameterValue) { + return $this->type($value->getValue()); } - if ($total > self::MAX_ITEMS) { - $entries['*truncated*'] = sprintf('%d more items', $total - self::MAX_ITEMS); + if (is_array($value)) { + return array_is_list($value) ? 'vec' : 'dict'; } - return $entries; - } - - private function sanitizeObject(object $value, int $depth): SanitizedObject - { - if ($this->processing->offsetExists($value)) { - return new SanitizedObject($value::class, []); - } - - $this->processing->offsetSet($value, null); - - try { - /** @var array $all */ - $all = get_object_vars($value); - $slice = array_slice(array: $all, offset: 0, length: self::MAX_ITEMS, preserve_keys: true); - - return new SanitizedObject($value::class, $this->sanitizeEntries($slice, $depth, count($all))); - } finally { - $this->processing->offsetUnset($value); - } + return get_debug_type($value); } } ``` -- [ ] **Step 4: Run the tests to verify they pass** - -Run: `vendor/bin/phpunit tests/Document/SanitizedObjectTest.php tests/Document/SanitizedMapTest.php tests/Trace/ArgumentSanitizerTest.php` -Expected: PASS, 16 tests. +- [ ] **Step 4: Run the test to verify it passes** -If `testItStopsAtTheDepthLimit` fails on the `substr_count` assertion, print the encoded value and adjust the expected count — the invariant to preserve is that nesting is bounded, not the literal number. +Run: `vendor/bin/phpunit tests/Trace/ArgumentTyperTest.php` +Expected: PASS, 5 tests. - [ ] **Step 5: Commit** ```bash composer run fix -git add src/Document/SanitizedObject.php src/Document/SanitizedMap.php src/Trace/ArgumentSanitizer.php tests/Document/SanitizedObjectTest.php tests/Document/SanitizedMapTest.php tests/Trace/ArgumentSanitizerTest.php -git commit -m "feat: sanitize trace arguments without invoking user code" +git add src/Trace/ArgumentTyper.php tests/Trace/ArgumentTyperTest.php +git commit -m "feat: report trace argument types instead of values" ``` --- @@ -1276,7 +870,7 @@ git commit -m "feat: relativize exception paths against the project directory" **Interfaces:** - Consumes: `Errata\Document\SourceLine` (Task 2). - Produces: - - `Errata\Document\Frame` — `__construct(?string $file = null, ?int $line = null, ?string $function = null, ?string $class = null, ?string $type = null, ?array $args = null, array $source = [])`. Serializes members in order `file, line, function, class, type, args, source`, omitting null members and an empty `source`; `args` is emitted only when PHP reported arguments for the frame, so `args: []` is a reported empty list and an absent member means PHP did not report arguments. + - `Errata\Document\Frame` — `__construct(?string $file = null, ?int $line = null, ?string $function = null, ?string $class = null, ?string $type = null, ?array $args = null, array $source = [])`. Serializes members in order `file, line, function, class, type, args, source`, omitting null members and an empty `source`; `args` is a list of type names, emitted only when PHP reported arguments for the frame, so `args: []` is a reported empty list and an absent member means PHP did not report arguments. - `Errata\Document\Trace` — `__construct(public array $frames, public bool $truncated)`, `jsonSerialize(): list` returning the frames. - [ ] **Step 1: Write the failing tests** @@ -1304,7 +898,7 @@ final class FrameTest extends TestCase public function testItOmitsNullMembersAndEmptySource(): void { - $frame = new Frame(file: 'src/Foo.php', line: 12, function: 'run', class: 'App\Foo', type: '->', args: [1], source: []); + $frame = new Frame(file: 'src/Foo.php', line: 12, function: 'run', class: 'App\Foo', type: '->', args: ['int'], source: []); $this->assertSame( [ @@ -1313,7 +907,7 @@ final class FrameTest extends TestCase 'function' => 'run', 'class' => 'App\Foo', 'type' => '->', - 'args' => [1], + 'args' => ['int'], ], $frame->jsonSerialize(), ); @@ -1419,7 +1013,7 @@ use Override; final readonly class Frame implements JsonSerializable { /** - * @param list|null $args + * @param list|null $args * @param list $source */ public function __construct( @@ -1539,7 +1133,7 @@ git commit -m "feat: add frame and trace document types" - `__construct(string $type, string $title, int $status, int $code, ?string $detail = null, ?string $file = null, ?int $line = null, array $source = [], ?Trace $trace = null, ?Problem $previous = null)` - `public static function minimal(Throwable $exception, int $status): self` — the status phrase, the short class name as `detail`, and the code. - `public static function development(Throwable $exception, int $status, string $file, int $line, array $source, Trace $trace, ?Problem $previous): self` — `minimal()` plus `detail` as `class: message`, origin, source window, trace, and cause. - - `jsonSerialize(): array` emitting `type, title, status, code, detail, file, line, source, trace, traceTruncated, previous`, omitting null/false members and empty `source`. + - `jsonSerialize(): array` emitting `type, title, status, code, detail, file, line, source, trace, truncated, previous`, omitting null/false members and empty `source`. - [ ] **Step 1: Write the failing test** @@ -1670,7 +1264,7 @@ final class ProblemTest extends TestCase $this->assertArrayNotHasKey('source', $serialized); $this->assertArrayNotHasKey('previous', $serialized); - $this->assertArrayNotHasKey('traceTruncated', $serialized); + $this->assertArrayNotHasKey('truncated', $serialized); } public function testDevelopmentFlagsATruncatedTrace(): void @@ -1685,7 +1279,7 @@ final class ProblemTest extends TestCase previous: null, ); - $this->assertTrue($problem->jsonSerialize()['traceTruncated'] ?? false); + $this->assertTrue($problem->jsonSerialize()['truncated'] ?? false); } public function testItCanBeConstructedDirectly(): void @@ -1886,7 +1480,7 @@ final readonly class Problem implements JsonSerializable $document['trace'] = $this->trace; if ($this->trace->truncated) { - $document['traceTruncated'] = true; + $document['truncated'] = true; } } @@ -1958,8 +1552,8 @@ git commit -m "feat: add the problem document type with both modes" - Test: `tests/Trace/TraceFactoryTest.php` **Interfaces:** -- Consumes: `Errata\Path\PathRelativizer` (Task 4), `Errata\Trace\SourceContext` (Task 2), `Errata\Trace\ArgumentSanitizer` (Task 3), `Errata\Document\Frame` and `Errata\Document\Trace` (Task 5). -- Produces: `Errata\Trace\TraceFactory` — `__construct(PathRelativizer $relativizer, SourceContext $source, ArgumentSanitizer $arguments, int $traceLimit)`, `frames(array $trace): Trace` where the input is PHP's `Throwable::getTrace()` array, which already lists the frame nearest the throw first, so the first `$traceLimit` entries — the innermost frames — are kept. An entry without an `args` key (or with a non-array one) yields a frame with no `args` member; an empty `args` array is kept as `args: []`. +- Consumes: `Errata\Path\PathRelativizer` (Task 4), `Errata\Trace\SourceContext` (Task 2), `Errata\Trace\ArgumentTyper` (Task 3), `Errata\Document\Frame` and `Errata\Document\Trace` (Task 5). +- Produces: `Errata\Trace\TraceFactory` — `__construct(PathRelativizer $relativizer, SourceContext $source, ArgumentTyper $types, int $traceLimit)`, `frames(array $trace): Trace` where the input is PHP's `Throwable::getTrace()` array, which already lists the frame nearest the throw first, so the first `$traceLimit` entries — the innermost frames — are kept. An entry without an `args` key (or with a non-array one) yields a frame with no `args` member; an empty `args` array is kept as `args: []`. - [ ] **Step 1: Write the failing test** @@ -1974,7 +1568,7 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use Errata\Document\Trace; use Errata\Path\PathRelativizer; -use Errata\Trace\ArgumentSanitizer; +use Errata\Trace\ArgumentTyper; use Errata\Trace\SourceContext; use Errata\Trace\TraceFactory; use stdClass; @@ -1995,7 +1589,7 @@ final class TraceFactoryTest extends TestCase $this->factory = new TraceFactory( new PathRelativizer($this->root), new SourceContext(), - new ArgumentSanitizer(), + new ArgumentTyper(), traceLimit: 30, ); } @@ -2174,7 +1768,7 @@ final class TraceFactory public function __construct( private readonly PathRelativizer $relativizer, private readonly SourceContext $source, - private readonly ArgumentSanitizer $arguments, + private readonly ArgumentTyper $types, private readonly int $traceLimit, ) {} @@ -2225,7 +1819,7 @@ final class TraceFactory * * @param array $entry * - * @return list|null + * @return list|null */ private function args(array $entry): ?array { @@ -2233,13 +1827,7 @@ final class TraceFactory return null; } - $args = []; - - foreach ($entry['args'] as $argument) { - $args[] = $this->arguments->sanitize($argument); - } - - return $args; + return array_map($this->types->type(...), array_values($entry['args'])); } /** @@ -2292,7 +1880,7 @@ git commit -m "feat: assemble trace frames with source windows and arguments" - Test: `tests/ExceptionHandlerTest.php` **Interfaces:** -- Consumes: `Errata\Mode` (Task 1), `Errata\Document\Problem` (Task 6), `Errata\Path\PathRelativizer` (Task 4), `Errata\Trace\SourceContext` (Task 2), `Errata\Trace\ArgumentSanitizer` (Task 3), `Errata\Trace\TraceFactory` (Task 7). +- Consumes: `Errata\Mode` (Task 1), `Errata\Document\Problem` (Task 6), `Errata\Path\PathRelativizer` (Task 4), `Errata\Trace\SourceContext` (Task 2), `Errata\Trace\ArgumentTyper` (Task 3), `Errata\Trace\TraceFactory` (Task 7). - Produces: - `Errata\Http\StatusCodeInterface` — `getStatusCode(): int`. - `Errata\ExceptionHandler` — `__construct(Mode $mode, ?string $projectDir = null, int $traceLimit = 30)`, `handle(Throwable $exception): Problem`. @@ -2359,7 +1947,7 @@ final class ExceptionHandlerTest extends TestCase $this->assertIsInt($problem->line); $this->assertNotSame([], $problem->source); $this->assertInstanceOf(Trace::class, $problem->trace); - $this->assertStringNotContainsString('traceTruncated', (string) json_encode($problem)); + $this->assertStringNotContainsString('truncated', (string) json_encode($problem)); $this->assertNull($problem->previous); } @@ -2484,7 +2072,7 @@ use Override; use Errata\Document\Problem; use Errata\Http\StatusCodeInterface; use Errata\Path\PathRelativizer; -use Errata\Trace\ArgumentSanitizer; +use Errata\Trace\ArgumentTyper; use Errata\Trace\SourceContext; use Errata\Trace\TraceFactory; use Throwable; @@ -2520,7 +2108,7 @@ final class ExceptionHandler implements ExceptionHandlerInterface $this->relativizer = new PathRelativizer($projectDir); $this->source = new SourceContext(); - $this->trace = new TraceFactory($this->relativizer, $this->source, new ArgumentSanitizer(), $traceLimit); + $this->trace = new TraceFactory($this->relativizer, $this->source, new ArgumentTyper(), $traceLimit); } #[Override] @@ -3182,14 +2770,14 @@ The exception's origin and every frame carry a five-line source window (the reported line ±2), clamped to the file, with blank lines removed and original line numbers preserved. Traces are capped at 30 frames (`traceLimit`), keeping the frames nearest the throw; a capped trace is -flagged with `traceTruncated`. +flagged with `truncated`. -Frame arguments are included, truncated to depth 5, 50 items, and 500 -bytes per string. Objects are reduced to a class name plus at most 50 -public properties, with the remainder reported by the same -`"*truncated*": "N more items"` marker used for maps. -`#[\SensitiveParameter]` values are redacted, and `__toString()` is -never called. +Frame arguments are reduced to their types, never their values: `args` +is a list of type names such as `int`, `string`, `bool`, `null`, +`float`, `Closure`, a class name, or `resource (stream)`. An array is +`vec` when it is a list and `dict` otherwise. A +`#[\SensitiveParameter]` argument reports the type of the protected +value, never the value. **Arguments require `zend.exception_ignore_args=Off`.** It defaults to `Off`, and `php.ini-development` sets `Off`, but `php.ini-production` @@ -3358,6 +2946,6 @@ git commit -m "docs: document usage, modes, traces, and status codes" Before declaring the plan done, confirm each of these: - `composer run verify` passes; coverage is exactly 100%. -- Every file listed under `src/` in the spec exists: `Mode.php`, `ExceptionHandlerInterface.php`, `ExceptionHandler.php`, `Http/StatusCodeInterface.php`, `Middleware/ExceptionMiddleware.php`, `Document/{Problem,Trace,Frame,SourceLine,SanitizedObject,SanitizedMap}.php`, `Path/PathRelativizer.php`, `Trace/{TraceFactory,SourceContext,ArgumentSanitizer}.php`. +- Every file listed under `src/` in the spec exists: `Mode.php`, `ExceptionHandlerInterface.php`, `ExceptionHandler.php`, `Http/StatusCodeInterface.php`, `Middleware/ExceptionMiddleware.php`, `Document/{Problem,Trace,Frame,SourceLine}.php`, `Path/PathRelativizer.php`, `Trace/{TraceFactory,SourceContext,ArgumentTyper}.php`. - `git grep -n 'vendor' src/` returns nothing: no vendor detection survives anywhere in the implementation. - The smoke script's minimal body is exactly `{"type":"about:blank","title":"Internal Server Error","status":500,"code":42,"detail":"RuntimeException"}`. diff --git a/docs/superpowers/specs/2026-09-30-errata-exception-handler-design.md b/docs/superpowers/specs/2026-09-30-errata-exception-handler-design.md index 8cac2b0..66a5bc4 100644 --- a/docs/superpowers/specs/2026-09-30-errata-exception-handler-design.md +++ b/docs/superpowers/specs/2026-09-30-errata-exception-handler-design.md @@ -14,6 +14,17 @@ JSON, so this amendment reduces `source` to the single reported line. Each amend response contract; no compatibility format is retained. The sections below describe the current contract, and the implementation follows it. +## Argument-type amendments — 2026-10-01 + +Trace frame arguments are reported as types, never values. `args` is a list of type names: `get_debug_type()` for +every value, except arrays, which are `vec` when `array_is_list()` is true and `dict` otherwise. A +`SensitiveParameterValue` is unwrapped so the trace reports the type of the protected value, never the value. + +This replaces the earlier argument sanitizer, which emitted truncated values, object property maps, and redaction +markers. Because no value ever reaches the trace, there is nothing to truncate, no cycle to detect, no user code +to avoid invoking, and no redaction to perform; `SanitizedMap`, `SanitizedObject`, and `ArgumentSanitizer` are +removed. The sections below describe the current contract, and the implementation follows it. + ## Purpose A small library that turns any uncaught `Throwable` in a JSON API into a @@ -67,23 +78,23 @@ later changes. | 6 | Trace frame shape | Reported `line` plus one `source` string: the source line at that line | | 7 | Vendor detection | None: no vendor flag, no vendor-directory config; every frame is treated identically | | 8 | Frame order | Innermost-first — PHP's own `getTrace()` order, nothing reversed | -| 9 | Frame arguments | Included, truncated; `#[\SensitiveParameter]` respected; omitted when PHP does not report them | +| 9 | Frame arguments | Included as types only; `#[\SensitiveParameter]` unwrapped to the protected value's type; omitted when PHP does not report them | | 10 | Path base | Composer-derived default, individually overridable | | 11 | Trace length | Capped, default 30 frames, keeps the innermost frames | | 12 | Mode source | `APP_ENV`, then `APP_DEBUG`, then Minimal | | 13 | Non-500 status | Opt-in `StatusCodeInterface`; interface only, no shipped exception classes | | 14 | `code` member | `(int) $exception->getCode()` | | 15 | Handler return | `Problem` value object (`JsonSerializable`) | -| 16 | Argument truncation | Depth 5, 50 items, 500-byte strings | +| 16 | Argument representation | Types only: `get_debug_type()`, with arrays split into `vec`/`dict` | | 17 | Chained exceptions | Recursed in full mode, omitted in minimal mode | | 18 | Logger failure | Caught, reported with `error_log()`, processing continues | | 19 | Log context | `exception`, `method`, `path`, `status` | -| 20 | Objects in arguments | Class name plus at most 50 public properties | +| 20 | Objects in arguments | Class name only | | 21 | Origin frame | Top-level `file`/`line`/`source` only; not duplicated into `trace` | | 22 | Response headers | `Content-Type: application/problem+json` only | | 23 | Source context | The source line at the reported line, origin and frames alike, trimmed of surrounding whitespace | | 24 | Document types | DTOs implementing `JsonSerializable`; bare arrays only for lists | -| 25 | Map payloads | String-keyed maps are carried by a DTO and serialized as a JSON object | +| 25 | Map payloads | None: arguments carry no values, so no map DTO exists | | 26 | API markers | Document DTOs are `@api`; collaborator classes are `@internal` | | 27 | Handler seam | `ExceptionHandlerInterface`, implemented by `ExceptionHandler`, is what `ExceptionMiddleware` depends on | | 28 | `title` / `detail` | `title` is the phrase for the status from `codeinc/http-reason-phrase-lookup`'s `HttpReasonPhraseLookup::getReasonPhrase()`, or the code when no phrase is registered; `detail` carries the exception identity — short class name in minimal, `class: message` in full | @@ -119,12 +130,10 @@ src/ Document/Problem.php final readonly, JsonSerializable Document/Trace.php final readonly, JsonSerializable Document/Frame.php final readonly, JsonSerializable - Document/SanitizedObject.php final readonly, JsonSerializable - Document/SanitizedMap.php final readonly, JsonSerializable Path/PathRelativizer.php final class Trace/TraceFactory.php final class Trace/SourceContext.php final class - Trace/ArgumentSanitizer.php final class + Trace/ArgumentTyper.php final class tests/ Fixtures/ source files and traces used by tests ``` @@ -274,7 +283,7 @@ final readonly class Frame implements JsonSerializable public ?string $function = null, public ?string $class = null, public ?string $type = null, - /** @var list|null */ + /** @var list|null */ public ?array $args = null, public ?string $source = null, ) {} @@ -282,62 +291,32 @@ final readonly class Frame implements JsonSerializable #[Override] public function jsonSerialize(): array; } - -/** @api */ -final readonly class SanitizedObject implements JsonSerializable -{ - public function __construct( - public string $class, - /** @var array */ - public array $properties, - ) {} - - #[Override] - public function jsonSerialize(): array; -} - -/** @api */ -final readonly class SanitizedMap implements JsonSerializable -{ - public function __construct( - /** @var array */ - public array $entries, - ) {} - - #[Override] - public function jsonSerialize(): array; -} ``` Serialization rules: - `Problem::jsonSerialize()` emits members in this order: `type`, `title`, `status`, `code`, `detail`, `file`, `line`, `source`, - `trace`, `traceTruncated`, `previous`. `title` is the status phrase + `trace`, `truncated`, `previous`. `title` is the status phrase (from `codeinc/http-reason-phrase-lookup`'s `HttpReasonPhraseLookup::getReasonPhrase()`) and `detail` the exception identity (short class name in minimal, `class: message` in full). It omits every member whose value is `null` or `false`, including `source` when it is `null`. `trace` is emitted as the frame list (`$this->trace` serializes to it); - `traceTruncated` is emitted only when `$this->trace->truncated` is + `truncated` is emitted only when `$this->trace->truncated` is `true`, so `Problem` holds no duplicated truncation flag. - `Frame::jsonSerialize()` omits null members, including a null `args`. - `args` is emitted only when PHP reported arguments for the frame, so - `args: []` is a reported empty list and an absent `args` member means - PHP did not report arguments (as with - `zend.exception_ignore_args=On`). `source` is omitted only when `null`, - not when it is an empty or whitespace-only string. + `args` is a list of type names (see "Argument types") and is emitted + only when PHP reported arguments for the frame, so `args: []` is a + reported empty list and an absent `args` member means PHP did not + report arguments (as with `zend.exception_ignore_args=On`). `source` + is omitted only when `null`, not when it is an empty or + whitespace-only string. - `Trace::jsonSerialize()` returns the frame list, so a `Trace` is exactly the value of the document's `trace` member. -- `SanitizedObject` serializes as - `{"@class": "", "props": {...}}`; `SanitizedMap` serializes as - its entries, i.e. as a JSON object. -`SanitizedMap` exists only to keep string-keyed maps off the API surface: -a sanitized argument that is a PHP map is returned as a DTO, not a bare -array, while its JSON form stays an object. `Problem`, `Trace`, and -`Frame` likewise never hand out structural arrays. +`Problem`, `Trace`, and `Frame` never hand out structural arrays. ### Mode detection @@ -426,8 +405,7 @@ and inventing a URI would be worse than omitting it. Throwable::getTrace() ──▶ TraceFactory ──▶ Document\Trace ├─▶ PathRelativizer relativize ├─▶ SourceContext source lines (every frame) - └─▶ ArgumentSanitizer args - └─▶ SanitizedObject / SanitizedMap / lists + └─▶ ArgumentTyper argument types ``` `TraceFactory` takes the trace array as an explicit input, not a @@ -445,7 +423,7 @@ final class TraceFactory public function __construct( private PathRelativizer $relativizer, private SourceContext $source, - private ArgumentSanitizer $arguments, + private ArgumentTyper $types, private int $traceLimit, ) {} @@ -460,9 +438,9 @@ final class SourceContext public function line(string $absolutePath, int $line): ?string; } -final class ArgumentSanitizer +final class ArgumentTyper { - public function sanitize(mixed $value): mixed; + public function type(mixed $value): string; } ``` @@ -483,8 +461,8 @@ Per-frame members: `file`, `line`, `function`, `class`, `type`, `args`, - PHP embeds source paths in closure function names (`{closure:/absolute/file.php:line}`) and anonymous class names (after a NUL byte, before the `:line$ordinal` suffix). Relativize those embedded paths when they are under the application directory, preserving the surrounding PHP-generated name; paths outside it keep `PathRelativizer`'s absolute-path behavior. - `type` is `->` for instance method calls and `::` for static calls, matching the keys PHP itself provides in a trace entry. -- `args` is present only when PHP reported arguments for the frame. - PHP omits the `args` key entirely when +- `args` is present only when PHP reported arguments for the frame, and is a list of type names (see + "Argument types"). PHP omits the `args` key entirely when `zend.exception_ignore_args=On`; `TraceFactory` normalizes that (and a malformed key) to `null`, so the member is omitted. A frame PHP reports with an empty argument list still carries `args: []`. @@ -494,7 +472,7 @@ Per-frame members: `file`, `line`, `function`, `class`, `type`, `args`, PHP already lists the frame nearest the throw first, so `trace[0]` is that frame. `traceLimit` keeps the innermost N frames; dropping any frame sets `Trace::$truncated`, which `Problem` reports as -`traceTruncated: true`. +`truncated: true`. ### Source lines @@ -515,48 +493,34 @@ Implementation: read the file once per distinct path with `trim()` it. Caching per instance prevents re-reading a file that appears in several frames. -### Argument sanitizer +### Argument types -A total function: it may not throw, may not invoke user code, and may -not loop forever. Contract: +A total function: it may not throw and may not invoke user code. It +returns one type name per argument, in order; the value itself never +appears. Contract: | Input | Output | |-------|--------| -| `null`, `bool`, `int`, `float` | verbatim | -| `string` | verbatim up to 500 bytes, else first 500 bytes + `...` | -| list array | `list` of sanitized values, up to 50 entries | -| map array | `SanitizedMap`, up to 50 entries | -| `SensitiveParameterValue` | `"*redacted*"` | -| other object | `SanitizedObject` (class name + up to 50 public properties) | -| `Closure` | `"Closure"` | -| `enum` | `"::"` | -| resource | `"resource()"` (via `get_resource_type()`) | -| anything past depth 5 | `"*depth limit*"` | +| array, `array_is_list()` true | `"vec"` | +| array, otherwise | `"dict"` | +| `SensitiveParameterValue` | the type of `getValue()` | +| anything else | `get_debug_type()` | Rules: -- Arrays are split by key: a list stays a list (`array_is_list()`), a map - becomes a `SanitizedMap`. A list is never serialized as a JSON object - and a map is never serialized as a JSON array. -- Cycles are detected with `SplObjectStorage`; a repeated object is - emitted as `SanitizedObject` with an empty property map. -- Public properties come from `get_object_vars()` called in the - sanitizer's own scope, which returns public properties only and does - not trigger `__get`. Uninitialized typed properties are absent - automatically. At most 50 properties are kept, and the rest are - summarized with the `*truncated*` marker. `__debugInfo`, `__toString`, - and `JsonSerializable` are never invoked. -- `SensitiveParameterValue` is detected with `instanceof` before any - other object branch, and `getValue()` is never called. PHP redacts - sensitive parameters in the trace by substituting this object, so - respecting it is a correctness requirement, not a nicety. Verified on - PHP 8.5.11: the substituted object's type is `SensitiveParameterValue`, - exposing `__construct`, `getValue`, `__debugInfo`. -- Truncation is marked in the payload, because a JSON array cannot carry - a named marker: a truncated list ends with the string - `"... (N more items)"`, and a truncated map or object gains the entry - `"*truncated*": "N more items"`. Array keys are stringified the same - way `json_encode()` would. +- `get_debug_type()` names scalars (`null`, `bool`, `int`, `float`, + `string`), objects and enums by FQCN, closures as `Closure`, and + resources as `resource (stream)` or `resource (closed)`. +- Arrays are split by key: a list is `vec` and anything else is `dict`. +- A `SensitiveParameterValue` is unwrapped with `getValue()` and its + inner value typed; the value is never emitted. PHP redacts sensitive + parameters in the trace by substituting this object, so unwrapping it + reports the protected value's type without exposing the value. + `SensitiveParameterValue` is `final`, so `getValue()` cannot be + overridden and cannot run user code. Verified on PHP 8.5.11: the + substituted object's type is `SensitiveParameterValue`, exposing + `__construct`, `getValue`, `__debugInfo`. +- There is no depth, item, or length limit, because no value is emitted. ### Path relativization @@ -675,12 +639,10 @@ returning `false`. non-file paths, and reported lines before the start or beyond EOF. Assert the exact source string, and `null` only for unavailable context. Also verify the existing per-instance file cache. - - `ArgumentSanitizer`: scalars, long strings, list and map arrays, - `array_is_list()` divergence (`[0 => 'a', 2 => 'b']`), 50+ entries in - both shapes, nesting past depth 5, cyclic object graphs, - `SensitiveParameterValue`, closures, enums, resources, objects with - public/private/protected properties, and objects with a throwing - `__toString`. + - `ArgumentTyper`: scalars, `vec`/`dict` arrays including + `array_is_list()` divergence (`[0 => 'a', 2 => 'b']`), objects, + closures, enums, open and closed resources, and + `SensitiveParameterValue` unwrapping to a scalar and to an array. - `PathRelativizer`: a path inside the project directory, a path outside it, a sibling directory whose name merely starts with the project directory name, and an unnormalized Composer path. The @@ -693,8 +655,7 @@ returning `false`. the project directory — still carrying its `source` line. - Document DTOs: each `jsonSerialize()` shape, member ordering and omission rules, null `source` omitted but blank source lines retained, - `traceTruncated` present only when truncated, and - `SanitizedMap`/`SanitizedObject` payload shapes. + and `truncated` present only when truncated. - `ExceptionHandler`: both modes, the status interface in and out of range, and chained exceptions. - Middleware integration tests use `nyholm/psr7`'s `Psr17Factory` with a diff --git a/src/Document/Frame.php b/src/Document/Frame.php index f7236c0..10a6836 100644 --- a/src/Document/Frame.php +++ b/src/Document/Frame.php @@ -21,7 +21,7 @@ public function __construct( public ?string $function = null, public ?string $class = null, public ?string $type = null, - /** @var list|null */ + /** @var list|null */ public ?array $args = null, public ?string $source = null, ) {} diff --git a/src/Document/Problem.php b/src/Document/Problem.php index dfb5823..b376354 100644 --- a/src/Document/Problem.php +++ b/src/Document/Problem.php @@ -25,24 +25,6 @@ */ private const string TYPE = 'about:blank'; - // @mago-ignore lint:excessive-parameter-list - public function __construct( - public string $type, - public string $title, - public int $status, - public int $code, - public ?string $detail = null, - public ?string $file = null, - public ?int $line = null, - public ?string $source = null, - public ?Trace $trace = null, - public ?Problem $previous = null, - ) {} - - /** - * The minimal document: the status phrase, the short class name as - * `detail`, and the code, nothing else. - */ public static function minimal(Throwable $exception, int $status): self { return new self( @@ -54,15 +36,8 @@ public static function minimal(Throwable $exception, int $status): self ); } - /** - * The full document: everything `minimal()` carries, plus `detail` - * as `class: message`, the origin, the source line, the trace, - * and the cause. - * - * - * @mago-ignore lint:excessive-parameter-list - */ - public static function development( + // @mago-ignore lint:excessive-parameter-list + public static function full( Throwable $exception, int $status, string $file, @@ -85,6 +60,20 @@ public static function development( ); } + // @mago-ignore lint:excessive-parameter-list + public function __construct( + public string $type, + public string $title, + public int $status, + public int $code, + public ?string $detail = null, + public ?string $file = null, + public ?int $line = null, + public ?string $source = null, + public ?Trace $trace = null, + public ?Problem $previous = null, + ) {} + /** * @return array */ @@ -118,7 +107,7 @@ public function jsonSerialize(): array $document['trace'] = $this->trace; if ($this->trace->truncated) { - $document['traceTruncated'] = true; + $document['truncated'] = true; } } @@ -129,39 +118,26 @@ public function jsonSerialize(): array return $document; } - /** - * The reason phrase for `$status`, from - * `codeinc/http-reason-phrase-lookup`. A status with no registered - * phrase falls back to the code itself, so the title is never empty. - */ private static function title(int $status): string { return HttpReasonPhraseLookup::getReasonPhrase($status) ?? (string) $status; } - /** - * The dev-mode exception identity: the short class name, then the - * message, always both. - */ private static function detail(Throwable $exception): string { return self::shortClass($exception) . ': ' . $exception->getMessage(); } - /** - * The unqualified class name, truncated at the NUL byte that an - * anonymous class carries before its origin path. - */ private static function shortClass(Throwable $exception): string { $class = $exception::class; - $nul = strpos(haystack: $class, needle: "\0"); + $nul = strpos($class, needle: "\0"); if ($nul !== false) { - $class = substr(string: $class, offset: 0, length: $nul); + $class = substr($class, offset: 0, length: $nul); } - $position = strrpos(haystack: $class, needle: '\\'); + $position = strrpos($class, needle: '\\'); return $position === false ? $class : substr($class, $position + 1); } diff --git a/src/Document/SanitizedMap.php b/src/Document/SanitizedMap.php deleted file mode 100644 index 2d28fa6..0000000 --- a/src/Document/SanitizedMap.php +++ /dev/null @@ -1,33 +0,0 @@ - */ - public array $entries, - ) {} - - /** - * @return array - */ - #[Override] - public function jsonSerialize(): array - { - return $this->entries; - } -} diff --git a/src/Document/SanitizedObject.php b/src/Document/SanitizedObject.php deleted file mode 100644 index fba561a..0000000 --- a/src/Document/SanitizedObject.php +++ /dev/null @@ -1,31 +0,0 @@ - */ - public array $properties, - ) {} - - /** - * @return array - */ - #[Override] - public function jsonSerialize(): array - { - return ['@class' => $this->class, 'props' => $this->properties]; - } -} diff --git a/src/Document/Trace.php b/src/Document/Trace.php index 6e65cbd..3aefb1f 100644 --- a/src/Document/Trace.php +++ b/src/Document/Trace.php @@ -10,9 +10,6 @@ /** * The trace section of a problem document. * - * Serializes to the frame list, so a `Trace` is exactly the value of the - * document's `trace` member. - * * @api */ final readonly class Trace implements JsonSerializable diff --git a/src/ExceptionHandler.php b/src/ExceptionHandler.php index 4bc10a5..e14f5d3 100644 --- a/src/ExceptionHandler.php +++ b/src/ExceptionHandler.php @@ -7,7 +7,7 @@ use Errata\Document\Problem; use Errata\Http\StatusCodeInterface; use Errata\Path\PathRelativizer; -use Errata\Trace\ArgumentSanitizer; +use Errata\Trace\ArgumentTyper; use Errata\Trace\SourceContext; use Errata\Trace\TraceFactory; use Override; @@ -18,33 +18,27 @@ * * @api */ -final class ExceptionHandler implements ExceptionHandlerInterface +final readonly class ExceptionHandler implements ExceptionHandlerInterface { private const int DEFAULT_TRACE_LIMIT = 30; - private readonly PathRelativizer $relativizer; + private PathRelativizer $relativizer; + private SourceContext $source; + private TraceFactory $trace; - private readonly SourceContext $source; - - private readonly TraceFactory $trace; - - /** - * A negative cap is clamped rather than trusted: `array_slice()` - * treats a negative length as a count from the end, so it cannot - * mean "at most N frames". - */ public function __construct( - private readonly Mode $mode, + private Mode $mode, ?string $projectDir = null, int $traceLimit = self::DEFAULT_TRACE_LIMIT, ) { + // Negative values MUST be clamped, otherwise array_slice() will count from the end. if ($traceLimit < 0) { $traceLimit = 0; } $this->relativizer = new PathRelativizer($projectDir); $this->source = new SourceContext(); - $this->trace = new TraceFactory($this->relativizer, $this->source, new ArgumentSanitizer(), $traceLimit); + $this->trace = new TraceFactory($this->relativizer, $this->source, new ArgumentTyper(), $traceLimit); } #[Override] @@ -61,7 +55,7 @@ public function handle(Throwable $exception): Problem /** @var list> $trace */ $trace = $exception->getTrace(); - return Problem::development( + return Problem::full( exception: $exception, status: $status, file: $this->relativizer->relativize($exception->getFile()), diff --git a/src/Http/StatusCodeInterface.php b/src/Http/StatusCodeInterface.php index f66b7b0..f1e39c2 100644 --- a/src/Http/StatusCodeInterface.php +++ b/src/Http/StatusCodeInterface.php @@ -5,9 +5,7 @@ namespace Errata\Http; /** - * Implemented by exceptions that carry their own HTTP status code. - * - * Values outside 400..599 are ignored in favour of 500. + * Optional interface for exceptions to define an HTTP status code. * * @api */ diff --git a/src/Middleware/ExceptionMiddleware.php b/src/Middleware/ExceptionMiddleware.php index 55ec5c3..86d07cc 100644 --- a/src/Middleware/ExceptionMiddleware.php +++ b/src/Middleware/ExceptionMiddleware.php @@ -57,13 +57,11 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface } } - /** - * Everything past this point runs while an exception is already - * being reported, so each step is guarded: a failure to report must - * not become a failure to respond. - */ private function respond(ServerRequestInterface $request, Throwable $exception): ResponseInterface { + // Everything past this point runs while an exception is already + // being reported, so each step is guarded: a failure to report must + // not become a failure to respond. try { $problem = $this->handler->handle($exception); } catch (Throwable $failure) { @@ -113,21 +111,16 @@ private function log(ServerRequestInterface $request, Throwable $exception, int */ private static function encode(Problem $problem): array { + $flags = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE; + try { - $body = json_encode( - value: $problem, - flags: JSON_UNESCAPED_SLASHES - | JSON_UNESCAPED_UNICODE - | JSON_INVALID_UTF8_SUBSTITUTE - | JSON_THROW_ON_ERROR, - ); + $body = json_encode($problem, $flags); } catch (Throwable $failure) { error_log(sprintf('errata: could not encode the problem document: %s', $failure->getMessage())); return [500, self::FALLBACK_BODY]; } - /** @var string $body */ return [$problem->status, $body]; } } diff --git a/src/Mode.php b/src/Mode.php index 08b916c..4842fae 100644 --- a/src/Mode.php +++ b/src/Mode.php @@ -25,9 +25,7 @@ enum Mode: string /** * Detects the mode from the process environment. * - * Reads `APP_ENV`, then `APP_DEBUG`. Unrecognised or absent values - * fall back to Minimal, because a mode that leaks internals must - * never be selected by accident. + * Checks both APP_ENV and APP_DEBUG to determine the appropriate mode. */ public static function fromEnv(): self { @@ -37,6 +35,10 @@ public static function fromEnv(): self return self::Full; } - return filter_var(getenv('APP_DEBUG'), FILTER_VALIDATE_BOOLEAN) ? self::Full : self::Minimal; + if (filter_var(getenv('APP_DEBUG'), FILTER_VALIDATE_BOOLEAN)) { + return self::Full; + } + + return self::Minimal; } } diff --git a/src/Path/PathRelativizer.php b/src/Path/PathRelativizer.php index 001b6d5..54fa35b 100644 --- a/src/Path/PathRelativizer.php +++ b/src/Path/PathRelativizer.php @@ -9,6 +9,7 @@ use function array_pop; use function explode; use function implode; +use function is_string; use function realpath; use function rtrim; use function str_replace; @@ -21,28 +22,23 @@ * * @internal */ -final class PathRelativizer +final readonly class PathRelativizer { private const string SEPARATOR = '/'; - private readonly string $projectDir; + private string $projectDir; - /** - * `$projectDir` defaults to the Composer root package directory. - */ public function __construct(?string $projectDir = null) { - $this->projectDir = rtrim(self::resolve($projectDir ?? self::composerRoot()), self::SEPARATOR); + // Composer root MUST be resolved like any other directory, it is NOT normalized. + $projectDir ??= InstalledVersions::getRootPackage()['install_path']; + + $this->projectDir = rtrim(self::resolve($projectDir), self::SEPARATOR); } - /** - * Paths under the project directory lose the prefix and keep `/` - * separators. Paths outside it stay absolute: a `../../../usr/lib` - * chain is noise, not information. - */ public function relativize(string $absolutePath): string { - $path = self::collapse($absolutePath); + $path = self::resolve($absolutePath); $prefix = $this->projectDir . self::SEPARATOR; if (!str_starts_with($path, $prefix)) { @@ -52,24 +48,17 @@ public function relativize(string $absolutePath): string return substr($path, strlen($prefix)); } - /** - * Composer's `install_path` is unnormalized — it ends in - * `composer/../../` — so `realpath()` comes first. - */ private static function resolve(string $path): string { $real = realpath($path); - return self::collapse($real === false ? $path : $real); - } + if (is_string($real)) { + return str_replace('\\', self::SEPARATOR, $real); + } - /** - * Pure string normalization, no filesystem access. - */ - private static function collapse(string $path): string - { $path = str_replace('\\', self::SEPARATOR, $path); $rooted = str_starts_with($path, self::SEPARATOR); + /** @var list $segments */ $segments = []; @@ -86,18 +75,12 @@ private static function collapse(string $path): string $segments[] = $segment; } - return ($rooted ? self::SEPARATOR : '') . implode(self::SEPARATOR, $segments); - } + $resolved = implode(self::SEPARATOR, $segments); - /** - * Composer guarantees `Composer\InstalledVersions` — composer-runtime-api - * is a hard requirement — so there is no fallback path to test. - */ - private static function composerRoot(): string - { - /** @var array{install_path: string} $package */ - $package = InstalledVersions::getRootPackage(); + if ($rooted) { + return self::SEPARATOR . $resolved; + } - return $package['install_path']; + return $resolved; } } diff --git a/src/Trace/ArgumentSanitizer.php b/src/Trace/ArgumentSanitizer.php deleted file mode 100644 index 448f3b2..0000000 --- a/src/Trace/ArgumentSanitizer.php +++ /dev/null @@ -1,187 +0,0 @@ - - */ - private SplObjectStorage $processing; - - public function __construct() - { - /** @var SplObjectStorage $processing */ - $processing = new SplObjectStorage(); - - $this->processing = $processing; - } - - public function sanitize(mixed $value): mixed - { - return $this->sanitizeValue($value, 0); - } - - private function sanitizeValue(mixed $value, int $depth): mixed - { - return match (true) { - $depth >= self::MAX_DEPTH => '*depth limit*', - $value === null, is_bool($value), is_int($value) => $value, - is_float($value) => self::float($value), - is_string($value) => $this->sanitizeString($value), - is_array($value) => $this->sanitizeArray($value, $depth), - $value instanceof SensitiveParameterValue => '*redacted*', - $value instanceof Closure => 'Closure', - $value instanceof UnitEnum => $value::class . '::' . $value->name, - is_object($value) => $this->sanitizeObject($value, $depth), - is_resource($value) => 'resource(' . get_resource_type($value) . ')', - default => 'resource(closed)', - }; - } - - /** - * `json_encode()` refuses INF and NAN, and a document that cannot be - * encoded is a document that cannot be reported, so non-finite - * floats become their names. - */ - private static function float(float $value): float|string - { - if (is_finite($value)) { - return $value; - } - - if (is_nan($value)) { - return 'NAN'; - } - - return $value > 0.0 ? 'INF' : '-INF'; - } - - private function sanitizeString(string $value): string - { - if (strlen($value) <= self::MAX_STRING_LENGTH) { - return $value; - } - - return substr(string: $value, offset: 0, length: self::MAX_STRING_LENGTH) . '...'; - } - - /** - * A list stays a list; anything else becomes a SanitizedMap. - * - * @param array $value - * - * @return list|SanitizedMap - */ - private function sanitizeArray(array $value, int $depth): array|SanitizedMap - { - $total = count($value); - $slice = array_slice(array: $value, offset: 0, length: self::MAX_ITEMS, preserve_keys: true); - - if (array_is_list($value)) { - $items = []; - - /** @var mixed $item */ - foreach ($slice as $item) { - $items[] = $this->sanitizeValue($item, $depth + 1); - } - - if ($total > self::MAX_ITEMS) { - $items[] = sprintf('... (%d more items)', $total - self::MAX_ITEMS); - } - - return $items; - } - - return new SanitizedMap($this->sanitizeEntries($slice, $depth, $total)); - } - - /** - * Sanitizes a capped slice of entries, appending the truncation marker - * when the source held more items than the cap. - * - * @param array $slice - * - * @return array - */ - private function sanitizeEntries(array $slice, int $depth, int $total): array - { - $entries = []; - - /** @var mixed $item */ - foreach ($slice as $key => $item) { - $entries[(string) $key] = $this->sanitizeValue($item, $depth + 1); - } - - if ($total > self::MAX_ITEMS) { - $entries['*truncated*'] = sprintf('%d more items', $total - self::MAX_ITEMS); - } - - return $entries; - } - - private function sanitizeObject(object $value, int $depth): SanitizedObject - { - if ($this->processing->offsetExists($value)) { - return new SanitizedObject($value::class, []); - } - - $this->processing->offsetSet($value, null); - - try { - /** @var array $all */ - $all = get_object_vars($value); - $slice = array_slice(array: $all, offset: 0, length: self::MAX_ITEMS, preserve_keys: true); - - return new SanitizedObject($value::class, $this->sanitizeEntries($slice, $depth, count($all))); - } finally { - $this->processing->offsetUnset($value); - } - } -} diff --git a/src/Trace/ArgumentTyper.php b/src/Trace/ArgumentTyper.php new file mode 100644 index 0000000..730f154 --- /dev/null +++ b/src/Trace/ArgumentTyper.php @@ -0,0 +1,38 @@ +type($value->getValue()); + } + + if (is_array($value)) { + return array_is_list($value) ? 'vec' : 'dict'; + } + + return get_debug_type($value); + } +} diff --git a/src/Trace/TraceFactory.php b/src/Trace/TraceFactory.php index 8719e3c..d668ea9 100644 --- a/src/Trace/TraceFactory.php +++ b/src/Trace/TraceFactory.php @@ -33,7 +33,7 @@ final class TraceFactory public function __construct( private readonly PathRelativizer $relativizer, private readonly SourceContext $source, - private readonly ArgumentSanitizer $arguments, + private readonly ArgumentTyper $types, private readonly int $traceLimit, ) {} @@ -125,7 +125,7 @@ private function relativizePath(array $matches): string * * @param array $entry * - * @return list|null + * @return list|null */ private function args(array $entry): ?array { @@ -133,7 +133,7 @@ private function args(array $entry): ?array return null; } - return array_map($this->arguments->sanitize(...), array_values($entry['args'])); + return array_map($this->types->type(...), array_values($entry['args'])); } /** diff --git a/tests/Document/FrameTest.php b/tests/Document/FrameTest.php index b7e74e1..d34f08c 100644 --- a/tests/Document/FrameTest.php +++ b/tests/Document/FrameTest.php @@ -34,7 +34,7 @@ public function testItOmitsNullMembersAndNullSource(): void function: 'run', class: 'App\Foo', type: '->', - args: [1], + args: ['int'], source: null, ); @@ -45,7 +45,7 @@ class: 'App\Foo', 'function' => 'run', 'class' => 'App\Foo', 'type' => '->', - 'args' => [1], + 'args' => ['int'], ], $frame->jsonSerialize(), ); diff --git a/tests/Document/ProblemTest.php b/tests/Document/ProblemTest.php index 7cc0bfb..53e1125 100644 --- a/tests/Document/ProblemTest.php +++ b/tests/Document/ProblemTest.php @@ -77,7 +77,7 @@ public function testDevelopmentCarriesEveryDevelopmentMember(): void { $previous = Problem::minimal(new RuntimeException('cause'), 500); $source = ' throw new RuntimeException();'; - $problem = Problem::development( + $problem = Problem::full( exception: new RuntimeException('boom', 3), status: 422, file: 'src/Foo.php', @@ -114,7 +114,7 @@ public function testDevelopmentCarriesEveryDevelopmentMember(): void public function testDevelopmentOmitsANullSourceAndANullPrevious(): void { - $problem = Problem::development( + $problem = Problem::full( exception: new RuntimeException('boom'), status: 500, file: 'src/Foo.php', @@ -129,12 +129,12 @@ public function testDevelopmentOmitsANullSourceAndANullPrevious(): void $this->assertNull($problem->source); $this->assertArrayNotHasKey('source', $serialized); $this->assertArrayNotHasKey('previous', $serialized); - $this->assertArrayNotHasKey('traceTruncated', $serialized); + $this->assertArrayNotHasKey('truncated', $serialized); } public function testDevelopmentIncludesAnEmptySourceLine(): void { - $problem = Problem::development( + $problem = Problem::full( exception: new RuntimeException('boom'), status: 500, file: 'src/Foo.php', @@ -162,7 +162,7 @@ public function testItIncludesAWhitespaceOnlySourceLineWhenConstructedDirectly() public function testDevelopmentFlagsATruncatedTrace(): void { - $problem = Problem::development( + $problem = Problem::full( exception: new RuntimeException('boom'), status: 500, file: 'src/Foo.php', @@ -172,7 +172,7 @@ public function testDevelopmentFlagsATruncatedTrace(): void previous: null, ); - $this->assertTrue($problem->jsonSerialize()['traceTruncated'] ?? false); + $this->assertTrue($problem->jsonSerialize()['truncated'] ?? false); } public function testItCanBeConstructedDirectly(): void diff --git a/tests/Document/SanitizedMapTest.php b/tests/Document/SanitizedMapTest.php deleted file mode 100644 index 5e75f87..0000000 --- a/tests/Document/SanitizedMapTest.php +++ /dev/null @@ -1,21 +0,0 @@ -assertSame( - ['alpha' => 1, 'beta' => 'two'], - new SanitizedMap(['alpha' => 1, 'beta' => 'two'])->jsonSerialize(), - ); - } -} diff --git a/tests/Document/SanitizedObjectTest.php b/tests/Document/SanitizedObjectTest.php deleted file mode 100644 index e54d9f6..0000000 --- a/tests/Document/SanitizedObjectTest.php +++ /dev/null @@ -1,21 +0,0 @@ -assertSame( - ['@class' => 'App\Thing', 'props' => ['id' => 1]], - new SanitizedObject('App\Thing', ['id' => 1])->jsonSerialize(), - ); - } -} diff --git a/tests/ExceptionHandlerTest.php b/tests/ExceptionHandlerTest.php index fac476c..9616d07 100644 --- a/tests/ExceptionHandlerTest.php +++ b/tests/ExceptionHandlerTest.php @@ -69,7 +69,7 @@ public function testFullCarriesTheMessageLocationAndSourceLine(): void $this->assertArrayHasKey('source', $document); $this->assertSame($problem->source, $document['source']); $this->assertInstanceOf(Trace::class, $problem->trace); - $this->assertStringNotContainsString('traceTruncated', (string) json_encode($problem)); + $this->assertStringNotContainsString('truncated', (string) json_encode($problem)); $this->assertNull($problem->previous); } diff --git a/tests/Trace/ArgumentSanitizerEnum.php b/tests/Trace/ArgumentSanitizerEnum.php deleted file mode 100644 index 5db25ef..0000000 --- a/tests/Trace/ArgumentSanitizerEnum.php +++ /dev/null @@ -1,11 +0,0 @@ - - */ - public function values(): array - { - return [$this->public, $this->protected, $this->private]; - } -} diff --git a/tests/Trace/ArgumentSanitizerHostileFixture.php b/tests/Trace/ArgumentSanitizerHostileFixture.php deleted file mode 100644 index 9058185..0000000 --- a/tests/Trace/ArgumentSanitizerHostileFixture.php +++ /dev/null @@ -1,18 +0,0 @@ -sanitizer = new ArgumentSanitizer(); - } - - public function testItPassesScalarsThroughUnchanged(): void - { - $this->assertNull($this->sanitizer->sanitize(null)); - $this->assertTrue($this->sanitizer->sanitize(true)); - $this->assertSame(7, $this->sanitizer->sanitize(7)); - $this->assertSame(1.5, $this->sanitizer->sanitize(1.5)); - $this->assertSame('short', $this->sanitizer->sanitize('short')); - } - - public function testItNamesNonFiniteFloatsSoTheDocumentStaysEncodable(): void - { - $this->assertSame(1.5, $this->sanitizer->sanitize(1.5)); - $this->assertSame('INF', $this->sanitizer->sanitize(fdiv(num1: 1.0, num2: 0.0))); - $this->assertSame('-INF', $this->sanitizer->sanitize(fdiv(num1: -1.0, num2: 0.0))); - $this->assertSame('NAN', $this->sanitizer->sanitize(acos(2.0))); - } - - public function testItTruncatesLongStrings(): void - { - /** @var string $sanitized */ - $sanitized = $this->sanitizer->sanitize(str_repeat(string: 'a', times: 501)); - - $this->assertIsString($sanitized); - $this->assertSame(503, strlen($sanitized)); - $this->assertStringEndsWith('...', $sanitized); - } - - public function testItKeepsListsAsLists(): void - { - $this->assertSame([1, 'two'], $this->sanitizer->sanitize([1, 'two'])); - } - - public function testItTreatsNonSequentialKeysAsAMap(): void - { - /** @var SanitizedMap $sanitized */ - $sanitized = $this->sanitizer->sanitize([0 => 'a', 2 => 'b']); - - $this->assertInstanceOf(SanitizedMap::class, $sanitized); - $this->assertSame('{"0":"a","2":"b"}', json_encode($sanitized)); - } - - public function testItMarksATruncatedList(): void - { - $json = json_encode($this->sanitizer->sanitize(range(start: 1, end: 60))); - - $this->assertIsString($json); - $this->assertStringEndsWith(',"... (10 more items)"]', $json); - $this->assertSame(51, substr_count(haystack: $json, needle: ',') + 1); - } - - public function testItMarksATruncatedMap(): void - { - $entries = []; - - for ($i = 0; $i < 60; $i++) { - $entries['key' . $i] = $i; - } - - /** @var SanitizedMap $sanitized */ - $sanitized = $this->sanitizer->sanitize($entries); - - $this->assertInstanceOf(SanitizedMap::class, $sanitized); - $this->assertSame(51, count($sanitized->entries)); - $this->assertSame( - ['*truncated*' => '10 more items'], - array_slice(array: $sanitized->entries, offset: -1, length: null, preserve_keys: true), - ); - } - - public function testItStopsAtTheDepthLimit(): void - { - $nested = ['end']; - - for ($i = 0; $i < 10; $i++) { - $nested = [$nested]; - } - - $json = json_encode($this->sanitizer->sanitize($nested)); - - $this->assertIsString($json); - $this->assertStringContainsString('*depth limit*', $json); - $this->assertSame(5, substr_count(haystack: $json, needle: '[')); - } - - public function testItEmptiesARepeatedObjectInsteadOfRecursing(): void - { - $node = new stdClass(); - $node->self = $node; - - $this->assertSame( - '{"@class":"stdClass","props":{"self":{"@class":"stdClass","props":[]}}}', - json_encode($this->sanitizer->sanitize($node)), - ); - } - - public function testItKeepsPublicPropertiesOnly(): void - { - $json = json_encode($this->sanitizer->sanitize(new ArgumentSanitizerFixture())); - - $this->assertIsString($json); - $this->assertStringContainsString('"props":{"public":"yes"}', $json); - $this->assertStringNotContainsString('protected', $json); - $this->assertStringNotContainsString('private', $json); - } - - public function testItCapsThePublicPropertiesOfAnObject(): void - { - /** @var SanitizedObject $sanitized */ - $sanitized = $this->sanitizer->sanitize(ArgumentSanitizerManyPropertiesFixture::withSixtyProperties()); - - $this->assertInstanceOf(SanitizedObject::class, $sanitized); - $this->assertSame(51, count($sanitized->properties)); - $this->assertSame('10 more items', $sanitized->properties['*truncated*'] ?? ''); - } - - public function testItNeverCallsToString(): void - { - /** @var SanitizedObject $sanitized */ - $sanitized = $this->sanitizer->sanitize(new ArgumentSanitizerHostileFixture()); - - $this->assertInstanceOf(SanitizedObject::class, $sanitized); - $this->assertSame([], $sanitized->properties); - } - - public function testItRedactsSensitiveParameters(): void - { - $this->assertSame('*redacted*', $this->sanitizer->sanitize(new SensitiveParameterValue('hunter2'))); - } - - public function testItNamesClosuresAndEnums(): void - { - $this->assertSame('Closure', $this->sanitizer->sanitize(static fn(): int => 1)); - $this->assertSame( - 'Errata\Tests\Trace\ArgumentSanitizerEnum::Second', - $this->sanitizer->sanitize(ArgumentSanitizerEnum::Second), - ); - } - - public function testItDescribesResources(): void - { - $handle = fopen(filename: 'php://memory', mode: 'r'); - - $this->assertSame('resource(stream)', $this->sanitizer->sanitize($handle)); - - fclose($handle); - - $this->assertSame('resource(closed)', $this->sanitizer->sanitize($handle)); - } - - public function testItSanitizesPropertiesRecursively(): void - { - $payload = new stdClass(); - $payload->token = new SensitiveParameterValue('hunter2'); - $payload->nested = ['a' => str_repeat(string: 'b', times: 501)]; - - $json = json_encode($this->sanitizer->sanitize($payload)); - - $this->assertIsString($json); - $this->assertStringContainsString('"token":"*redacted*"', $json); - $this->assertStringContainsString('"nested":{"a":"' . str_repeat(string: 'b', times: 500) . '..."}', $json); - } -} diff --git a/tests/Trace/ArgumentTyperTest.php b/tests/Trace/ArgumentTyperTest.php new file mode 100644 index 0000000..bb3d831 --- /dev/null +++ b/tests/Trace/ArgumentTyperTest.php @@ -0,0 +1,72 @@ +typer = new ArgumentTyper(); + } + + public function testItNamesScalars(): void + { + $this->assertSame('null', $this->typer->type(null)); + $this->assertSame('bool', $this->typer->type(true)); + $this->assertSame('int', $this->typer->type(7)); + $this->assertSame('float', $this->typer->type(1.5)); + $this->assertSame('string', $this->typer->type('plain')); + } + + public function testItSplitsArraysIntoVecAndDict(): void + { + $this->assertSame('vec', $this->typer->type([1, 2])); + $this->assertSame('vec', $this->typer->type([])); + $this->assertSame('dict', $this->typer->type(['key' => 'value'])); + $this->assertSame('dict', $this->typer->type([0 => 'a', 2 => 'b'])); + } + + public function testItNamesObjectsClosuresAndEnums(): void + { + $this->assertSame(stdClass::class, $this->typer->type(new stdClass())); + $this->assertSame('Closure', $this->typer->type(static fn(): int => 1)); + $this->assertSame(Mode::class, $this->typer->type(Mode::Full)); + } + + public function testItNamesResources(): void + { + $handle = fopen(filename: 'php://memory', mode: 'r'); + + try { + $this->assertSame('resource (stream)', $this->typer->type($handle)); + } finally { + fclose($handle); + } + + $this->assertSame('resource (closed)', $this->typer->type($handle)); + } + + public function testItUnwrapsSensitiveParametersToTheProtectedType(): void + { + $this->assertSame('string', $this->typer->type(new SensitiveParameterValue('hunter2'))); + $this->assertSame('vec', $this->typer->type(new SensitiveParameterValue([1, 2]))); + $this->assertSame('dict', $this->typer->type(new SensitiveParameterValue(['a' => 1]))); + } +} diff --git a/tests/Trace/TraceFactoryTest.php b/tests/Trace/TraceFactoryTest.php index aa41aae..4b36742 100644 --- a/tests/Trace/TraceFactoryTest.php +++ b/tests/Trace/TraceFactoryTest.php @@ -6,7 +6,7 @@ use Errata\Document\Trace; use Errata\Path\PathRelativizer; -use Errata\Trace\ArgumentSanitizer; +use Errata\Trace\ArgumentTyper; use Errata\Trace\SourceContext; use Errata\Trace\TraceFactory; use LogicException; @@ -24,6 +24,7 @@ use function json_decode; use function json_encode; use function random_bytes; +use function realpath; use function sys_get_temp_dir; use function unlink; @@ -45,7 +46,7 @@ protected function setUp(): void $this->factory = new TraceFactory( new PathRelativizer($this->root), new SourceContext(), - new ArgumentSanitizer(), + new ArgumentTyper(), traceLimit: 30, ); } @@ -86,7 +87,8 @@ public function testItTrimsEmptyAndWhitespaceOnlySource(): void [" \t \r\n\t \r\n", 2, ''], [" \$x = 1; \n", 1, '$x = 1;'], ] as [$contents, $line, $source]) { - $path = sys_get_temp_dir() . '/errata-trace-source-' . bin2hex(random_bytes(8)) . '.php'; + // @mago-expect analysis:possibly-false-operand + $path = realpath(sys_get_temp_dir()) . '/errata-trace-source-' . bin2hex(random_bytes(8)) . '.php'; file_put_contents(filename: $path, data: $contents); try { @@ -183,7 +185,7 @@ public function testItCarriesClassTypeAndArguments(): void 'function' => 'run', 'class' => 'App\Thing', 'type' => '->', - 'args' => ['plain', new stdClass()], + 'args' => ['plain', new stdClass(), [1, 2], ['a' => 1]], ], ]); @@ -193,7 +195,7 @@ public function testItCarriesClassTypeAndArguments(): void 'function' => 'run', 'class' => 'App\Thing', 'type' => '->', - 'args' => ['plain', ['@class' => 'stdClass', 'props' => []]], + 'args' => ['string', 'stdClass', 'vec', 'dict'], ], ], $this->serialize($trace),