Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introspective handling #14

Merged
merged 2 commits into from
Apr 20, 2023
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
13 changes: 0 additions & 13 deletions src/Router/Controllers/NotFound404Controller.php

This file was deleted.

15 changes: 15 additions & 0 deletions src/Router/Exceptions/NotFound404Exception.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace Gacela\Router\Exceptions;

use RuntimeException;

final class NotFound404Exception extends RuntimeException
{
public function __construct()
{
parent::__construct('Error 404 - Not Found');
}
}
23 changes: 22 additions & 1 deletion src/Router/Handlers.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@

namespace Gacela\Router;

use Exception;
use Gacela\Router\Exceptions\NotFound404Exception;
use Gacela\Router\Handlers\FallbackExceptionHandler;
use Gacela\Router\Handlers\NotFound404ExceptionHandler;

final class Handlers
{
/** @var array<class-string, callable> */
private array $handlers = [];

public function __construct()
{
$this->addBuiltInHandlers();
}
/**
* @param class-string $exception
* @param class-string<Exception> $exception
*/
public function handle(string $exception, callable $handler): self
{
Expand All @@ -25,4 +34,16 @@ public function getAllHandlers(): array
{
return $this->handlers;
}

private function addBuiltInHandlers(): void
{
$this->handle(
NotFound404Exception::class,
static fn (NotFound404Exception $exception) => (new NotFound404ExceptionHandler())->__invoke($exception),
);
$this->handle(
Exception::class,
static fn (Exception $exception) => (new FallbackExceptionHandler())->__invoke($exception),
);
}
}
17 changes: 17 additions & 0 deletions src/Router/Handlers/FallbackExceptionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Gacela\Router\Handlers;

use Exception;

final class FallbackExceptionHandler
{
public function __invoke(Exception $exception): string
{
header('HTTP/1.1 500 Internal Server Error');

return '';
}
}
17 changes: 17 additions & 0 deletions src/Router/Handlers/NotFound404ExceptionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Gacela\Router\Handlers;

use Gacela\Router\Exceptions\NotFound404Exception;

final class NotFound404ExceptionHandler
{
public function __invoke(NotFound404Exception $notFound404Exception): string
{
header('HTTP/1.0 404 Not Found');

return '';
}
}
16 changes: 8 additions & 8 deletions src/Router/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use Closure;
use Exception;
use Gacela\Router\Controllers\NotFound404Controller;
use Gacela\Router\Entities\Route;
use Gacela\Router\Exceptions\NotFound404Exception;
use ReflectionException;
use ReflectionFunction;

Expand All @@ -34,9 +34,10 @@ public static function configure(Closure $fn): void
$fn(...$params);

try {
echo self::findRoute($routes)->run($bindings);
echo self::findRoute($routes)
->run($bindings);
} catch (Exception $exception) {
echo self::handleException($handlers, $exception);
echo (string) self::findHandler($handlers, $exception)($exception);
}
}

Expand All @@ -48,18 +49,17 @@ private static function findRoute(Routes $routes): Route
}
}

return new Route('', '/', NotFound404Controller::class);
throw new NotFound404Exception();
}

private static function handleException(Handlers $handlers, Exception $exception): string
private static function findHandler(Handlers $handlers, Exception $exception): callable
{
$handler = $handlers->getAllHandlers()[get_class($exception)] ?? null;

if ($handler === null) {
header('HTTP/1.1 500 Internal Server Error');
return '';
return $handlers->getAllHandlers()[Exception::class];
}

return $handler($exception);
return $handler;
}
}
49 changes: 48 additions & 1 deletion tests/Feature/Router/ErrorHandlingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

namespace GacelaTest\Feature\Router;

use Exception;
use Gacela\Router\Entities\Request;
use Gacela\Router\Exceptions\NotFound404Exception;
use Gacela\Router\Handlers;
use Gacela\Router\Router;
use Gacela\Router\Routes;
Expand Down Expand Up @@ -101,7 +103,7 @@ public function test_respond_500_status_when_unhandled_exception(): void
], $this->headers());
}

public function test_handle_handled_exception(): void
public function test_handle_handled_exception_with_anonymous_function(): void
{
$_SERVER['REQUEST_URI'] = 'https://example.org/expected/uri';
$_SERVER['REQUEST_METHOD'] = Request::METHOD_GET;
Expand All @@ -116,7 +118,52 @@ public function test_handle_handled_exception(): void
});

$this->expectOutputString('Handled!');
self::assertSame([
[
'header' => 'HTTP/1.1 418 I\'m a teapot',
'replace' => true,
'response_code' => 0,
],
], $this->headers());
}

public function test_custom_404_handler(): void
{
$_SERVER['REQUEST_URI'] = 'https://example.org/expected/uri';
$_SERVER['REQUEST_METHOD'] = Request::METHOD_GET;

Router::configure(static function (Handlers $handlers): void {
$handlers->handle(NotFound404Exception::class, static function (): string {
\Gacela\Router\header('HTTP/1.1 418 I\'m a teapot');
return 'Handled!';
});
});

$this->expectOutputString('Handled!');
self::assertSame([
[
'header' => 'HTTP/1.1 418 I\'m a teapot',
'replace' => true,
'response_code' => 0,
],
], $this->headers());
}

public function test_custom_fallback_handler(): void
{
$_SERVER['REQUEST_URI'] = 'https://example.org/expected/uri';
$_SERVER['REQUEST_METHOD'] = Request::METHOD_GET;

Router::configure(static function (Handlers $handlers, Routes $routes): void {
$routes->get('expected/uri', FakeControllerWithUnhandledException::class);

$handlers->handle(Exception::class, static function (): string {
\Gacela\Router\header('HTTP/1.1 418 I\'m a teapot');
return 'Handled!';
});
});

$this->expectOutputString('Handled!');
self::assertSame([
[
'header' => 'HTTP/1.1 418 I\'m a teapot',
Expand Down
24 changes: 22 additions & 2 deletions tests/Feature/header.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

declare(strict_types=1);

namespace Gacela\Router\Controllers {
namespace Gacela\Router {
function header(string $header, bool $replace = true, int $responseCode = 0): void
{
/** @var list<array{header: string, replace: boolean, response_code: int}> | null $testHeaders */
Expand All @@ -22,7 +22,27 @@ function header(string $header, bool $replace = true, int $responseCode = 0): vo

// TODO: Find a better way to mock the head function in different namespaces

namespace Gacela\Router {
namespace Gacela\Router\Handlers {
function header(string $header, bool $replace = true, int $responseCode = 0): void
{
/** @var list<array{header: string, replace: boolean, response_code: int}> | null $testHeaders */
global $testHeaders;

if (!\is_array($testHeaders)) {
$testHeaders = [];
}

$testHeaders[] = [
'header' => $header,
'replace' => $replace,
'response_code' => $responseCode,
];
}
}

// TODO: Find a better way to mock the head function in different namespaces

namespace Gacela\Router\Controllers {
function header(string $header, bool $replace = true, int $responseCode = 0): void
{
/** @var list<array{header: string, replace: boolean, response_code: int}> | null $testHeaders */
Expand Down