Completed
Push — master ( 9a342a...a162ae )
by Andrii
13:06
created

UseBaseMiddleware::ensureCommandExists()   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 hiapi\Core\Http\Psr7\Response\FatResponse;
6
use hiapi\exceptions\NotAuthenticatedException;
7
use hiapi\legacy\lib\mrdpBase;
8
use Psr\Container\ContainerInterface;
9
use Psr\Http\Message\MessageInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Psr\Http\Message\ServerRequestInterface;
12
use Psr\Http\Server\MiddlewareInterface;
13
use Psr\Http\Server\RequestHandlerInterface;
14
15
class UseBaseMiddleware implements MiddlewareInterface
16
{
17
    /**
18
     * @var ContainerInterface
19
     */
20
    private $container;
21
22
    public function __construct(ContainerInterface $container)
23
    {
24
        $this->container = $container;
25
    }
26
27
    /**
28
     * @inheritDoc
29
     */
30
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
31
    {
32
        return $this->perform($request);
33
    }
34
35
    private function perform(ServerRequestInterface $request): ResponseInterface
36
    {
37
        $command = $this->getCommandName($request);
38
39
        $this->ensureCommandExists($command);
40
        $this->ensureCommandAllowed($command);
41
42
        $data = $this->getInputData($request);
43
44
        $res = $this->getBase()->{$command}($data);
45
46
        if ($res instanceof ResponseInterface) {
47
            return $res;
48
        }
49
50
        return FatResponse::create($res, $request);
51
    }
52
53
    private function getInputData(ServerRequestInterface $request): array
54
    {
55
        $query = $request->getQueryParams();
56
        $post  = $request->getParsedBody();
57
58
        return array_merge($query, $post);
59
60
        // XXX TODO check if it really exactly corresponds to
61
        // return $_REQUEST;
62
    }
63
64
    private function getCommandName(MessageInterface $request): string
65
    {
66
        $path = $request->getUri()->getPath();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\MessageInterface as the method getUri() does only exist in the following implementations of said interface: GuzzleHttp\Psr7\Request, GuzzleHttp\Psr7\ServerRequest, hiapi\console\ServerRequest.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
67
        $URLPARTS = explode('/', ltrim($path, '/'));
68
69
        return $URLPARTS[0];
70
    }
71
72
    private $base;
73
74
    private function getBase(): mrdpBase
75
    {
76
        if ($this->base === null) {
77
            $this->base = $this->container->get(mrdpBase::class);
78
        }
79
80
        return $this->base;
81
    }
82
83
    private function ensureCommandExists(string $command): void
84
    {
85
        if (!$this->getBase()->hasCommand($command)) {
86
            throw new \RuntimeException("Not existing command: $command");
87
        }
88
    }
89
90
    private function ensureCommandAllowed(string $command): void
91
    {
92
        if (!$this->getBase()->isCommandAllowed($command)) {
93
            throw new NotAuthenticatedException("Not allowed command: $command");
94
        }
95
    }
96
}
97