GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#18)
by
unknown
02:15
created

CacheMiddleware::post()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 4.054

Importance

Changes 0
Metric Value
dl 0
loc 40
ccs 17
cts 20
cp 0.85
rs 9.28
c 0
b 0
f 0
cc 4
nc 3
nop 3
crap 4.054
1
<?php declare(strict_types=1);
2
3
namespace ApiClients\Middleware\Cache;
4
5
use ApiClients\Foundation\Middleware\MiddlewareInterface;
6
use Psr\Http\Message\RequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use React\Cache\CacheInterface;
9
use React\Promise\CancellablePromiseInterface;
10
use React\Promise\PromiseInterface;
11
use function React\Promise\reject;
12
use function React\Promise\resolve;
13
use RingCentral\Psr7\BufferStream;
14
use Throwable;
15
16
final class CacheMiddleware implements MiddlewareInterface
17
{
18
    const DEFAULT_GLUE = '/';
19
20
    /**
21
     * @var CacheInterface[]
22
     */
23
    private $cache;
24
25
    /**
26
     * @var string[]
27
     */
28
    private $key;
29
30
    /**
31
     * @var RequestInterface[]
32
     */
33
    private $request;
34
35
    /**
36
     * @var bool[]
37
     */
38
    private $store = false;
39
40
    /**
41
     * @var StrategyInterface[]
42
     */
43
    private $strategy;
44
45
    /**
46
     * @param  RequestInterface            $request
47
     * @param  array                       $options
48
     * @return CancellablePromiseInterface
49
     */
50 13
    public function pre(
51
        RequestInterface $request,
52
        string $transactionId,
53
        array $options = []
54
    ): CancellablePromiseInterface {
55 13
        if (!isset($options[self::class][Options::CACHE]) || !isset($options[self::class][Options::STRATEGY])) {
56
            return resolve($request);
57
        }
58 13
        $this->cache[$transactionId] = $options[self::class][Options::CACHE];
59 13
        $this->strategy[$transactionId] = $options[self::class][Options::STRATEGY];
60 13
        if (!($this->cache[$transactionId] instanceof CacheInterface) ||
61 13
            !($this->strategy[$transactionId] instanceof StrategyInterface)
62
        ) {
63
            return resolve($request);
64
        }
65
66 13
        if ($request->getMethod() !== 'GET') {
67 10
            $this->cleanUpTransaction($transactionId);
68
69 10
            return resolve($request);
70
        }
71
72 3
        $this->request[$transactionId] = $request;
73 3
        $this->key[$transactionId] = CacheKey::create(
74 3
            $this->request[$transactionId]->getUri(),
75 3
            $options[self::class][Options::GLUE] ?? self::DEFAULT_GLUE
76
        );
77
78 3
        return $this->cache[$transactionId]->get(
79 3
            $this->key[$transactionId]
80
        )->then(function (string $json) use ($transactionId) {
81 1
            $document = Document::createFromString($json);
82
83 1
            if ($document->hasExpired()) {
84
                $this->cache[$transactionId]->remove($this->key[$transactionId]);
0 ignored issues
show
Bug introduced by
The method remove() does not seem to exist on object<React\Cache\CacheInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
85
86
                return resolve($this->request[$transactionId]);
87
            }
88
89 1
            return reject($document->getResponse());
90
        }, function () use ($transactionId) {
91 2
            return resolve($this->request[$transactionId]);
92 3
        });
93
    }
94
95
    /**
96
     * @param  ResponseInterface           $response
97
     * @param  array                       $options
98
     * @return CancellablePromiseInterface
99
     */
100 11
    public function post(
101
        ResponseInterface $response,
102
        string $transactionId,
103
        array $options = []
104
    ): CancellablePromiseInterface {
105 11
        if (!isset($this->request[$transactionId]) ||
106 11
            !($this->request[$transactionId] instanceof RequestInterface)
107
        ) {
108 10
            $this->cleanUpTransaction($transactionId);
109
110 10
            return resolve($response);
111
        }
112
113 1
        $this->store[$transactionId] = $this->strategy[$transactionId]->
114 1
            decide($this->request[$transactionId], $response);
115
116 1
        if (!$this->store[$transactionId]) {
117
            $this->cleanUpTransaction($transactionId);
118
119
            return resolve($response);
120
        }
121
122
        return $this->hasBody($response)->then(function (ResponseInterface $response) use ($transactionId) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface React\Promise\PromiseInterface as the method always() does only exist in the following implementations of said interface: React\Promise\FulfilledPromise, React\Promise\LazyPromise, React\Promise\Promise, React\Promise\RejectedPromise.

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...
123 1
            $document = Document::createFromResponse(
124 1
                $response,
125 1
                $this->strategy[$transactionId]->determineTtl(
126 1
                    $this->request[$transactionId],
127 1
                    $response
128
                )
129
            );
130
131 1
            $this->cache[$transactionId]->set($this->key[$transactionId], (string)$document);
132
133 1
            return resolve($document->getResponse());
134
        }, function () use ($response) {
135
            return resolve($response);
136
        })->always(function () use ($transactionId): void {
137 1
            $this->cleanUpTransaction($transactionId);
138 1
        });
139
    }
140
141
    public function error(
142
        Throwable $throwable,
143
        string $transactionId,
144
        array $options = []
145
    ): CancellablePromiseInterface {
146
        $this->cleanUpTransaction($transactionId);
147
148
        return reject($throwable);
149
    }
150
151
    /**
152
     * @param  ResponseInterface $response
153
     * @return PromiseInterface
154
     */
155 1
    private function hasBody(ResponseInterface $response): PromiseInterface
156
    {
157 1
        if ($response->getBody() instanceof BufferStream) {
158 1
            return resolve($response);
159
        }
160
161
        return reject();
162
    }
163
164 11
    private function cleanUpTransaction(string $transactionId): void
165
    {
166 11
        if (isset($this->cache[$transactionId])) {
167 11
            unset($this->cache[$transactionId]);
168
        }
169
170 11
        if (isset($this->strategy[$transactionId])) {
171 11
            unset($this->strategy[$transactionId]);
172
        }
173
174 11
        if (isset($this->request[$transactionId])) {
175 1
            unset($this->request[$transactionId]);
176
        }
177
178 11
        if (isset($this->key[$transactionId])) {
179 1
            unset($this->key[$transactionId]);
180
        }
181
182 11
        if (isset($this->store[$transactionId])) {
183 1
            unset($this->store[$transactionId]);
184
        }
185 11
    }
186
}
187