From 740f866081c8bc009372241a2ce340f64ca755d6 Mon Sep 17 00:00:00 2001 From: Woody Gilk Date: Thu, 1 Oct 2026 11:47:55 -0500 Subject: [PATCH] refactor(trace): report source as a single trimmed line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the `{start, end, code}` source block with a single `source` string: the source line at the reported line, trimmed of surrounding whitespace. The ±3 window and the `SourceBlock` DTO are removed. Update the spec, README, changelog, and tests to match. --- CHANGELOG.md | 6 +- README.md | 8 +- .../2026-09-30-snafu-exception-handler.md | 16 +- ...26-09-30-snafu-exception-handler-design.md | 179 ++++++------------ src/Document/Frame.php | 2 +- src/Document/Problem.php | 6 +- src/Document/SourceBlock.php | 32 ---- src/ExceptionHandler.php | 2 +- src/Mode.php | 2 +- src/Trace/SourceContext.php | 36 +--- src/Trace/TraceFactory.php | 2 +- tests/Document/FrameTest.php | 22 +-- tests/Document/ProblemTest.php | 20 +- tests/Document/SourceBlockTest.php | 21 -- tests/ExceptionHandlerTest.php | 24 +-- tests/Fixtures/source/utf8_failure.php | 3 +- tests/Middleware/ExceptionMiddlewareTest.php | 12 +- tests/Trace/SourceContextTest.php | 111 +++-------- tests/Trace/TraceFactoryTest.php | 38 ++-- 19 files changed, 149 insertions(+), 393 deletions(-) delete mode 100644 src/Document/SourceBlock.php delete mode 100644 tests/Document/SourceBlockTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 797e48d..5768a70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ### Changed -- Full responses now report source context as one `{start, end, code}` block with one `code` array element per line. - It covers the reported line ±3, clamped to the file, with blank lines and whitespace preserved. +- Full responses now report source context as a single `source` string: the source line at the reported line, + trimmed of surrounding whitespace. - Paths embedded in trace closure function names and anonymous class names are now relative to the application root. ### Added @@ -24,7 +24,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). - `ExceptionHandler`, which maps a `Throwable` to a `Problem` document. - `Mode` with full and minimal modes, detected from `APP_ENV` and `APP_DEBUG`. -- Full documents with message, origin, source blocks of up to seven lines, +- Full documents with message, origin, source lines, relative paths, traces, and chained causes. - Trace frames with truncated frame arguments; `#[\SensitiveParameter]` values are redacted and `__toString()` is never invoked. diff --git a/README.md b/README.md index 1c01e6d..edfd2aa 100644 --- a/README.md +++ b/README.md @@ -59,11 +59,9 @@ Paths are relative to the application directory, which defaults to the Composer overridden with the second `ExceptionHandler` argument. Paths embedded in PHP closure function names and anonymous class names are also made relative when they point inside the application directory. -The exception's origin and every frame carry one `source` object shaped as `{start, end, code}`. `start` and `end` -are inclusive file line numbers; `code` is an array with one string per source line. Empty strings represent blank -lines. It covers the reported line ±3, clamped to the file, preserving indentation and whitespace. Unavailable source -is omitted. Traces are capped at 30 frames (`traceLimit`), keeping the frames nearest the throw; a capped trace -is flagged with `traceTruncated`. +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`. 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 diff --git a/docs/superpowers/plans/2026-09-30-snafu-exception-handler.md b/docs/superpowers/plans/2026-09-30-snafu-exception-handler.md index ee499ec..b229181 100644 --- a/docs/superpowers/plans/2026-09-30-snafu-exception-handler.md +++ b/docs/superpowers/plans/2026-09-30-snafu-exception-handler.md @@ -4,17 +4,17 @@ **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 `Snafu\Document\` own the JSON contract; `Snafu\Trace\` holds the plumbing that reads source windows, sanitizes arguments, and assembles frames; `Snafu\Path\PathRelativizer` turns absolute paths into project-relative ones; `Snafu\ExceptionHandler` maps a `Throwable` to a `Problem`; `Snafu\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 `Snafu\Document\` own the JSON contract; `Snafu\Trace\` holds the plumbing that reads source lines, sanitizes arguments, and assembles frames; `Snafu\Path\PathRelativizer` turns absolute paths into project-relative ones; `Snafu\ExceptionHandler` maps a `Throwable` to a `Problem`; `Snafu\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. **Spec:** `docs/superpowers/specs/2026-09-30-snafu-exception-handler-design.md` — read it alongside this plan; it records why each decision was made. -> **Source-context amendments (2026-10-01, implemented):** The spec requires one `{start, end, code}` source -> block, `code` as an array of source lines, the reported line ±3, and preserved blank lines. This supersedes the -> `SourceLine` list, ±2 window, -> blank-line stripping, and related signatures/tests throughout this original implementation plan. These tasks -> describe the original design; the implementation now follows the amended spec. +> **Source-context amendments (2026-10-01, implemented):** The spec requires `source` as a single string: the +> source line at the reported line, trimmed of surrounding whitespace. This supersedes the `SourceLine` +> list, ±2 window, blank-line stripping, the `{start, end, code}` block, and related signatures/tests throughout +> this original implementation plan. These tasks describe the original design; the implementation now follows the +> amended spec. ## Global Constraints @@ -22,13 +22,13 @@ Copied from the spec; every task implicitly includes them. - PHP floor is 8.4 (`composer.json` `require.php` is the single source of truth and CI derives the CI version from it). Local dev runs 8.5.11 — never use an 8.5-only API (`array_first`, `|>`, `#[\NoDiscard]`). - Every class is `final` (mago `enforce-class-finality`). -- Docblock `@api` on: `Mode`, `ExceptionHandler`, `ExceptionMiddleware`, `Http\StatusCodeInterface`, and all six `Document\` DTOs. Docblock `@internal` on every other class (mago `require-api-or-internal`). +- Docblock `@api` on: `Mode`, `ExceptionHandler`, `ExceptionMiddleware`, `Http\StatusCodeInterface`, and all five `Document\` DTOs. Docblock `@internal` on every other class (mago `require-api-or-internal`). - Every overriding method carries `#[Override]`. - Full type hints on parameters, returns, and closures. Nullable parameters use explicit `?T` (PHP 8.4 deprecates implicit nullable). - 100% line coverage is enforced by `composer run test`. No unreachable line may exist in `src/`, because no test can cover it. - Test classes carry `#[CoversClass(...)]` (`phpunit.xml` sets `requireCoverageMetadata="true"`); test methods use the `test` prefix (verified: PHPUnit 13.3.6 `Util\Test::isTestMethod` still honours it). - Output is JSON only, media type `application/problem+json`, `type` is always `about:blank`, `title` is the recommended HTTP status phrase from `codeinc/http-reason-phrase-lookup`'s `HttpReasonPhraseLookup::getReasonPhrase()` (RFC 9457 §4.2.1), and `detail` carries the exception identity. -- Source context is one `{start, end, code}` block with one code-array element per line, for the reported line ±3, clamped to the file, preserving blank lines and whitespace, for the origin and every frame. +- Source context is the source line at the reported line, trimmed of surrounding whitespace, for the origin and every frame. - **There is no vendor detection.** No vendor flag, no vendor-directory config, no special case for third-party paths. - Document types are `JsonSerializable` DTOs. Bare PHP arrays appear only as *lists*, plus the two places PHP forces them: `jsonSerialize(): array` and `Throwable::getTrace()`'s input. - Argument truncation limits: depth 5, 50 items, 500-byte strings. Markers: `*depth limit*`, `*redacted*`, `*truncated*`, `... (N more items)`. diff --git a/docs/superpowers/specs/2026-09-30-snafu-exception-handler-design.md b/docs/superpowers/specs/2026-09-30-snafu-exception-handler-design.md index a8f3b06..9f9932a 100644 --- a/docs/superpowers/specs/2026-09-30-snafu-exception-handler-design.md +++ b/docs/superpowers/specs/2026-09-30-snafu-exception-handler-design.md @@ -5,15 +5,14 @@ Status: approved in brainstorming; pending review of this document ## Source-context amendments — 2026-10-01 -The source contract is `{line: int, source: {start: int, end: int, code: list}}`. The outer `line` -remains the reported line; `start` and `end` are the inclusive, original file line numbers of the contiguous -window. `code` contains one string per physical source line; blank lines are empty strings. The window is the -reported line ±3, with no blank lines removed. +The source contract is `{line: int, source: string}`. The outer `line` is the reported line; `source` is that +one physical source line, trimmed of surrounding whitespace. Unavailable source is omitted. -The first amendment chose a single multiline string for `code`. This follow-up replaces that representation -with a line array so JSON viewers display code line by line without escaped newline characters. Both amendments -change the existing response contract; no compatibility format is retained. The sections below describe the -current contract, and the implementation follows it. +Earlier amendments carried a `{start, end, code}` block covering the reported line ±3, first as one multiline +string and then as a line array. The surrounding lines proved unhelpful and the nested object read poorly in +JSON, so this amendment reduces `source` to the single reported line. Each amendment changes the existing +response contract; no compatibility format is retained. The sections below describe the current contract, and +the implementation follows it. ## Purpose @@ -34,7 +33,7 @@ Success criteria: short exception class name in `detail`, and the exception code, and nothing else that could leak internals. - Full bodies contain `detail` as `class: message`, the origin - `file`/`line`/`source`, and a frame list, each with a source block of up to 7 lines. + `file`/`line`/`source`, and a frame list, each with its source line. - No code path in the middleware can itself throw, including when logging fails or when JSON encoding fails. @@ -49,10 +48,9 @@ Success criteria: name in `detail`, and code only. 6. Full: additionally `detail` as `class: message`, file, line, trace. 7. Trace paths are relative to the application directory. -8. Context is the reported line ±3, clamped to the file, for the origin - and for every frame alike. -9. Context is one contiguous code block with inclusive `start` and `end` - line numbers; blank and whitespace-only lines are preserved. +8. Context is the source line at the reported line, for the origin and + for every frame alike. +9. Context is one source line, trimmed of surrounding whitespace. ## Decisions @@ -66,7 +64,7 @@ later changes. | 3 | Minimal body | Full-only members omitted entirely, never `null`; `detail` is the short class name | | 4 | Class structure | Separate `ExceptionHandler` + `ExceptionMiddleware` | | 5 | Logging | `LoggerInterface` optional (null disables), level configurable, default `LogLevel::ERROR` | -| 6 | Trace frame shape | Reported `line` plus one `source` object with `{start, end, code}`; `code` is a line array, and bounds are inclusive original file line numbers | +| 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 | @@ -83,7 +81,7 @@ later changes. | 20 | Objects in arguments | Class name plus at most 50 public properties | | 21 | Origin frame | Top-level `file`/`line`/`source` only; not duplicated into `trace` | | 22 | Response headers | `Content-Type: application/problem+json` only | -| 23 | Context window | Reported line ±3, clamped to the file, origin and frames alike; `code` is a line list with blank lines and whitespace preserved | +| 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 | | 26 | API markers | Document DTOs are `@api`; collaborator classes are `@internal` | @@ -121,7 +119,6 @@ src/ Document/Problem.php final readonly, JsonSerializable Document/Trace.php final readonly, JsonSerializable Document/Frame.php final readonly, JsonSerializable - Document/SourceBlock.php final readonly, JsonSerializable Document/SanitizedObject.php final readonly, JsonSerializable Document/SanitizedMap.php final readonly, JsonSerializable Path/PathRelativizer.php final class @@ -142,7 +139,7 @@ Every class is `final` (mago `enforce-class-finality`). Document DTOs, `Path/`, `Trace/`, and the internal members of the rest are marked `@internal` (mago `require-api-or-internal`). `Problem` is `@api` because it is the return type of `ExceptionHandlerInterface::handle()` -and holds `Trace`, `Frame`, and `SourceBlock`; marking it internal would +and holds `Trace` and `Frame`; marking it internal would put an internal type in a public signature without making it inaccessible. @@ -225,7 +222,7 @@ final readonly class Problem implements JsonSerializable public ?string $detail = null, public ?string $file = null, public ?int $line = null, - public ?SourceBlock $source = null, + public ?string $source = null, public ?Trace $trace = null, public ?Problem $previous = null, ) {} @@ -238,14 +235,14 @@ final readonly class Problem implements JsonSerializable /** * The full document: `minimal()` plus `detail` as `class: message`, - * the origin, the source window, the trace, and the cause. + * the origin, the source line, the trace, and the cause. */ public static function development( Throwable $exception, int $status, string $file, int $line, - ?SourceBlock $source, + ?string $source, Trace $trace, ?Problem $previous, ): self; @@ -279,21 +276,7 @@ final readonly class Frame implements JsonSerializable public ?string $type = null, /** @var list|null */ public ?array $args = null, - public ?SourceBlock $source = null, - ) {} - - #[Override] - public function jsonSerialize(): array; -} - -/** @api */ -final readonly class SourceBlock implements JsonSerializable -{ - public function __construct( - public int $start, - public int $end, - /** @var list */ - public array $code, + public ?string $source = null, ) {} #[Override] @@ -344,10 +327,7 @@ Serialization rules: `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 its `code` is empty or consists of blank-line strings. -- `SourceBlock::jsonSerialize()` returns `{start, end, code}` in that - order. `start` and `end` are inclusive original file line numbers; - `code` is a list of strings, one per physical line in that interval. + 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 @@ -404,19 +384,7 @@ Full, HTTP 500: "detail": "RuntimeException: Something broke", "file": "src/Service/Thing.php", "line": 42, - "source": { - "start": 39, - "end": 45, - "code": [ - " $thing = $this->load();", - "", - " if (!$thing) {", - " throw new RuntimeException('Something broke');", - " }", - "", - " return $thing;" - ] - }, + "source": " throw new RuntimeException('Something broke');", "trace": [ { "file": "src/Http/Controller.php", @@ -425,19 +393,7 @@ Full, HTTP 500: "class": "App\\Http\\Controller", "type": "->", "args": [], - "source": { - "start": 14, - "end": 20, - "code": [ - " public function index(): void", - " {", - " $thing = new Thing();", - " $thing->run();", - "", - " return;", - " }" - ] - } + "source": " $thing->run();" }, { "file": "vendor/framework/router.php", @@ -446,19 +402,7 @@ Full, HTTP 500: "class": "Framework\\Router", "type": "->", "args": [], - "source": { - "start": 85, - "end": 91, - "code": [ - " {", - " $route = $this->match($request);", - "", - " return $route->run($request);", - " }", - "", - "}" - ] - } + "source": " return $route->run($request);" } ] } @@ -481,7 +425,7 @@ and inventing a URI would be worse than omitting it. ``` Throwable::getTrace() ──▶ TraceFactory ──▶ Document\Trace ├─▶ PathRelativizer relativize - ├─▶ SourceContext windows (every frame) + ├─▶ SourceContext source lines (every frame) └─▶ ArgumentSanitizer args └─▶ SanitizedObject / SanitizedMap / lists ``` @@ -513,9 +457,7 @@ final class TraceFactory final class SourceContext { - private const int CONTEXT_RADIUS = 3; - - public function window(string $absolutePath, int $line): ?SourceBlock; + public function line(string $absolutePath, int $line): ?string; } final class ArgumentSanitizer @@ -525,9 +467,8 @@ final class ArgumentSanitizer ``` `ExceptionHandler` builds the origin source with -`window($originFile, $originLine)` and `TraceFactory` does the same for -every frame. The radius is not configurable (decision 23), so -`SourceContext` owns it and no caller passes it. +`line($originFile, $originLine)` and `TraceFactory` does the same for +every frame. Snippets are always **read** from the absolute path and **reported** with the relativized path. `SourceContext` never sees a relative path, and @@ -555,35 +496,24 @@ that frame. `traceLimit` keeps the innermost N frames; dropping any frame sets `Trace::$truncated`, which `Problem` reports as `traceTruncated: true`. -### Source windows - -- The reported line and three physical lines on either side (`line ±3`), - clamped to the file, for the origin and every frame alike (decision 23). - A window has at most 7 lines. Near a file boundary, do not compensate - by taking extra lines from the other side. -- One `SourceBlock`, serialized as - `{"start": , "end": , "code": }`. - Bounds are inclusive, 1-based original file line numbers: - `start = max(1, line - 3)` and `end = min(file line count, line + 3)`. - The outer `line` still identifies the reported line; its zero-based - offset within the list is `line - source.start`. -- Keep every line in the interval, including blank and whitespace-only - lines. Each `code` element is one line; a blank line is `""`. - Preserve leading indentation and trailing whitespace. Do not trim, - filter, dedent, number, or decorate the code. -- A single empty source line is `code: [""]` and is still a valid, - present block. `end - start + 1` is the number of code elements. -- A file that cannot be read (missing, unreadable, or not a regular file), - or a reported line outside the file, yields `null`. Serializers omit - `source` in that case. Missing context is distinct from a blank block. -- The JSON array makes each line readable without escaped newline - characters; blank lines remain visible as empty strings. +### Source lines + +- The source line at the reported line, for the origin and every frame + alike (decision 23). +- `source` is a single string: the physical line at the reported line + number, trimmed of surrounding whitespace. Do not otherwise filter, + dedent, number, or decorate it. +- A blank or whitespace-only line is `""` and is still valid, present + source. Missing context is distinct from a blank line. +- A file that cannot be read (missing, unreadable, or not a regular + file), or a reported line outside the file, yields `null`. Serializers + omit `source` in that case. +- One string keeps the JSON free of escaped newlines and nested objects. Implementation: read the file once per distinct path with -`file($path, FILE_IGNORE_NEW_LINES)`, slice the window without filtering -or trimming, and use the resulting list of lines as `SourceBlock::code`. -Caching per instance prevents re-reading a file that appears in several -frames. +`file($path, FILE_IGNORE_NEW_LINES)`, index the reported line, and +`trim()` it. Caching per instance prevents re-reading a file that +appears in several frames. ### Argument sanitizer @@ -723,7 +653,7 @@ Response headers: `Content-Type: application/problem+json` only. No Encoding flags: `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR`. -Invalid UTF-8 in source windows is substituted rather than failing, and +Invalid UTF-8 in source lines is substituted rather than failing, and `JSON_THROW_ON_ERROR` makes the failure path explicit instead of returning `false`. @@ -739,14 +669,12 @@ returning `false`. test method carrying `#[WithEnvironmentVariable(...)]` — the attribute is fixed per method, so a data provider cannot drive it, and `value: null` covers the unset case. - - `SourceContext`: fixtures on disk covering a full 7-line window, - windows at line 1 and EOF without compensating for the clamped side, - blank and whitespace-only lines (including at window boundaries), - a blank-only window, indentation and trailing whitespace preserved, - LF/CRLF line separators, missing or unreadable files, non-file paths, - and reported lines before the start or beyond EOF. Assert `SourceBlock` - bounds and exact code strings, and `null` only for unavailable context. - Also verify the existing per-instance file cache. + - `SourceContext`: fixtures on disk covering the first and last lines, + blank and whitespace-only lines, indentation and trailing whitespace + trimmed, LF/CRLF line separators, missing or unreadable files, + 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, @@ -762,12 +690,11 @@ returning `false`. `Trace::$truncated`, frames without a file, args omitted for a missing key and kept as an empty list for a reported empty list, and a frame whose file sits outside - the project directory — still carrying its `source` window. + the project directory — still carrying its `source` line. - Document DTOs: each `jsonSerialize()` shape, member ordering and - omission rules, null `source` omitted but blank source blocks retained, - `SourceBlock` serialized as `{start, end, code}` with line-array `code`, `traceTruncated` - present only when truncated, and `SanitizedMap`/`SanitizedObject` - payload shapes. + omission rules, null `source` omitted but blank source lines retained, + `traceTruncated` present only when truncated, and + `SanitizedMap`/`SanitizedObject` payload shapes. - `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 fcf111e..c14bae8 100644 --- a/src/Document/Frame.php +++ b/src/Document/Frame.php @@ -23,7 +23,7 @@ public function __construct( public ?string $type = null, /** @var list|null */ public ?array $args = null, - public ?SourceBlock $source = null, + public ?string $source = null, ) {} /** diff --git a/src/Document/Problem.php b/src/Document/Problem.php index 979b9a3..7f4d18c 100644 --- a/src/Document/Problem.php +++ b/src/Document/Problem.php @@ -34,7 +34,7 @@ public function __construct( public ?string $detail = null, public ?string $file = null, public ?int $line = null, - public ?SourceBlock $source = null, + public ?string $source = null, public ?Trace $trace = null, public ?Problem $previous = null, ) {} @@ -56,7 +56,7 @@ public static function minimal(Throwable $exception, int $status): self /** * The full document: everything `minimal()` carries, plus `detail` - * as `class: message`, the origin, the source window, the trace, + * as `class: message`, the origin, the source line, the trace, * and the cause. * * @@ -67,7 +67,7 @@ public static function development( int $status, string $file, int $line, - ?SourceBlock $source, + ?string $source, Trace $trace, ?Problem $previous, ): self { diff --git a/src/Document/SourceBlock.php b/src/Document/SourceBlock.php deleted file mode 100644 index b29af02..0000000 --- a/src/Document/SourceBlock.php +++ /dev/null @@ -1,32 +0,0 @@ - */ - public array $code, - ) {} - - /** - * @return array{start: int, end: int, code: list} - */ - #[Override] - public function jsonSerialize(): array - { - return ['start' => $this->start, 'end' => $this->end, 'code' => $this->code]; - } -} diff --git a/src/ExceptionHandler.php b/src/ExceptionHandler.php index 86f1a0a..cc52910 100644 --- a/src/ExceptionHandler.php +++ b/src/ExceptionHandler.php @@ -66,7 +66,7 @@ public function handle(Throwable $exception): Problem status: $status, file: $this->relativizer->relativize($exception->getFile()), line: $exception->getLine(), - source: $this->source->window($exception->getFile(), $exception->getLine()), + source: $this->source->line($exception->getFile(), $exception->getLine()), trace: $this->trace->frames($trace), previous: $previous === null ? null : $this->handle($previous), ); diff --git a/src/Mode.php b/src/Mode.php index 471b75d..2aeb3a4 100644 --- a/src/Mode.php +++ b/src/Mode.php @@ -12,7 +12,7 @@ /** * The document mode the handler renders. * - * `Full` carries the message, origin, source windows, trace, and causes; + * `Full` carries the message, origin, source lines, trace, and causes; * `Minimal` carries the short exception class name and the code. * * @api diff --git a/src/Trace/SourceContext.php b/src/Trace/SourceContext.php index 5969dc8..c4d3a10 100644 --- a/src/Trace/SourceContext.php +++ b/src/Trace/SourceContext.php @@ -4,32 +4,22 @@ namespace Snafu\Trace; -use Snafu\Document\SourceBlock; - use function array_key_exists; -use function array_slice; use function array_values; -use function count; use function file; use function is_file; use function is_readable; -use function max; -use function min; +use function trim; use const FILE_IGNORE_NEW_LINES; /** - * Reads the fixed source window around a line of a file. + * Reads one line of source from a file. * * @internal */ final class SourceContext { - /** - * Lines kept either side of the reported line: up to 7 lines in total. - */ - private const int CONTEXT_RADIUS = 3; - /** * Contents of files already read, keyed by absolute path. * @@ -38,26 +28,16 @@ final class SourceContext private array $files = []; /** - * Returns the reported line ±3 as one block, preserving all whitespace. + * Returns the source line at `$line`, trimmed of surrounding + * whitespace. * - * Unavailable context yields null, distinct from a valid blank block. + * Unavailable source yields null, distinct from a valid blank line. */ - public function window(string $absolutePath, int $line): ?SourceBlock + public function line(string $absolutePath, int $line): ?string { - $lines = $this->lines($absolutePath); - - if ($lines === [] || $line < 1 || $line > count($lines)) { - return null; - } - - $first = max(1, $line - self::CONTEXT_RADIUS); - $last = min(count($lines), $line + self::CONTEXT_RADIUS); + $source = $this->lines($absolutePath)[$line - 1] ?? null; - return new SourceBlock( - start: $first, - end: $last, - code: array_slice(array: $lines, offset: $first - 1, length: $last - $first + 1), - ); + return $source === null ? null : trim($source); } /** diff --git a/src/Trace/TraceFactory.php b/src/Trace/TraceFactory.php index 372a49a..b98d9f0 100644 --- a/src/Trace/TraceFactory.php +++ b/src/Trace/TraceFactory.php @@ -72,7 +72,7 @@ function: $this->functionName($entry), class: $this->className($entry), type: $this->string($entry, 'type'), args: $this->args($entry), - source: $file === null || $line === null ? null : $this->source->window($file, $line), + source: $file === null || $line === null ? null : $this->source->line($file, $line), ); } diff --git a/tests/Document/FrameTest.php b/tests/Document/FrameTest.php index a2e035a..6d5d7d9 100644 --- a/tests/Document/FrameTest.php +++ b/tests/Document/FrameTest.php @@ -8,7 +8,6 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use Snafu\Document\Frame; -use Snafu\Document\SourceBlock; use function is_array; use function json_decode; @@ -54,34 +53,33 @@ class: 'App\Foo', public function testItIncludesSourceWhenPresent(): void { - $source = new SourceBlock(start: 11, end: 13, code: ['{', ' $x = 1;', '}']); - $frame = new Frame(file: 'src/Foo.php', line: 12, source: $source); + $frame = new Frame(file: 'src/Foo.php', line: 12, source: ' $x = 1;'); - $this->assertSame($source, $frame->source); - $this->assertSame($source, $frame->jsonSerialize()['source'] ?? null); + $this->assertSame(' $x = 1;', $frame->source); + $this->assertSame(' $x = 1;', $frame->jsonSerialize()['source'] ?? null); $this->assertSame( [ 'file' => 'src/Foo.php', 'line' => 12, - 'source' => ['start' => 11, 'end' => 13, 'code' => ['{', ' $x = 1;', '}']], + 'source' => ' $x = 1;', ], self::json($frame), ); } - public function testItIncludesSourceWithEmptyCode(): void + public function testItIncludesAnEmptySourceLine(): void { - $frame = new Frame(source: new SourceBlock(start: 12, end: 12, code: [''])); + $frame = new Frame(source: ''); - $this->assertSame(['source' => ['start' => 12, 'end' => 12, 'code' => ['']]], self::json($frame)); + $this->assertSame(['source' => ''], self::json($frame)); } - public function testItIncludesSourceWithWhitespaceOnlyCode(): void + public function testItIncludesAWhitespaceOnlySourceLine(): void { - $frame = new Frame(source: new SourceBlock(start: 11, end: 12, code: [' \t ', '\t '])); + $frame = new Frame(source: ' \t '); - $this->assertSame(['source' => ['start' => 11, 'end' => 12, 'code' => [' \t ', '\t ']]], self::json($frame)); + $this->assertSame(['source' => ' \t '], self::json($frame)); } public function testItEmitsAnEmptyArgumentListThatPhpReported(): void diff --git a/tests/Document/ProblemTest.php b/tests/Document/ProblemTest.php index d72e18d..929e100 100644 --- a/tests/Document/ProblemTest.php +++ b/tests/Document/ProblemTest.php @@ -12,7 +12,6 @@ use PHPUnit\Framework\TestCase; use RuntimeException; use Snafu\Document\Problem; -use Snafu\Document\SourceBlock; use Snafu\Document\Trace; use function is_array; @@ -77,7 +76,7 @@ public function testANonIntegerCodeIsCast(): void public function testDevelopmentCarriesEveryDevelopmentMember(): void { $previous = Problem::minimal(new RuntimeException('cause'), 500); - $source = new SourceBlock(start: 12, end: 12, code: [' throw new RuntimeException();']); + $source = ' throw new RuntimeException();'; $problem = Problem::development( exception: new RuntimeException('boom', 3), status: 422, @@ -99,7 +98,7 @@ public function testDevelopmentCarriesEveryDevelopmentMember(): void 'detail' => 'RuntimeException: boom', 'file' => 'src/Foo.php', 'line' => 12, - 'source' => ['start' => 12, 'end' => 12, 'code' => [' throw new RuntimeException();']], + 'source' => ' throw new RuntimeException();', 'trace' => [], 'previous' => [ 'type' => 'about:blank', @@ -133,35 +132,32 @@ public function testDevelopmentOmitsANullSourceAndANullPrevious(): void $this->assertArrayNotHasKey('traceTruncated', $serialized); } - public function testDevelopmentIncludesSourceWithEmptyCode(): void + public function testDevelopmentIncludesAnEmptySourceLine(): void { $problem = Problem::development( exception: new RuntimeException('boom'), status: 500, file: 'src/Foo.php', line: 1, - source: new SourceBlock(start: 1, end: 1, code: ['']), + source: '', trace: new Trace([], false), previous: null, ); - $this->assertSame(['start' => 1, 'end' => 1, 'code' => ['']], self::json($problem)['source'] ?? null); + $this->assertSame('', self::json($problem)['source'] ?? null); } - public function testItIncludesSourceWithWhitespaceOnlyCodeWhenConstructedDirectly(): void + public function testItIncludesAWhitespaceOnlySourceLineWhenConstructedDirectly(): void { $problem = new Problem( type: 'about:blank', title: 'Internal Server Error', status: 500, code: 0, - source: new SourceBlock(start: 1, end: 2, code: [' \t ', '\t ']), + source: ' \t ', ); - $this->assertSame( - ['start' => 1, 'end' => 2, 'code' => [' \t ', '\t ']], - self::json($problem)['source'] ?? null, - ); + $this->assertSame(' \t ', self::json($problem)['source'] ?? null); } public function testDevelopmentFlagsATruncatedTrace(): void diff --git a/tests/Document/SourceBlockTest.php b/tests/Document/SourceBlockTest.php deleted file mode 100644 index 2216673..0000000 --- a/tests/Document/SourceBlockTest.php +++ /dev/null @@ -1,21 +0,0 @@ -assertSame( - ['start' => 39, 'end' => 41, 'code' => ['first', '', 'last']], - new SourceBlock(start: 39, end: 41, code: ['first', '', 'last'])->jsonSerialize(), - ); - } -} diff --git a/tests/ExceptionHandlerTest.php b/tests/ExceptionHandlerTest.php index 9d77d80..5635fa0 100644 --- a/tests/ExceptionHandlerTest.php +++ b/tests/ExceptionHandlerTest.php @@ -10,7 +10,6 @@ use PHPUnit\Framework\TestCase; use RuntimeException; use Snafu\Document\Problem; -use Snafu\Document\SourceBlock; use Snafu\Document\Trace; use Snafu\ExceptionHandler; use Snafu\Mode; @@ -57,21 +56,18 @@ public function testMinimalNeverLeaksTheMessageOrLocation(): void $this->assertStringNotContainsString('ExceptionHandlerTest', $json); } - public function testFullCarriesTheMessageLocationAndWindow(): void + public function testFullCarriesTheMessageLocationAndSourceLine(): void { $exception = new RuntimeException('boom'); $problem = $this->handler(Mode::Full)->handle($exception); $this->assertSame('RuntimeException: boom', $problem->detail); $this->assertSame('tests/ExceptionHandlerTest.php', $problem->file); $this->assertSame($exception->getLine(), $problem->line); - $this->assertInstanceOf(SourceBlock::class, $problem->source); - $this->assertSame($exception->getLine() - 3, $problem->source->start); - $this->assertSame($exception->getLine() + 3, $problem->source->end); - $this->assertContains(' $exception = new RuntimeException(\'boom\');', $problem->source->code); + $this->assertSame('$exception = new RuntimeException(\'boom\');', $problem->source); $document = $this->document($problem); - /** @var array{source: array{start: int, end: int, code: list}} $document */ + /** @var array{source: string} $document */ $this->assertArrayHasKey('source', $document); - $this->assertSame($problem->source->jsonSerialize(), $document['source']); + $this->assertSame($problem->source, $document['source']); $this->assertInstanceOf(Trace::class, $problem->trace); $this->assertStringNotContainsString('traceTruncated', (string) json_encode($problem)); $this->assertNull($problem->previous); @@ -86,7 +82,7 @@ public function testItUsesTheStatusCodeInterfaceOnlyWhenTheStatusIsInRange(): vo $this->assertSame(500, $handler->handle(new ExceptionHandlerStatusFixture(600))->status); } - public function testMinimalOmitsTheCauseButFullNestsItWithSourceBlocks(): void + public function testMinimalOmitsTheCauseButFullNestsItWithSourceLines(): void { $exception = $this->chainedFailure(); @@ -104,12 +100,8 @@ public function testMinimalOmitsTheCauseButFullNestsItWithSourceBlocks(): void $this->assertInstanceOf(LogicException::class, $cause); $this->assertSame($cause->getLine(), $previous->line); - $this->assertInstanceOf(SourceBlock::class, $problem->source); - $this->assertInstanceOf(SourceBlock::class, $previous->source); - $this->assertSame($exception->getLine() - 3, $problem->source->start); - $this->assertSame($cause->getLine() - 3, $previous->source->start); - $this->assertContains(' return new RuntimeException(\'outer\', 0, $previous);', $problem->source->code); - $this->assertContains(' $previous = new LogicException(\'inner\');', $previous->source->code); + $this->assertSame('return new RuntimeException(\'outer\', 0, $previous);', $problem->source); + $this->assertSame('$previous = new LogicException(\'inner\');', $previous->source); $serializedProblem = $this->document($problem); /** @var array{previous: array} $serializedProblem */ @@ -139,7 +131,7 @@ public function __construct(string $file) $outer = $this->handler(Mode::Full)->handle(new RuntimeException('outer', 0, $missingSource)); $unavailablePrevious = $outer->previous; - $this->assertInstanceOf(SourceBlock::class, $outer->source); + $this->assertIsString($outer->source); $this->assertInstanceOf(Problem::class, $unavailablePrevious); $this->assertNull($unavailablePrevious->source); $serializedOuter = $this->document($outer); diff --git a/tests/Fixtures/source/utf8_failure.php b/tests/Fixtures/source/utf8_failure.php index 3ee8890..bb923ab 100644 --- a/tests/Fixtures/source/utf8_failure.php +++ b/tests/Fixtures/source/utf8_failure.php @@ -2,6 +2,5 @@ function snafu_fixture_utf8_failure(): never { - // ÿþ invalid utf8 € - throw new RuntimeException("invalid utf8 fixture"); + throw new RuntimeException("invalid utf8 fixture"); // ÿþ invalid utf8 € } diff --git a/tests/Middleware/ExceptionMiddlewareTest.php b/tests/Middleware/ExceptionMiddlewareTest.php index c27f60f..43e8af9 100644 --- a/tests/Middleware/ExceptionMiddlewareTest.php +++ b/tests/Middleware/ExceptionMiddlewareTest.php @@ -74,7 +74,7 @@ public function testItRespondsWithAFullProblemDocumentOnFailure(): void $this->assertSame('application/problem+json', $response->getHeaderLine('Content-Type')); $document = $this->document($response); - /** @var array{detail: string, file: string, line: int, source: array{start: int, end: int, code: list}, trace: list} $document */ + /** @var array{detail: string, file: string, line: int, source: string, trace: list} $document */ $this->assertArrayHasKey('detail', $document); $this->assertSame('RuntimeException: boom', $document['detail']); @@ -83,15 +83,7 @@ public function testItRespondsWithAFullProblemDocumentOnFailure(): void $this->assertArrayHasKey('line', $document); $this->assertSame($exception->getLine(), $document['line']); $this->assertArrayHasKey('source', $document); - $this->assertIsArray($document['source']); - $source = $document['source']; - $this->assertSame(['start', 'end', 'code'], array_keys($source)); - $this->assertArrayHasKey('start', $source); - $this->assertSame($exception->getLine() - 3, $source['start']); - $this->assertArrayHasKey('end', $source); - $this->assertSame($exception->getLine() + 3, $source['end']); - $this->assertArrayHasKey('code', $source); - $this->assertIsArray($source['code']); + $this->assertSame('$exception = new RuntimeException(\'boom\', 5);', $document['source']); $this->assertArrayHasKey('trace', $document); $this->assertIsArray($document['trace']); } diff --git a/tests/Trace/SourceContextTest.php b/tests/Trace/SourceContextTest.php index b7f9c26..d20a1c6 100644 --- a/tests/Trace/SourceContextTest.php +++ b/tests/Trace/SourceContextTest.php @@ -7,7 +7,6 @@ use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; -use Snafu\Document\SourceBlock; use Snafu\Trace\SourceContext; use function bin2hex; @@ -30,125 +29,67 @@ protected function setUp(): void $this->context = new SourceContext(); } - public function testItReturnsSevenContiguousLinesAndPreservesBlankLines(): void + public function testItReturnsTheReportedLineTrimmed(): void { - $source = $this->context->window(self::FIXTURE, 5); - - $this->assertInstanceOf(SourceBlock::class, $source); - $this->assertSame( - [ - 'start' => 2, - 'end' => 8, - 'code' => [ - '', - 'function snafu_fixture_alpha(): void', - '{', - ' $alpha = 1;', - '', - ' $beta = 2;', - '}', - ], - ], - $source->jsonSerialize(), - ); + $this->assertSame('$alpha = 1;', $this->context->line(self::FIXTURE, 5)); } - public function testItClampsTheWindowAtTheStartWithoutCompensating(): void + public function testItReturnsTheFirstAndLastLines(): void { - $source = $this->context->window(self::FIXTURE, 1); - - $this->assertInstanceOf(SourceBlock::class, $source); - $this->assertSame( - [ - 'start' => 1, - 'end' => 4, - 'code' => ['jsonSerialize(), - ); - } - - public function testItClampsTheWindowAtTheEndWithoutCompensating(): void - { - $source = $this->context->window(self::FIXTURE, 13); - - $this->assertInstanceOf(SourceBlock::class, $source); - $this->assertSame( - [ - 'start' => 10, - 'end' => 13, - 'code' => ['function snafu_fixture_omega(): void', '{', ' $omega = 3;', '}'], - ], - $source->jsonSerialize(), - ); + $this->assertSame('context->line(self::FIXTURE, 1)); + $this->assertSame('}', $this->context->line(self::FIXTURE, 13)); } public function testItReturnsNullForAReportedLineOutsideTheFile(): void { - $this->assertNull($this->context->window(self::FIXTURE, 0)); - $this->assertNull($this->context->window(self::FIXTURE, 999)); + $this->assertNull($this->context->line(self::FIXTURE, 0)); + $this->assertNull($this->context->line(self::FIXTURE, 999)); } public function testItReturnsNullForAnEmptyFile(): void { - $this->assertNull($this->windowFromContents('', 1)); + $this->assertNull($this->lineFromContents('', 1)); } public function testItReturnsNullForAMissingFile(): void { - $this->assertNull($this->context->window('/nonexistent/snafu/window.php', 1)); + $this->assertNull($this->context->line('/nonexistent/snafu/window.php', 1)); } public function testItReturnsNullForADirectory(): void { - $this->assertNull($this->context->window(__DIR__ . '/../Fixtures/source', 1)); - } - - public function testItPreservesWhitespaceAndNormalizesLineSeparators(): void - { - $source = $this->windowFromContents("\t \r\n\r\n \$value = 1; \t\r\n \t", 3); - - $this->assertInstanceOf(SourceBlock::class, $source); - $this->assertSame( - ['start' => 1, 'end' => 4, 'code' => ["\t ", '', " \$value = 1; \t", " \t"]], - $source->jsonSerialize(), - ); + $this->assertNull($this->context->line(__DIR__ . '/../Fixtures/source', 1)); } - public function testItKeepsAnAllBlankWindowAsPresentSource(): void + public function testItTrimsWhitespaceAndNormalizesLineSeparators(): void { - $source = $this->windowFromContents("\n\n\n\n\n\n\n", 4); + $contents = "\t \r\n\r\n \$value = 1; \t\r\n \t"; - $this->assertInstanceOf(SourceBlock::class, $source); - $this->assertSame(['start' => 1, 'end' => 7, 'code' => ['', '', '', '', '', '', '']], $source->jsonSerialize()); + $this->assertSame('', $this->lineFromContents($contents, 1)); + $this->assertSame('', $this->lineFromContents($contents, 2)); + $this->assertSame('$value = 1;', $this->lineFromContents($contents, 3)); + $this->assertSame('', $this->lineFromContents($contents, 4)); } - public function testItKeepsAnEmptySingleLineBlockDistinctFromMissingContext(): void + public function testItReturnsAnEmptyStringForABlankLine(): void { - $source = $this->windowFromContents("\n", 1); - - $this->assertInstanceOf(SourceBlock::class, $source); - $this->assertSame(['start' => 1, 'end' => 1, 'code' => ['']], $source->jsonSerialize()); + $this->assertSame('', $this->lineFromContents("\n", 1)); } public function testItCachesFileContentsAcrossCalls(): void { - $path = sys_get_temp_dir() . '/snafu-window-' . bin2hex(random_bytes(8)) . '.php'; + $path = sys_get_temp_dir() . '/snafu-line-' . bin2hex(random_bytes(8)) . '.php'; try { file_put_contents(filename: $path, data: "context->window($path, 3); + $first = $this->context->line($path, 3); - $this->assertInstanceOf(SourceBlock::class, $first); - $this->assertSame( - ['start' => 1, 'end' => 3, 'code' => ['jsonSerialize(), - ); + $this->assertSame('$first = 1;', $first); file_put_contents(filename: $path, data: "context->window($path, 3); + $second = $this->context->line($path, 3); - $this->assertEquals($first, $second); + $this->assertSame($first, $second); } finally { if (is_file($path)) { unlink($path); @@ -156,14 +97,14 @@ public function testItCachesFileContentsAcrossCalls(): void } } - private function windowFromContents(string $contents, int $line): ?SourceBlock + private function lineFromContents(string $contents, int $line): ?string { - $path = sys_get_temp_dir() . '/snafu-window-' . bin2hex(random_bytes(8)) . '.php'; + $path = sys_get_temp_dir() . '/snafu-line-' . bin2hex(random_bytes(8)) . '.php'; try { file_put_contents(filename: $path, data: $contents); - return new SourceContext()->window($path, $line); + return new SourceContext()->line($path, $line); } finally { if (is_file($path)) { unlink($path); diff --git a/tests/Trace/TraceFactoryTest.php b/tests/Trace/TraceFactoryTest.php index 327a4ec..424443c 100644 --- a/tests/Trace/TraceFactoryTest.php +++ b/tests/Trace/TraceFactoryTest.php @@ -8,7 +8,6 @@ use Override; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; -use Snafu\Document\SourceBlock; use Snafu\Document\Trace; use Snafu\Path\PathRelativizer; use Snafu\Trace\ArgumentSanitizer; @@ -59,7 +58,7 @@ public function testItKeepsTheInnermostFrameFirst(): void ]); $this->assertFalse($trace->truncated); - $this->assertInstanceOf(SourceBlock::class, $trace->frames[0]->source ?? null); + $this->assertSame('$alpha = 1;', $trace->frames[0]->source ?? null); $this->assertNull($trace->frames[1]->source ?? null); $this->assertSame( [ @@ -67,19 +66,7 @@ public function testItKeepsTheInnermostFrameFirst(): void 'file' => 'tests/Fixtures/source/window.php', 'line' => 5, 'function' => 'inner', - 'source' => [ - 'start' => 2, - 'end' => 8, - 'code' => [ - '', - 'function snafu_fixture_alpha(): void', - '{', - ' $alpha = 1;', - '', - ' $beta = 2;', - '}', - ], - ], + 'source' => '$alpha = 1;', ], [ 'file' => 'src/Outer.php', @@ -91,23 +78,22 @@ public function testItKeepsTheInnermostFrameFirst(): void ); } - public function testItRetainsEmptyAndWhitespaceOnlySource(): void + public function testItTrimsEmptyAndWhitespaceOnlySource(): void { foreach ([ - ["\n", 1, ['']], - [" \t \r\n\t \r\n", 2, [" \t ", "\t "]], - ] as [$contents, $end, $code]) { + ["\n", 1, ''], + [" \t \r\n\t \r\n", 1, ''], + [" \t \r\n\t \r\n", 2, ''], + [" \$x = 1; \n", 1, '$x = 1;'], + ] as [$contents, $line, $source]) { $path = sys_get_temp_dir() . '/snafu-trace-source-' . bin2hex(random_bytes(8)) . '.php'; file_put_contents(filename: $path, data: $contents); try { - $trace = $this->factory->frames([['file' => $path, 'line' => 1]]); + $trace = $this->factory->frames([['file' => $path, 'line' => $line]]); - $this->assertInstanceOf(SourceBlock::class, $trace->frames[0]->source ?? null); - $this->assertSame( - [['file' => $path, 'line' => 1, 'source' => ['start' => 1, 'end' => $end, 'code' => $code]]], - $this->serialize($trace), - ); + $this->assertSame($source, $trace->frames[0]->source ?? null); + $this->assertSame([['file' => $path, 'line' => $line, 'source' => $source]], $this->serialize($trace)); } finally { unlink($path); } @@ -262,7 +248,7 @@ public function testItDoesNotFlagATraceAtExactlyTheLimit(): void $this->assertCount(30, $trace->frames); } - public function testItSkipsTheSourceWindowWhenTheLineIsOutOfRange(): void + public function testItSkipsTheSourceLineWhenTheLineIsOutOfRange(): void { $trace = $this->factory->frames([[ 'file' => $this->root . self::ROOT_FIXTURE,