Skip to content

Commit

Permalink
Make error handler cache static
Browse files Browse the repository at this point in the history
  • Loading branch information
trowski committed Feb 2, 2023
1 parent 8a9e39f commit a2f94d0
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 23 deletions.
1 change: 0 additions & 1 deletion resources/error.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
}

.box {
margin: 30px;
background: #fff;
border-radius: 3px;
padding: 20px 30px;
Expand Down
37 changes: 15 additions & 22 deletions src/DefaultErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,32 @@
use Amp\Http\HttpStatus;

/**
* ErrorHandler instance used by default if none is given.
* Error handler that sends a simple HTML error page.
*/
final class DefaultErrorHandler implements ErrorHandler
{
/** @var string[] */
private array $cache = [];
private static ?string $errorHtml = null;

/** @var array<int, string> */
private static array $cache = [];

public function handleError(int $status, ?string $reason = null, ?Request $request = null): Response
{
static $errorHtml;

if ($errorHtml === null) {
$errorHtml = \file_get_contents(\dirname(__DIR__) . "/resources/error.html");
}
self::$errorHtml ??= \file_get_contents(\dirname(__DIR__) . "/resources/error.html");

if (!isset($this->cache[$status])) {
$this->cache[$status] = \str_replace(
["{code}", "{reason}"],
// Using standard reason in HTML for caching purposes.
[$status, HttpStatus::getReason($status)],
$errorHtml
);
}
$body = self::$cache[$status] ??= \str_replace(
["{code}", "{reason}"],
// Using standard reason in HTML for caching purposes.
[$status, HttpStatus::getReason($status)],
self::$errorHtml,
);

$response = new Response(
return new Response(
status: $status,
headers: [
"content-type" => "text/html; charset=utf-8",
],
body: $this->cache[$status],
body: $body,
);

$response->setStatus($status, $reason);

return $response;
}
}

0 comments on commit a2f94d0

Please sign in to comment.