OptionsMiddleware::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace SubjectivePHP\Slim\Middleware;
4
5
use Fig\Http\Message\RequestMethodInterface;
6
use phpDocumentor\Reflection\DocBlock\Tags\Method;
0 ignored issues
show
introduced by
Unused use statement
Loading history...
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
0 ignored issues
show
introduced by
Comment missing for @throws tag in function comment
Loading history...
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