Skip to content
Closed
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
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ build
composer.lock
phpunit.xml
vendor
composer-require-checker.phar
composer-require-checker.phar
.php-cs-fixer.php
tests/coverage
28 changes: 28 additions & 0 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ final class Router implements RequestHandler
use ForbidCloning;
use ForbidSerialization;

public const OPTIONS_METHOD = 'OPTIONS';
private const DEFAULT_CACHE_SIZE = 512;

private bool $running = false;
Expand Down Expand Up @@ -80,6 +81,13 @@ public function handleRequest(Request $request): Response

if (null === $match = $this->cache->get($toMatch)) {
$match = $this->routeDispatcher->dispatch($method, $path);

if ($this->isNotAllowedOptionsMethod($match, $method)) {
$toMatch = self::OPTIONS_METHOD . "\0{$path}";

$match = $this->optionsRequests($match[1], $request);
}

$this->cache->set($toMatch, $match);
}

Expand Down Expand Up @@ -300,4 +308,24 @@ private function onStop(): void
$this->routeDispatcher = null;
$this->running = false;
}

private function isNotAllowedOptionsMethod(array $match, string $method): bool
{
return $match[0] === Dispatcher::METHOD_NOT_ALLOWED
&& \count($match[1]) > 0
&& $method === self::OPTIONS_METHOD;
}

private function optionsRequests(array $methods, Request $request): array
{
$handler = new ClosureRequestHandler(fn () => $this->methodNotAllowed($methods, $request));

$requestHandler = Middleware\stackMiddleware($handler, ...$this->middlewares);

return [
Dispatcher::FOUND,
$requestHandler,
[],
];
}
}
64 changes: 63 additions & 1 deletion test/RouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public function testThrowsOnInvalidCacheSize(): void
{
$this->expectException(\Error::class);

new Router($this->server, $this->testLogger, $this->errorHandler, 0);
(new Router($this->server, $this->testLogger, $this->errorHandler, 0));
}

public function testRouteThrowsOnEmptyMethodString(): void
Expand All @@ -52,6 +52,7 @@ public function testRouteThrowsOnEmptyMethodString(): void

$router = new Router($this->server, $this->testLogger, $this->errorHandler);
$router->addRoute("", "/uri", new ClosureRequestHandler(function () {
// empty handler
}));
}

Expand Down Expand Up @@ -345,4 +346,65 @@ public function testSetFallbackAfterStart(): void
$this->expectExceptionMessage('Cannot add fallback');
$router->setFallback($requestHandler);
}

public function testHandleOptionsRequestWhenRouteIsNotMatched(): void
{
$router = new Router($this->server, $this->testLogger, $this->errorHandler);

$this->server->start($router, $this->errorHandler);

$request = new Request($this->createMock(Client::class), Router::OPTIONS_METHOD, Uri\Http::createFromString("/foo/bar"));
$response = $router->handleRequest($request);
$this->assertEquals(HttpStatus::NOT_FOUND, $response->getStatus());
$this->assertNull($response->getHeader('allow'));
}

public function testHandleOptionsRequestWithoutMiddlewares(): void
{
$requestHandler = new ClosureRequestHandler(function () {
return new Response(HttpStatus::OK);
});

$router = new Router($this->server, $this->testLogger, $this->errorHandler);
$router->addRoute("GET", "/foo/{name}", $requestHandler);

$this->server->start($router, $this->errorHandler);

$request = new Request($this->createMock(Client::class), Router::OPTIONS_METHOD, Uri\Http::createFromString("/foo/bar"));
$response = $router->handleRequest($request);
$this->assertEquals(HttpStatus::METHOD_NOT_ALLOWED, $response->getStatus());
$this->assertSame('GET', $response->getHeader('allow'));
}

public function testHandleOptionsRequestWithCorsMiddleware(): void
{
$requestHandler = new ClosureRequestHandler(function () {
return new Response(HttpStatus::OK);
});

$router = new Router($this->server, $this->testLogger, $this->errorHandler);
$router->addRoute("GET", "/foo/{name}", $requestHandler);

$router->addMiddleware(new class implements Middleware {
public function handleRequest(Request $request, RequestHandler $requestHandler): Response
{
if ($request->getMethod() === 'OPTIONS') {
$response = new Response();
$response->setHeader('Access-Control-Allow-Origin', '*');
$response->setStatus(HttpStatus::OK);

return $response;
}

return $requestHandler->handleRequest($request);
}
});

$this->server->start($router, $this->errorHandler);

$request = new Request($this->createMock(Client::class), Router::OPTIONS_METHOD, Uri\Http::createFromString("/foo/bar"));
$response = $router->handleRequest($request);
$this->assertEquals(HttpStatus::OK, $response->getStatus());
$this->assertSame('*', $response->getHeader('access-control-allow-origin'));
}
}