Skip to content

Instantly share code, notes, and snippets.

@aramis-it
Created June 12, 2021 00:35
Show Gist options
  • Save aramis-it/c9d64bfbd59dc5516e086f35cab73a7d to your computer and use it in GitHub Desktop.
Save aramis-it/c9d64bfbd59dc5516e086f35cab73a7d to your computer and use it in GitHub Desktop.
cakephp 4, cors, middleware
<?php
declare(strict_types=1);
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Cors middleware
*/
class CorsMiddleware implements MiddlewareInterface
{
/**
* Process method.
*
* @param \Psr\Http\Message\ServerRequestInterface $request The request.
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler.
* @return \Psr\Http\Message\ResponseInterface A response.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
if ($request->getHeader('Origin')) {
$response = $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', '*');
if (strtoupper($request->getMethod()) === 'OPTIONS') {
$response = $response
->withStatus(200, __('Say cheese!'));
}
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment