Skip to content

Instantly share code, notes, and snippets.

@akrabat
Created October 21, 2017 13:12
Show Gist options
  • Save akrabat/88d797036de4d2e3f64d41268f5c76a3 to your computer and use it in GitHub Desktop.
Save akrabat/88d797036de4d2e3f64d41268f5c76a3 to your computer and use it in GitHub Desktop.
Expressive factory to use CORS middleware
<?php declare(strict_types=1);
namespace App\Factory;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Tuupola\Middleware\Cors;
use Zend\Diactoros\Response;
use Zend\Diactoros\Response\JsonResponse;
use Zend\ProblemDetails\ProblemDetailsResponseFactory;
use Zend\Stratigility\Middleware\CallableMiddlewareWrapper;
class CorsMiddlewareFactory
{
protected static $problemDetailsResponseFactory;
public function __invoke($container)
{
self::$problemDetailsResponseFactory = $container->get(ProblemDetailsResponseFactory::class);
return new CallableMiddlewareWrapper(
new Cors([
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"],
"headers.allow" => ["Content-Type", "Accept"],
"headers.expose" => [],
"credentials" => false,
"cache" => 0,
"error" => [$this, 'error'],
]),
new Response()
);
}
public static function error(RequestInterface $request, ResponseInterface $response, $arguments)
{
return self::$problemDetailsResponseFactory->createResponse(
$request,
401,
'',
$arguments['message'],
'',
[]
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment