1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SubjectivePHP\Slim\Middleware; |
4
|
|
|
|
5
|
|
|
use Fig\Http\Message\RequestMethodInterface; |
6
|
|
|
use phpDocumentor\Reflection\DocBlock\Tags\Method; |
|
|
|
|
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
9
|
|
|
use Slim\Exception\NotFoundException; |
10
|
|
|
|
11
|
|
|
final class OptionsMiddleware implements RequestMethodInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
private $origin; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var string[] |
20
|
|
|
*/ |
21
|
|
|
private $headers; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Create a new instance of OptionsMiddleware. |
25
|
|
|
* |
26
|
|
|
* @param string $origin Value for the Access-Control-Allow-Origin header. |
27
|
|
|
* @param string[] $headers Value for the Access-Control-Allow-Headers header. |
28
|
|
|
*/ |
29
|
|
|
public function __construct(string $origin, array $headers) |
30
|
|
|
{ |
31
|
|
|
$this->origin = $origin; |
32
|
|
|
$this->headers = $headers; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Invoke this middleware. |
37
|
|
|
* |
38
|
|
|
* @param ServerRequestInterface $request The incoming HTTP request. |
39
|
|
|
* @param ResponseInterface $response The outgoing HTTP response. |
40
|
|
|
* @param callable $next The next middleware in the stack. |
41
|
|
|
* |
42
|
|
|
* @return ResponseInterface |
43
|
|
|
* |
44
|
|
|
* @throws NotFoundException |
|
|
|
|
45
|
|
|
*/ |
46
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) : ResponseInterface |
47
|
|
|
{ |
48
|
|
|
if ($request->getMethod() !== self::METHOD_OPTIONS) { |
49
|
|
|
return $next($request, $response); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$route = $request->getAttribute('route'); |
53
|
|
|
if (empty($route)) { |
54
|
|
|
throw new NotFoundException($request, $response); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$methods = $route->getMethods(); |
58
|
|
|
$methods[] = self::METHOD_OPTIONS; |
59
|
|
|
return $response->withHeader('Access-Control-Allow-Origin', $this->origin) |
60
|
|
|
->withHeader('Access-Control-Allow-Headers', implode(',', $this->headers)) |
61
|
|
|
->withHeader('Access-Control-Allow-Methods', implode(',', $methods)); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|