Completed
Push — master ( c29e8f...68ea4d )
by Alexpts
02:33
created

CheckXHR::__invoke()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 16
ccs 0
cts 10
cp 0
rs 8.8571
c 1
b 0
f 0
cc 5
eloc 10
nc 5
nop 2
crap 30
1
<?php
2
namespace PTS\Routing\Middlewares;
3
4
use Psr\Http\Message\RequestInterface;
5
6
class CheckXHR
7
{
8
    const ONLY_XHR = 1;
9
    const ONLY_NO_XHR = 2;
10
11
    protected $state;
12
13
    /**
14
     * CheckXHR constructor.
15
     * @param int $state
16
     */
17
    public function __construct(int $state = self::ONLY_XHR)
18
    {
19
        $this->state = $state;
20
    }
21
22
    /**
23
     * @param RequestInterface $request
24
     * @param callable $next
25
     * @return mixed
26
     */
27
    public function __invoke(RequestInterface $request, callable $next)
28
    {
29
        $isXHR = 'XMLHttpRequest' === $request->getHeader('X-Requested-With');
30
31
        switch ($this->state) {
32
            case self::ONLY_XHR:
33
                if (!$isXHR) { return null; }
34
                break;
35
            case self::ONLY_NO_XHR:
36
                if ($isXHR) { return null; }
37
                break;
38
39
        }
40
41
        return $next($request);
42
    }
43
}
44