Completed
Push — master ( 1db52f...973541 )
by Dmitry
20:40 queued 05:39
created

CorsMiddleware::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace hiapi\Core\Http\Psr15\Middleware;
4
5
use Psr\Http\Message\ResponseFactoryInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
use Psr\Http\Server\MiddlewareInterface;
9
use Psr\Http\Server\RequestHandlerInterface;
10
11
class CorsMiddleware implements MiddlewareInterface
12
{
13
    protected $headers = [
14
        'Access-Control-Allow-Origin' => ['*'],
15
        'Access-Control-Request-Method' => ['GET POST'],
16
    ];
17
    public bool $interceptOptionsRequests = false;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
18
    private ResponseFactoryInterface $responseFactory;
19
20
    public function __construct(array $headers = [], ResponseFactoryInterface $responseFactory)
21
    {
22
        foreach ($headers as $name => $value) {
23
            $this->addHeader($name, $value);
24
        }
25
        $this->responseFactory = $responseFactory;
26
    }
27
28
    public function addHeader($name, $value): self
29
    {
30
        $this->headers[$name] = array_merge($this->headers[$name] ?? [], [$value]);
31
32
        return $this;
33
    }
34
35
    /**
36
     * @inheritDoc
37
     */
38
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
39
    {
40
        if ($this->interceptOptionsRequests && $request->getMethod() === 'OPTIONS') {
41
            return $this->addHeaders($this->responseFactory->createResponse(201));
42
        }
43
44
        $response = $handler->handle($request);
45
46
        return $this->addHeaders($response);
47
    }
48
49
    private function addHeaders(ResponseInterface $response)
50
    {
51
        foreach ($this->headers as $name => $headers) {
52
            $response = $response->withHeader($name, $headers);
53
        }
54
55
        return $response;
56
    }
57
}
58