Created
October 21, 2017 13:12
-
-
Save akrabat/88d797036de4d2e3f64d41268f5c76a3 to your computer and use it in GitHub Desktop.
Expressive factory to use CORS middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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