Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/php.yml
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ jobs:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
php-version: '8.4' # ← Было '8.3', стало '8.4'
extensions: xdebug
coverage: xdebug # ← Явно включаем драйвер покрытия

# Шаг 3: Валидация composer.json и composer.lock
- name: Validate composer.json and composer.lock
Expand Down
24 changes: 19 additions & 5 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,25 @@
- [Rudra\Exceptions\RouterException](#rudra_exceptions_routerexception)
- [Rudra\Exceptions\RudraException](#rudra_exceptions_rudraexception)
- [Rudra\Exceptions\RuntimeException](#rudra_exceptions_runtimeexception)
<hr>


---



<a id="rudra_exceptions_exceptioninterface"></a>

### Class: Rudra\Exceptions\ExceptionInterface
| Visibility | Function |
|:-----------|:---------|
| abstract public | `getMessage(): string`<br> |
| abstract public | `getCode()`<br> |
| abstract public | `getFile(): string`<br> |
| abstract public | `getLine(): int`<br> |
| abstract public | `getTrace(): array`<br> |
| abstract public | `getPrevious(): ?Throwable`<br> |
| abstract public | `getTraceAsString(): string`<br> |
| abstract public | `__toString(): string`<br> |


<a id="rudra_exceptions_logicexception"></a>
Expand Down Expand Up @@ -71,8 +83,8 @@
### Class: Rudra\Exceptions\RouterException
| Visibility | Function |
|:-----------|:---------|
| public | `__construct( $message, $code, ?Exception $previous)`<br>Constructs a new RouterException and sets a global exception handler.<br>The exception handler will catch all unhandled exceptions of this type<br>and redirect them using RedirectFacade to the appropriate error page/controller.<br>-------------------------<br>Конструктор RouterException устанавливает глобальный обработчик исключений.<br>Обработчик перехватывает все неперехваченные исключения этого типа<br>и вызывает RedirectFacade для перехода к странице/контроллеру ошибки. |
| public | `exception_handler(Exception $exception): void`<br>Custom exception handler triggered by this class.<br>Uses RedirectFacade to send an HTTP status code and then calls the error handler,<br>which is defined in the config under `http.errors`.<br>-------------------------<br>Собственный обработчик исключений, запускаемый этим классом.<br>Использует RedirectFacade для отправки HTTP-статуса и вызова обработчика ошибок,<br>указанного в конфигурации под ключом `http.errors`. |
| public | `__construct(string $message, int $code, ?Throwable $previous)`<br>Constructs a new RouterException and sets a global exception handler. |
| public | `exception_handler(Throwable $exception): void`<br>Custom exception handler triggered by this class.<br>Uses RedirectFacade to send an HTTP status code and then calls the error handler. |
| public | `__wakeup()`<br> |
| final public | `getMessage(): string`<br> |
| final public | `getCode()`<br> |
Expand Down Expand Up @@ -116,6 +128,8 @@
| final public | `getPrevious(): ?Throwable`<br> |
| final public | `getTraceAsString(): string`<br> |
| public | `__toString(): string`<br> |
<hr>

###### created with [Rudra-Documentation-Collector](#https://github.com/Jagepard/Rudra-Documentation-Collector)

---

###### created with [Rudra-Documentation-Collector](https://github.com/Jagepard/Rudra-Documentation-Collector)
39 changes: 1 addition & 38 deletions src/ExceptionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,44 +13,7 @@

/**
* A marker interface used to tag all custom exceptions within the Rudra framework.
*
* This empty interface serves as a common base for grouping and filtering exceptions,
* making it easier to catch or identify all exceptions originating from the Rudra project.
*
* It is especially useful when:
* - You want to catch any exception thrown by your application or framework
* - You're building a reusable component and want to ensure a unified exception hierarchy
* - You are using PSR-14 or event-driven error handling
*
* Example usage:
* ```php
* try {
* $router->dispatch();
* } catch (\Rudra\Exceptions\ExceptionInterface $e) {
* // Handle any Rudra-related exception uniformly
* }
* ```
* ---------------------
* Маркерный интерфейс, используемый для группировки всех пользовательских исключений в фреймворке Rudra.
*
* Этот пустой интерфейс служит общей точкой отсчёта для группировки и фильтрации исключений,
* что упрощает их обработку и идентификацию в проекте.
*
* Он особенно полезен при:
* - Необходимости ловить любые исключения, брошенные приложением или фреймворком
* - Создании переиспользуемых компонентов с единой иерархией исключений
* - Работе с событийной моделью ошибок (например, PSR-14)
*
* Пример использования:
* ```php
* try {
* $router->dispatch();
* } catch (\Rudra\Exceptions\ExceptionInterface $e) {
* // Единым образом обрабатываем все исключения из Rudra
* }
* ```
*/
interface ExceptionInterface
interface ExceptionInterface extends \Throwable
{
// Пустой интерфейс — используется только как маркер для пользовательских исключений
}
24 changes: 0 additions & 24 deletions src/LogicException.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,5 @@
* An exception that indicates errors in the program logic.
* This type of exception should lead directly to code fixes — these are not runtime issues,
* but problems in implementation, configuration or incorrect use of the API.
*
* This class extends RudraException and implements ExceptionInterface,
* making it part of the unified exception hierarchy for the Rudra framework.
*
* Example:
* ```php
* if (!method_exists($controller, $action)) {
* throw new \Rudra\Exceptions\RouterException("503");
* }
* ```
* ---------------------
* Исключение, указывающее на ошибки логики программы.
* Такие ошибки должны приводить к исправлениям в коде — это не ошибки времени выполнения,
* а проблемы реализации, конфигурации или неверного использования API.
*
* Этот класс расширяет RudraException и реализует ExceptionInterface,
* что делает его частью единой системы исключений фреймворка Rudra.
*
* Пример:
* ```php
* if (!method_exists($controller, $action)) {
* throw new \Rudra\Exceptions\RouterException("503");
* }
* ```
*/
class LogicException extends RudraException implements ExceptionInterface {}
30 changes: 1 addition & 29 deletions src/MiddlewareException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,36 +11,8 @@

namespace Rudra\Exceptions;

use Rudra\Exceptions\ExceptionInterface;

/**
* An exception that is thrown when a middleware-related error occurs,
* such as an invalid format, missing class, or incorrect parameters.
*
* This exception is typically used in the routing and middleware execution layer
* of the framework to indicate issues with:
* - Invalid or unsupported middleware format
* - Missing or non-callable middleware class
* - Incorrect parameter handling
*
* It extends Rudra\Exception\LogicException to indicate that the problem is related to application logic
* and not runtime behavior.
*
* This exception implements ExceptionInterface for unified filtering and catching across the framework.
* ---------------------
* Исключение, выбрасываемое при возникновении ошибки, связанной с middleware, например:
* - Неверный формат middleware
* - Отсутствующий или неназванный класс middleware
* - Некорректная передача параметров
*
* Это исключение обычно используется на уровне маршрутизации и выполнения middleware для указания проблем с:
* - Неподдерживаемым форматом middleware
* - Отсутствием вызываемого метода __invoke()
* - Ошибками в параметрах
*
* Расширяет \Rudra\Exceptions\LogicException, чтобы показать, что проблема связана с логикой приложения,
* а не с состоянием среды выполнения.
*
* Реализует ExceptionInterface для унифицированной обработки всех исключений в рамках фреймворка.
*/
class MiddlewareException extends LogicException implements ExceptionInterface {}
class MiddlewareException extends LogicException {}
5 changes: 1 addition & 4 deletions src/NotFoundException.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,5 @@
/**
* Custom exception class for handling "Not Found" errors.
* This exception is typically thrown when a requested resource, service, or data is not found.
* -------------------------
* Пользовательский класс исключения для обработки ошибок "Не найдено".
* Это исключение обычно выбрасывается, когда запрашиваемый ресурс, сервис или данные не найдены.
*/
class NotFoundException extends RudraException {}
class NotFoundException extends RudraException {}
59 changes: 6 additions & 53 deletions src/RouterException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,80 +11,33 @@

namespace Rudra\Exceptions;

use Exception;
use Throwable;
use Rudra\Router\RouterFacade as Router;
use Rudra\Container\Facades\Rudra as Rudra;
use Rudra\Redirect\RedirectFacade as Redirect;

/**
* Represents an exception that occurs during route registration or dispatching.
* This exception is used when a route cannot be matched or dispatched correctly.
*
* When thrown, it triggers a custom exception handler to:
* - Set the appropriate HTTP error code
* - Dispatch the corresponding error controller action
*
* Example:
* ```php
* throw new \Rudra\Exceptions\RouterException("404");
* ```
*
* Will redirect to the configured error handler for "404" (if defined).
* -------------------------
* Представляет исключение, возникающее при регистрации или диспетчеризации маршрутов.
* Используется, когда маршрут не может быть найден или выполнен корректно.
*
* При выбрасывании исключения вызывается собственный обработчик ошибок, который:
* - Устанавливает соответствующий HTTP-код ошибки
* - Вызывает настроенный контроллер ошибки
*
* Пример:
* ```php
* throw new \Rudra\Exceptions\RouterException("404");
* ```
*
* Перенаправит на обработчик ошибок, определённый в конфигурации для кода "404".
*/
class RouterException extends RudraException
{
/**
* Constructs a new RouterException and sets a global exception handler.
*
* The exception handler will catch all unhandled exceptions of this type
* and redirect them using RedirectFacade to the appropriate error page/controller.
* -------------------------
* Конструктор RouterException устанавливает глобальный обработчик исключений.
*
* Обработчик перехватывает все неперехваченные исключения этого типа
* и вызывает RedirectFacade для перехода к странице/контроллеру ошибки.
*
* @param string $message
* @param int $code
* @param \Exception|null $previous
*/
public function __construct($message = "", $code = 0, ?Exception $previous = null)
public function __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
@set_exception_handler([$this, 'exception_handler']);
}

/**
* Custom exception handler triggered by this class.
*
* Uses RedirectFacade to send an HTTP status code and then calls the error handler,
* which is defined in the config under `http.errors`.
* -------------------------
* Собственный обработчик исключений, запускаемый этим классом.
*
* Использует RedirectFacade для отправки HTTP-статуса и вызова обработчика ошибок,
* указанного в конфигурации под ключом `http.errors`.
*
* @param \Exception $exception
* @return void
* Uses RedirectFacade to send an HTTP status code and then calls the error handler.
*/
public function exception_handler(\Exception $exception): void
public function exception_handler(Throwable $exception): void
{
Redirect::responseCode($exception->getMessage());
Router::directCall(Rudra::config()->get("http.errors")[$exception->getMessage()]);
Redirect::responseCode($exception->getCode());
Router::directCall(Rudra::config()->get("http.errors")[$exception->getCode()]);
}
}
41 changes: 1 addition & 40 deletions src/RudraException.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,44 +16,5 @@
/**
* Base exception class for all exceptions thrown by the Rudra framework.
* This class serves as the root of the exception hierarchy and implements ExceptionInterface.
*
* It's designed to:
* - Provide a common ancestor for all framework-related exceptions
* - Allow unified handling or catching of multiple exception types
* - Support categorization and filtering in larger applications or libraries
*
* All custom exceptions in the Rudra project should extend this class or one of its descendants.
*
* Example:
* ```php
* try {
* $router->set($route);
* } catch (\Rudra\Exceptions\RudraException $e) {
* // Handle any Rudra-related exception uniformly
* }
* ```
* ---------------------
* Базовый класс исключений для всех ошибок, генерируемых фреймворком Rudra.
* Этот класс служит корневым элементом иерархии исключений и реализует ExceptionInterface.
*
* Он предназначен для:
* - Обеспечения общей точки наследования для всех исключений фреймворка
* - Единой обработки или отлова всех типов исключений
* - Группировки и фильтрации ошибок в крупных приложениях и библиотеках
*
* Все пользовательские исключения в проекте Rudra должны наследоваться от этого класса
* или его потомков.
*
* Пример:
* ```php
* try {
* $router->set($route);
* } catch (\Rudra\Exceptions\RudraException $e) {
* // Единым образом обрабатываем любые исключения Rudra
* }
* ```
*/
class RudraException extends RuntimeException implements ExceptionInterface
{
// Пустой класс — используется как базовый для всех пользовательских исключений
}
class RudraException extends RuntimeException implements ExceptionInterface {}
3 changes: 0 additions & 3 deletions src/RuntimeException.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,5 @@
/**
* For errors that occur during execution, and depend on external factors
* (e.g. file not found, no write permissions, DB error, etc.)
* -----------------------------------------------------------
* Для ошибок, возникающих во время выполнения, и зависящих от внешних факторов
* (например, файл не найден, нет прав на запись, ошибка БД и т.д.)
*/
class RuntimeException extends RudraException {}
1 change: 0 additions & 1 deletion src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,3 @@ function abort(int $code): void
throw new RouterException($code);
}
}

Loading