Skip to content

Commit

Permalink
Requests that match only OPTIONS should be 404
Browse files Browse the repository at this point in the history
Because the OptionsController matches on all URIs, Silex reports a 405
Method Not Allowed when it should be a 404 Not Found.
  • Loading branch information
jdesrosiers committed Mar 8, 2017
1 parent 07e3c6e commit 67b0b4f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/CorsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
use Silex\Controller;
use Silex\ControllerCollection;
use Silex\ServiceProviderInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;

/**
* The CORS service provider provides a `cors` service that a can be included in your project as application middleware.
Expand All @@ -22,6 +26,13 @@ public function boot(Application $app)
$app->match("{route}", new OptionsController())
->assert("route", ".+")
->method("OPTIONS");

$app->on(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) {
$e = $event->getException();
if ($e instanceof MethodNotAllowedHttpException && $e->getHeaders()["Allow"] === "OPTIONS") {
$event->setException(new NotFoundHttpException());
}
});
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/OptionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public function __invoke(Application $app, Request $request)

$app["request_context"]->setMethod("OPTIONS");

if (count($allow) == 0) {
if (count($allow) === 0) {
throw new NotFoundHttpException();
}

Expand Down
10 changes: 10 additions & 0 deletions src/Test/CorsServiceProviderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -300,4 +300,14 @@ public function testNotEnabledMethod()
$this->assertEquals("405", $response->getStatusCode());
$this->assertEquals("POST, OPTIONS", $response->headers->get("Allow"));
}

public function testRouteWithOptionsOnlyRespondsWith404()
{
$client = new Client($this->app);
$client->request("GET", "/foo");

$response = $client->getResponse();

$this->assertEquals("404", $response->getStatusCode());
}
}

0 comments on commit 67b0b4f

Please sign in to comment.