Passed
Push — master ( c44d00...13b3c2 )
by David
53s
created

HostHeader::__invoke()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
4
namespace TheCodingMachine\Middlewares\OriginFetchers;
5
6
use Psr\Http\Message\ServerRequestInterface;
7
use TheCodingMachine\Middlewares\CsrfHeaderCheckMiddlewareException;
8
9
/**
10
 * Reads the target origin from the "Host" HTTP 1.1 header.
11
 * Note: the "Host" header cannot be modified from Javascript.
12
 *
13
 * We do not rely on the "X-Forwarded-Host" header on purpose because this header can be tempered from JS.
14
 */
15
class HostHeader implements TargetOriginInterface
16
{
17
    use HeaderFetcher;
18
19
    /**
20
     * Returns an array of allowed domain names.
21
     * If the "source" origin matches one of these origins, the request is valid.
22
     *
23
     * @return string[]
24
     * @throws \TheCodingMachine\Middlewares\CsrfHeaderCheckMiddlewareException
25
     */
26
    public function __invoke(ServerRequestInterface $request): array
27
    {
28
        $host = $this->getHeaderLine($request, 'HOST');
29
30
        if (null === $host) {
31
            throw new CsrfHeaderCheckMiddlewareException('Could not find the HOST header in the HTTP request.');
32
        }
33
34
        return [ $this->removePortFromHost($host) ];
35
    }
36
37
    private function removePortFromHost(string $host)
38
    {
39
        return explode(':', $host)[0];
40
    }
41
}
42