Bicycle/System/Classes/HTTP/HTTPException.php
Egor Isaev b65603b4d0 dev
2026-06-23 10:44:18 +03:00

82 lines
2.7 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* @package Bicycle
* @author Egor Isaev
* @description HTTP/HTTPException.php
* @copyright (c) 04/06/2026
*/
namespace System\Classes\HTTP;
use System\Classes\Core;
use System\Classes\MyException;
use System\Classes\Response;
use Throwable;
/**
* Базовое HTTP-исключение. factory() подбирает подкласс по коду,
* getResponse() рендерит соответствующий шаблон ошибки.
*/
class HTTPException extends MyException
{
/** @var int HTTP-код исключения */
protected int $_code = 0;
/**
* @param string $message Сообщение (поддерживает плейсхолдеры)
* @param array|null $variables Карта замен для strtr
* @param Throwable|null $previous Предыдущее исключение
* @param int $code_override Код, переопределяющий $_code (для неизвестных кодов)
*/
public function __construct(string $message = '', ?array $variables = null, ?Throwable $previous = null, int $code_override = 0)
{
if ($code_override !== 0) {
$this->_code = $code_override;
}
parent::__construct($message, $variables, $this->_code, $previous);
}
/**
* Создаёт HTTPException_{code} или базовый класс для неизвестных кодов.
*
* @param int $code HTTP-код
* @param string $message Сообщение
* @param array|null $variables Карта замен для strtr
* @param Throwable|null $previous Предыдущее исключение
* @return static
*/
public static function factory(int $code, string $message = '', ?array $variables = null, ?Throwable $previous = null): static
{
$class = 'System\\Classes\\HTTP\\Exception\\HTTPException_' . $code;
if (class_exists($class)) {
return new $class($message, $variables, $previous);
}
return new static($message, $variables, $previous, $code);
}
/**
* Формирует Response с телом из шаблона view/errors/{code}.html.
*
* @return Response
*/
public function getResponse(): Response
{
$code = $this->_code ?: 500;
http_response_code($code);
$response = new Response($code);
$view = Core::findFile('view/errors', (string)$code, 'html');
if ($view) {
ob_start();
$message = $this->getMessage();
include $view;
$response->body(ob_get_clean());
}
return $response;
}
}