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
Push — master ( da5913...4f177e )
by Cees-Jan
03:48
created

Client   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 189
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 7
dl 0
loc 189
ccs 51
cts 51
cp 1
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A request() 0 6 1
A requestRaw() 0 10 2
A checkCache() 0 8 2
A sendRequest() 0 14 2
A requestPsr7() 0 14 1
A createRequest() 0 6 1
A getHeaders() 0 8 1
A jsonDecode() 0 6 1
A getHydrator() 0 4 1
A getLoop() 0 4 1
A getBaseURL() 0 4 1
1
<?php
2
declare(strict_types=1);
3
4
namespace WyriHaximus\ApiClient\Transport;
5
6
use GuzzleHttp\Client as GuzzleClient;
7
use GuzzleHttp\Psr7\Request;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
use React\Cache\CacheInterface;
11
use React\EventLoop\LoopInterface;
12
use React\Promise\Deferred;
13
use React\Promise\PromiseInterface;
14
use function React\Promise\reject;
15
use function React\Promise\resolve;
16
use function WyriHaximus\React\futureFunctionPromise;
17
18
class Client
19
{
20
    const DEFAULT_OPTIONS = [
21
        'schema' => 'https',
22
        'path' => '/',
23
        'user_agent' => 'WyriHaximus/php-api-client',
24
        'headers' => [],
25
    ];
26
27
    /**
28
     * @var GuzzleClient
29
     */
30
    protected $handler;
31
32
    /**
33
     * @var LoopInterface
34
     */
35
    protected $loop;
36
37
    /**
38
     * @var array
39
     */
40
    protected $options = [];
41
42
    /**
43
     * @var Hydrator
44
     */
45
    protected $hydrator;
46
47
    /**
48
     * @var CacheInterface
49
     */
50
    protected $cache;
51
52
    /**
53
     * @param LoopInterface $loop
54
     * @param GuzzleClient $handler
55
     * @param array $options
56
     */
57 12
    public function __construct(LoopInterface $loop, GuzzleClient $handler, array $options = [])
58
    {
59 12
        $this->loop = $loop;
60 12
        $this->handler = $handler;
61 12
        $this->options = $options + self::DEFAULT_OPTIONS;
62 12
        if (isset($this->options['cache']) && $this->options['cache'] instanceof CacheInterface) {
63 3
            $this->cache = $this->options['cache'];
64
        }
65 12
        $this->hydrator = new Hydrator($this, $options);
66 12
    }
67
68
    /**
69
     * @param string $path
70
     * @param bool $refresh
71
     * @return PromiseInterface
72
     */
73 5
    public function request(string $path, bool $refresh = false): PromiseInterface
74
    {
75
        return $this->requestRaw($path, $refresh)->then(function ($json) {
76 3
            return $this->jsonDecode($json);
77 5
        });
78
    }
79
80
    /**
81
     * @param string $path
82
     * @param bool $refresh
83
     * @return PromiseInterface
84
     */
85 5
    public function requestRaw(string $path, bool $refresh = false): PromiseInterface
86
    {
87 5
        if ($refresh) {
88 2
            return $this->sendRequest($path);
89
        }
90
91
        return $this->checkCache($path)->otherwise(function () use ($path) {
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 otherwise() 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...
92 2
            return $this->sendRequest($path);
93 3
        });
94
    }
95
96
    /**
97
     * @param string $path
98
     * @return PromiseInterface
99
     */
100 3
    protected function checkCache(string $path): PromiseInterface
101
    {
102 3
        if ($this->cache instanceof CacheInterface) {
103 2
            return $this->cache->get($path);
104
        }
105
106 1
        return reject();
107
    }
108
109
    /**
110
     * @param string $path
111
     * @param string $method
112
     * @return PromiseInterface
113
     */
114 4
    protected function sendRequest(string $path, string $method = 'GET', bool $raw = false): PromiseInterface
115
    {
116 4
        return $this->requestPsr7(
117 4
            $this->createRequest($method, $path)
118
        )->then(function ($response) use ($path, $raw) {
119 2
            $json = $response->getBody()->getContents();
120
121 2
            if ($this->cache instanceof CacheInterface) {
122 2
                $this->cache->set($path, $json);
123
            }
124
125 2
            return resolve($json);
126 4
        });
127
    }
128
129
    /**
130
     * @param RequestInterface $request
131
     * @return PromiseInterface
132
     */
133 4
    public function requestPsr7(RequestInterface $request): PromiseInterface
134
    {
135 4
        $deferred = new Deferred();
136
137 4
        $this->handler->sendAsync(
138
            $request
139
        )->then(function (ResponseInterface $response) use ($deferred) {
140 2
            $deferred->resolve($response);
141
        }, function ($error) use ($deferred) {
142
            $deferred->reject($error);
143 4
        });
144
145 4
        return $deferred->promise();
146
    }
147
148
    /**
149
     * @param string $method
150
     * @param string $path
151
     * @return RequestInterface
152
     */
153 4
    protected function createRequest(string $method, string $path): RequestInterface
154
    {
155 4
        $url = $this->getBaseURL() . $path;
156 4
        $headers = $this->getHeaders();
157 4
        return new Request($method, $url, $headers);
158
    }
159
160
    /**
161
     * @return array
162
     */
163 4
    public function getHeaders(): array
164
    {
165
        $headers = [
166 4
            'User-Agent' => $this->options['user_agent'],
167
        ];
168 4
        $headers += $this->options['headers'];
169 4
        return $headers;
170
    }
171
172
    /**
173
     * @param string $json
174
     * @return PromiseInterface
175
     */
176
    public function jsonDecode(string $json): PromiseInterface
177
    {
178 3
        return futureFunctionPromise($this->loop, $json, function ($json) {
179 3
            return json_decode($json, true);
180 3
        });
181
    }
182
183
    /**
184
     * @return Hydrator
185
     */
186 1
    public function getHydrator(): Hydrator
187
    {
188 1
        return $this->hydrator;
189
    }
190
191
    /**
192
     * @return LoopInterface
193
     */
194 3
    public function getLoop(): LoopInterface
195
    {
196 3
        return $this->loop;
197
    }
198
199
    /**
200
     * @return string
201
     */
202 7
    public function getBaseURL(): string
203
    {
204 7
        return $this->options['schema'] . '://' . $this->options['host'] . $this->options['path'];
205
    }
206
}
207