Skip to content

Commit adec2dc

Browse files
committed
src: add set404Handler() and match SmartString's or404()
- set404Handler($callback): or404() calls your handler instead of printing the built-in page. The 404 status is still sent first and the page stops after. The handler gets the message as plain text, or null. Returns the previous handler; null brings back the built-in page. An or404() inside the handler prints the built-in page instead of calling the handler again - SmartArray and SmartArrayHtml share one handler. SmartString has its own, and in HTML mode ->first()->or404() on an empty result uses it, so the docs say to set both - or404() now works like SmartString's: it skips the headers when output already started, throws away buffered output first, and accepts SmartString and SmartNull messages - or404 tests run in a subprocess (tests/Support/bin/empty-guard.php), since the buffer cleanup also closes PHPUnit's output buffer - Docs: method-reference, ai-reference, displaying-fields, CHANGELOG, security scan prompt
1 parent 571f3cd commit adec2dc

10 files changed

Lines changed: 490 additions & 44 deletions

File tree

‎.github/scripts/codex-security-scan.sh‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@ behavior. SmartArray and SmartArrayRaw return plain values by design; only
4747
SmartArrayHtml wraps elements as SmartStrings. toArray(), map() callbacks,
4848
and jsonSerialize() expose raw values per the documented contract. Only flag
4949
these if a concrete in-repo path renders their result into HTML without
50-
encoding.
50+
encoding. A set404Handler() handler receives or404()'s message as plain text
51+
by design; flag only a shipped doc example or docblock that prints it
52+
without encoding.
5153
5254
Known limitations and finding criteria:
5355

‎CHANGELOG.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ Everything else is hardening and fixes.
3636
- **`where($field)` / `whereNot($field)`** - one-argument forms filter by
3737
PHP's `empty()` rule: `where('featured')` keeps rows where the field is
3838
non-empty, `whereNot('featured')` keeps the rest
39+
- **`set404Handler()`** - show your own 404 page from `or404()` instead of
40+
the built-in one; SmartString has its own, so set both
3941

4042
### Performance
4143

@@ -133,7 +135,10 @@ Also: writes to a `SmartNull` throw instead of silently discarding the
133135
value, raw-mode arrays throw on SmartString-style fallbacks like `->or()`
134136
on missing keys (use `??` instead), `print_r()` and `var_dump()` show
135137
clean array data (use `debug()` for exact types), `orDie()` and `or404()`
136-
exit with status 1 so shell scripts see the failure, deprecated names are
138+
exit with status 1 so shell scripts see the failure, `or404()` works like
139+
SmartString's (it discards partial page output, skips the 404 status
140+
instead of warning once output has started, and accepts SmartString
141+
messages), deprecated names are
137142
real declared methods so IDEs and `method_exists()` see them, `help()`
138143
and `debug()` print plain text on the command line, and a couple dozen
139144
small fixes to error messages and `load()`, `column()`, `get()`, and

‎docs/ai-reference.md‎

Lines changed: 33 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ Contents:
2727
- [Row Position](#row-position) - isFirst(), isLast(), position()
2828
- [Filtering and Sorting](#filtering-and-sorting) - where(), whereNot(), whereInList(), filter(), sort(), sortBy(), unique()
2929
- [Transforming and Grouping](#transforming-and-grouping) - column(), columnAt(), indexBy(), groupBy(), keys(), values(), map(), merge(), implode()
30-
- [Guards](#guards) - or404(), orDie(), orThrow(), orRedirect()
30+
- [Guards](#guards) - or404(), orDie(), orThrow(), orRedirect(), set404Handler()
3131
- [Database Metadata](#database-metadata) - mysqli(), load()
3232
- [Debugging](#debugging) - debug()
3333
- [Errors and Exceptions](#errors-and-exceptions)
@@ -273,21 +273,45 @@ Sorting above.
273273
Fire when the COLLECTION IS EMPTY (no rows/elements; contrast SmartString's
274274
field guards, which fire on missing values). Non-empty: return `$this`
275275
unchanged, so they chain inline. `$text` is HTML-encoded automatically
276-
(messages often interpolate user input).
276+
(messages often interpolate user input), except that `or404()` passes it to
277+
a `set404Handler()` handler unencoded.
277278

278-
| Method | On empty |
279-
|---------------------------------------|----------------------------------------------------------------------------------------------------------|
280-
| `or404(?string $text = null): static` | HTTP 404 + minimal HTML page + `exit(1)`. Default text "The requested URL was not found on this server." |
281-
| `orDie(string $text): static` | Echo encoded text + `exit(1)` |
282-
| `orThrow(string $text): static` | `throw new RuntimeException($encodedText)` |
283-
| `orRedirect(string $url): static` | 302 + `Location: $url` + `exit`. Checks `headers_sent()` immediately (throws even when non-empty) |
279+
| Method | On empty |
280+
|--------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------|
281+
| `or404(string\|SmartString\|SmartNull\|null $text = null): static` | HTTP 404 + minimal HTML page (or the `set404Handler()` page) + `exit(1)`. Default text "The requested URL was not found on this server." |
282+
| `orDie(string $text): static` | Echo encoded text + `exit(1)` |
283+
| `orThrow(string $text): static` | `throw new RuntimeException($encodedText)` |
284+
| `orRedirect(string $url): static` | 302 + `Location: $url` + `exit`. Checks `headers_sent()` immediately (throws even when non-empty) |
284285

285286
```php
286287
$article = $articles->where('num', $num)->first()->or404('Article not found');
287288
```
288289

289290
(`first()` on empty returns SmartNull; its `or404()` delegates and fires.)
290291

292+
`SmartArray::set404Handler(?callable $callback): ?Closure` - static; sets the
293+
page `or404()` shows instead of the built-in one. Call once at startup.
294+
295+
```php
296+
$show404 = function (?string $text): void {
297+
$message = SmartString::new($text ?? "We couldn't find that page."); // encodes itself when echoed
298+
include __DIR__ . '/404.php'; // your page template, which echoes $message
299+
};
300+
SmartArray::set404Handler($show404);
301+
SmartString::set404Handler($show404);
302+
```
303+
304+
- The handler gets the message as plain text (NOT encoded; encode it before
305+
output), or null when `or404()` had no message. Type it `?string`.
306+
- `or404()` sends the 404 status and discards output buffers before the
307+
handler, and calls `exit(1)` after it returns.
308+
- Returns the previous handler, or null; `set404Handler(null)` restores the
309+
built-in page.
310+
- SmartArray and SmartString keep separate handlers. In HTML mode,
311+
collections use SmartArray's and single values (fields, missing keys,
312+
`first()` on an empty result) use SmartString's. In raw mode every
313+
`or404()` uses SmartArray's. Set both.
314+
291315
## Database Metadata
292316

293317
Set via the `$properties` constructor argument; ZenDB and CMS Builder do
@@ -390,7 +414,7 @@ RuntimeException (strict mode for new installs).
390414
not an array - chain `values()`.
391415
- Collection guards fire on EMPTY collections; SmartString field guards
392416
fire on missing VALUES. `$row->or404()` (row) vs `$row->num->or404()`
393-
(field) differ.
417+
(field) differ, and each library has its own `set404Handler()`: set both.
394418
- `where()` drops rows missing the field; `whereNot()` keeps them.
395419
- `implode()` in HTML mode returns a SmartString: interpolating it into a
396420
raw-SQL string would encode the joined text; call `->string()` first or

‎docs/displaying-fields.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,25 @@ echo "<h1>$article->title</h1>"; // with ?num=7 this prints: <h1>Fall Fair Sept
138138
Messages HTML-encode automatically, so interpolating user input into them is
139139
safe: `->orDie("No results for '$keyword'")`.
140140

141+
`or404()` prints a plain built-in page. To show your site's own 404 page
142+
instead, set a handler once in your init file:
143+
144+
```php
145+
use Itools\SmartArray\SmartArray;
146+
use Itools\SmartString\SmartString;
147+
148+
$show404 = function (?string $text): void {
149+
$message = SmartString::new($text ?? "We couldn't find that page."); // encodes itself when echoed
150+
include __DIR__ . '/404.php'; // your page template, which echoes $message
151+
};
152+
SmartArray::set404Handler($show404);
153+
SmartString::set404Handler($show404);
154+
```
155+
156+
SmartArray and SmartString each keep their own handler, so set both. Field
157+
guards like `$article->title->or404()`, and `->first()->or404()` with no
158+
match, use SmartString's.
159+
141160
## Checking a Single Field
142161

143162
The guards work on single fields too:

‎docs/method-reference.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,9 @@ HTML-encode automatically, so interpolated user input is safe.*
156156
| `->orThrow($text)` | Throws a `RuntimeException` with `$text` |
157157
| `->orRedirect($url)` | Sends a 302 redirect to `$url` and stops (throws if headers were already sent) |
158158

159+
To show your site's own 404 page instead, set it once at startup with
160+
`SmartArray::set404Handler()`.
161+
159162
### Database Metadata
160163

161164
*For collections created from query results; ZenDB and CMS Builder set

‎src/SmartArrayBase.php‎

Lines changed: 72 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
use Itools\SmartString\SmartString;
1010

1111
// import built-ins so calls resolve at compile time instead of per-call lookups; NamespacedCallsTest keeps this list exact
12-
use function addcslashes, array_column, array_filter, array_key_exists, array_key_first, array_key_last, array_keys, array_map, array_merge, array_multisort, array_slice, array_unique, array_values, basename, count, debug_backtrace, func_num_args, get_debug_type, header, headers_sent, http_response_code, implode, is_array, is_bool, is_callable, is_float, is_int, is_null, is_object, is_scalar, is_string, json_decode, json_encode, max, method_exists, preg_match, preg_replace, rtrim, sort, spl_object_id, sprintf, str_contains, str_pad, str_repeat, strlen, trigger_error, trim, var_export;
12+
use function addcslashes, array_column, array_filter, array_key_exists, array_key_first, array_key_last, array_keys, array_map, array_merge, array_multisort, array_slice, array_unique, array_values, basename, count, debug_backtrace, func_num_args, get_debug_type, header, headers_sent, http_response_code, implode, is_array, is_bool, is_callable, is_float, is_int, is_null, is_object, is_scalar, is_string, json_decode, json_encode, max, method_exists, ob_end_clean, preg_match, preg_replace, rtrim, sort, spl_object_id, sprintf, str_contains, str_pad, str_repeat, strlen, trigger_error, trim, var_export;
1313
use const ARRAY_FILTER_USE_BOTH, DEBUG_BACKTRACE_IGNORE_ARGS, E_USER_WARNING, JSON_INVALID_UTF8_SUBSTITUTE, SORT_ASC, SORT_DESC, SORT_REGULAR;
1414

1515
/**
@@ -1529,22 +1529,87 @@ public function __unset(string $name): void
15291529
//endregion
15301530
//region Error Handling
15311531

1532+
/**
1533+
* The handler set with set404Handler(), or null for the built-in page.
1534+
*/
1535+
private static ?Closure $notFoundHandler = null;
1536+
1537+
/**
1538+
* True while the handler runs, so an or404() on the handler's own page prints
1539+
* the built-in page instead of calling the handler again.
1540+
*/
1541+
private static bool $inNotFoundHandler = false;
1542+
1543+
/**
1544+
* Shows your own page when or404() finds an empty array, instead of the built-in
1545+
* "Not Found" page. Call it once at startup. or404() sends the 404 status before
1546+
* calling the handler and exits after it returns, so the handler only prints the page.
1547+
*
1548+
* SmartArray and SmartArrayHtml share one handler. SmartString keeps its own, which
1549+
* field guards and ->first()->or404() on an empty SmartArrayHtml result use, so set both.
1550+
*
1551+
* SECURITY: the handler gets the message as plain text. HTML-encode it before printing.
1552+
*
1553+
* $show404 = function (?string $text): void {
1554+
* $message = SmartString::new($text ?? "We couldn't find that page."); // encodes itself when echoed
1555+
* include __DIR__ . '/404.php'; // your page template, which echoes $message
1556+
* };
1557+
* SmartArray::set404Handler($show404);
1558+
* SmartString::set404Handler($show404);
1559+
* SmartArray::set404Handler(null); // back to the built-in page
1560+
*
1561+
* @param callable|null $callback Gets or404()'s message as plain text, or null when it has none
1562+
* @return Closure|null The handler set before, or null
1563+
*/
1564+
public static function set404Handler(?callable $callback): ?Closure
1565+
{
1566+
$previous = self::$notFoundHandler;
1567+
self::$notFoundHandler = $callback !== null ? Closure::fromCallable($callback) : null;
1568+
return $previous;
1569+
}
1570+
15321571
/**
15331572
* Sends a 404 header and message if the array is empty, then exits with status 1
1534-
* so shell scripts and cron jobs see the failure.
1573+
* so shell scripts and cron jobs see the failure. With set404Handler() set, the
1574+
* handler prints the page instead and gets $text as plain text.
15351575
*
1536-
* @param string|null $text Plain-text message; HTML-encoded automatically before output. Defaults to "The requested URL was not found on this server."
1576+
* Any page output that's still buffered is thrown away first, so the 404 page shows on
1577+
* its own. A buffer PHP won't let us remove keeps its content, and the 404 page prints
1578+
* after it. If output already went to the browser, the 404 page still prints, but the
1579+
* HTTP status can't change anymore and stays whatever was already sent (usually 200).
1580+
*
1581+
* @param string|SmartString|SmartNull|null $text Plain-text message. The built-in page HTML-encodes it and defaults to "The requested URL was not found on this server."; a set404Handler() handler gets it unencoded, or null.
15371582
* @return static Returns $this if not empty, exits with 404 if empty
15381583
*/
1539-
public function or404(?string $text = null): static
1584+
public function or404(string|SmartString|SmartNull|null $text = null): static
15401585
{
15411586
if (!empty($this->data)) {
15421587
return $this;
15431588
}
15441589

1545-
// Send 404 header and message
1546-
http_response_code(404);
1547-
header("Content-Type: text/html; charset=utf-8");
1590+
// Headers can only be sent before any output. If the page already started printing, skip
1591+
// them: the visitor still gets the 404 page, under a 200 status instead of a PHP
1592+
// "headers already sent" warning.
1593+
if (!headers_sent()) {
1594+
http_response_code(404);
1595+
header("Content-Type: text/html; charset=utf-8");
1596+
}
1597+
// Throw away buffered output that hasn't been sent yet, so the 404 page shows on its own.
1598+
// Loop until ob_end_clean() returns false, not until ob_get_level() is 0: a buffer started
1599+
// without PHP_OUTPUT_HANDLER_REMOVABLE can't be closed, so a level check would loop forever.
1600+
while (@ob_end_clean()) {
1601+
}
1602+
$text = is_string($text) ? $text : self::getRawValue($text); // fast path: skip getRawValue() for plain values
1603+
$text = $text === null ? null : (string)$text; // SmartNull stays null; a SmartString number or bool becomes text
1604+
if (self::$notFoundHandler !== null && !self::$inNotFoundHandler) {
1605+
self::$inNotFoundHandler = true;
1606+
try {
1607+
(self::$notFoundHandler)($text);
1608+
} finally {
1609+
self::$inNotFoundHandler = false;
1610+
}
1611+
self::exit(1);
1612+
}
15481613
$text ??= "The requested URL was not found on this server.";
15491614
$text = self::h($text);
15501615

‎src/SmartNull.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -288,7 +288,9 @@ private function throwCannotSet(): never
288288
* result means nothing was produced, so the SmartNull itself returns and the
289289
* chain stays open for either ending, ->or('n/a') for a value or ->implode()
290290
* for a collection. Produced results (or() fallbacks, int() and other scalars)
291-
* return as usual. map() and its deprecated alias apply() propagate without
291+
* return as usual. Guards like or404() are SmartString methods too, so in HTML
292+
* mode they run SmartString's version and its set404Handler() page; raw mode
293+
* runs SmartArray's. map() and its deprecated alias apply() propagate without
292294
* running their callback: a missing key has no value to pass it, while a
293295
* NULL value in an existing key still runs the callback.
294296
*

‎tests/Integration/DocsExamplesTest.php‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,27 @@ public function testDisplayingFieldsOr404ReturnsTheRowWhenTheRecordExists(): voi
349349
$this->assertSame('<h1>Fall Fair Sept 20-21</h1>', $output);
350350
}
351351

352+
353+
/**
354+
* The startup lines as written. The handler only runs when or404() fires, which exits,
355+
* so this checks both setters take the doc's closure; EmptyGuardsTest covers it firing.
356+
*/
357+
public function testDisplayingFieldsSet404HandlerTakesTheDocsClosure(): void
358+
{
359+
$show404 = function (?string $text): void {
360+
$message = SmartString::new($text ?? "We couldn't find that page.");
361+
include __DIR__ . '/404.php';
362+
};
363+
364+
try {
365+
$this->assertNull(SmartArray::set404Handler($show404));
366+
$this->assertNull(SmartString::set404Handler($show404));
367+
} finally {
368+
SmartArray::set404Handler(null);
369+
SmartString::set404Handler(null);
370+
}
371+
}
372+
352373
//endregion
353374
//region Displaying Fields: Checking a Single Field
354375

0 commit comments

Comments
 (0)