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

OriginOrRefererHeader::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
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
 * Fetches data from the Origin header, or from the Referer header if the Origin header is not present
11
 */
12
class OriginOrRefererHeader implements SourceOriginInterface
13
{
14
    use HeaderFetcher;
15
16
    /**
17
     * Returns the domain name of the website performing the request.
18
     *
19
     * @param ServerRequestInterface $request
20
     * @return string
21
     * @throws \TheCodingMachine\Middlewares\CsrfHeaderCheckMiddlewareException
22
     */
23
    public function __invoke(ServerRequestInterface $request): string
24
    {
25
        $source = $this->getHeaderLine($request, 'ORIGIN');
26
        if (null !== $source) {
27
            return parse_url($source, PHP_URL_HOST);
28
        }
29
30
        $referrer = $this->getHeaderLine($request, 'REFERER');
31
        if (null === $referrer) {
32
            throw new CsrfHeaderCheckMiddlewareException('Could not find neither the ORIGIN header nor the REFERER header in the HTTP request.');
33
        }
34
35
        return parse_url($referrer, PHP_URL_HOST);
36
    }
37
}
38