Completed
Push — master ( 3b9ac7...e8290d )
by Dmitry
03:08
created

RequestFilterMiddleware::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tarantool\Mapper\Middleware;
6
7
use Exception;
8
use LogicException;
9
use Tarantool\Client\Handler\Handler;
10
use Tarantool\Client\Request\Request;
11
use Tarantool\Client\Response;
12
use Tarantool\Client\Middleware\Middleware;
13
14
class RequestFilterMiddleware implements Middleware
15
{
16
    private $whitelist = [];
17
    private $blacklist = [];
18
19
    public function addBlacklist(string $classname) : self
20
    {
21
        return $this->add('blacklist', $classname);
22
    }
23
24
    public function addWhitelist(string $classname) : self
25
    {
26
        return $this->add('whitelist', $classname);
27
    }
28
29
    public function process(Request $request, Handler $handler) : Response
30
    {
31
        $class = get_class($request);
32
        $isValid = !array_key_exists($class, $this->blacklist);
33
        if ($isValid) {
34
            $isValid = !count($this->whitelist) || array_key_exists($class, $this->whitelist);
35
        }
36
37
        if (!$isValid) {
38
            throw new Exception("Request $class is not allowed");
39
        }
40
41
        return $handler->handle($request);
42
    }
43
44
    private function add(string $category, string $classname) : self
45
    {
46
        if (!is_subclass_of($classname, Request::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Tarantool\Client\Request\Request::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
47
            throw new LogicException("$classname should extend ".Request::class);
48
        }
49
50
        $this->$category[$classname] = true;
51
        return $this;
52
    }
53
}