|
9 | 9 | use Itools\SmartString\SmartString; |
10 | 10 |
|
11 | 11 | // 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; |
13 | 13 | use const ARRAY_FILTER_USE_BOTH, DEBUG_BACKTRACE_IGNORE_ARGS, E_USER_WARNING, JSON_INVALID_UTF8_SUBSTITUTE, SORT_ASC, SORT_DESC, SORT_REGULAR; |
14 | 14 |
|
15 | 15 | /** |
@@ -1529,22 +1529,87 @@ public function __unset(string $name): void |
1529 | 1529 | //endregion |
1530 | 1530 | //region Error Handling |
1531 | 1531 |
|
| 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 | + |
1532 | 1571 | /** |
1533 | 1572 | * 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. |
1535 | 1575 | * |
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. |
1537 | 1582 | * @return static Returns $this if not empty, exits with 404 if empty |
1538 | 1583 | */ |
1539 | | - public function or404(?string $text = null): static |
| 1584 | + public function or404(string|SmartString|SmartNull|null $text = null): static |
1540 | 1585 | { |
1541 | 1586 | if (!empty($this->data)) { |
1542 | 1587 | return $this; |
1543 | 1588 | } |
1544 | 1589 |
|
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 | + } |
1548 | 1613 | $text ??= "The requested URL was not found on this server."; |
1549 | 1614 | $text = self::h($text); |
1550 | 1615 |
|
|
0 commit comments