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 ( 9342c5...da5913 )
by Cees-Jan
02:41
created

Client::request()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 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
        $deferred = new Deferred();
117
118 4
        $this->handler->sendAsync(
119 4
            $this->createRequest($method, $path)
120
        )->then(function (ResponseInterface $response) use ($deferred) {
121 2
            $deferred->resolve($response);
122
        }, function ($error) use ($deferred) {
123
            $deferred->reject($error);
124 4
        });
125
126
        return $deferred->promise()->then(function ($response) use ($path, $raw) {
127 2
            $json = $response->getBody()->getContents();
128
129 2
            if ($this->cache instanceof CacheInterface) {
130 2
                $this->cache->set($path, $json);
131
            }
132
133 2
            return resolve($json);
134 4
        });
135
    }
136
137
    /**
138
     * @param string $method
139
     * @param string $path
140
     * @return RequestInterface
141
     */
142 4
    protected function createRequest(string $method, string $path): RequestInterface
143
    {
144 4
        $url = $this->getBaseURL() . $path;
145
        $headers = [
146 4
            'User-Agent' => $this->options['user_agent'],
147
        ];
148 4
        $headers += $this->options['headers'];
149 4
        return new Request($method, $url, $headers);
150
    }
151
152
    /**
153
     * @param string $json
154
     * @return PromiseInterface
155
     */
156
    public function jsonDecode(string $json): PromiseInterface
157
    {
158 3
        return futureFunctionPromise($this->loop, $json, function ($json) {
159 3
            return json_decode($json, true);
160 3
        });
161
    }
162
163
    /**
164
     * @return Hydrator
165
     */
166 1
    public function getHydrator(): Hydrator
167
    {
168 1
        return $this->hydrator;
169
    }
170
171
    /**
172
     * @return LoopInterface
173
     */
174 3
    public function getLoop(): LoopInterface
175
    {
176 3
        return $this->loop;
177
    }
178
179
    /**
180
     * @return string
181
     */
182 7
    public function getBaseURL(): string
183
    {
184 7
        return $this->options['schema'] . '://' . $this->options['host'] . $this->options['path'];
185
    }
186
}
187