/**
* Handles preflight requests.
*
* @param String $method The REST verb
*
* @param ApiRouter $router The API Routing object
*
* @return void
*
* @since 4.0.0
*/
protected function handlePreflight($method, $router)
{
/**
* If not an OPTIONS request or CORS is not enabled,
* there's nothing useful to do here.
*/
if ($method !== 'OPTIONS' || !(int) $this->get('cors')) {
return;
}
// Extract routes matching current route from all known routes.
$matchingRoutes = $router->getMatchingRoutes();
// Extract exposed methods from matching routes.
$matchingRoutesMethods = array_unique(array_reduce($matchingRoutes, function ($carry, $route) {
return array_merge($carry, $route->getMethods());
}, []));
/**
* Obtain allowed CORS origin from Global Settings.
* Set to * (=all) if not set.
*/
$allowedOrigin = $this->get('cors_allow_origin', '*');
/**
* Obtain allowed CORS headers from Global Settings.
* Set to sensible default if not set.
*/
$allowedHeaders = $this->get('cors_allow_headers', 'Content-Type,X-Joomla-Token');
/**
* Obtain allowed CORS methods from Global Settings.
* Set to methods exposed by current route if not set.
*/
$allowedMethods = $this->get('cors_allow_methods', implode(',', $matchingRoutesMethods));
// No use to go through the regular route handling hassle,
// so let's simply output the headers and exit.
$this->setHeader('status', '204');
$this->setHeader('Access-Control-Allow-Origin', $allowedOrigin);
$this->setHeader('Access-Control-Allow-Headers', $allowedHeaders);
$this->setHeader('Access-Control-Allow-Methods', $allowedMethods);
$this->sendHeaders();
$this->close();
}