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 — 1.x ( 14dc7b...51d58d )
by Jakub
04:08
created

ResourceBase::getHeaders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * Resource base class.
5
 *
6
 * Abstract resource base class.
7
 */
8
9
namespace Vipps\Resource;
10
11
use Doctrine\Common\Annotations\AnnotationRegistry;
12
use Http\Client\Exception\HttpException;
13
use Http\Client\HttpAsyncClient;
14
use Http\Client\HttpClient;
15
use JMS\Serializer\SerializerBuilder;
16
use Psr\Http\Message\RequestInterface;
17
use Vipps\Exceptions\VippsException;
18
use Vipps\VippsInterface;
19
20
/**
21
 * Class ResourceBase
22
 * @package Vipps\Resources
23
 */
24
abstract class ResourceBase implements ResourceInterface
25
{
26
27
    /**
28
     * @var VippsInterface
29
     */
30
    protected $app;
31
32
    /**
33
     * @var array
34
     */
35
    protected $headers = [];
36
37
    /**
38
     * @var string
39
     */
40
    protected $body = '';
41
42
    /**
43
     * @var string
44
     */
45
    protected $id;
46
47
    /**
48
     * @var string
49
     */
50
    protected $path;
51
52
    /**
53
     * @var \Vipps\Resource\HttpMethod
54
     */
55
    protected $method;
56
57
    /**
58
     * @var \JMS\Serializer\Serializer
59
     */
60
    protected $serializer;
61
62
    /**
63
     * AbstractResource constructor.
64
     *
65
     * @param \Vipps\VippsInterface $vipps
66
     * @param string $subscription_key
67
     */
68
    public function __construct(VippsInterface $vipps, $subscription_key)
69
    {
70
        $this->app = $vipps;
71
72
        $this->headers['Ocp-Apim-Subscription-Key'] = $subscription_key;
73
74
        // Initiate serializer.
75
        AnnotationRegistry::registerLoader('class_exists');
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\Common\Annotati...istry::registerLoader() has been deprecated with message: this method is deprecated and will be removed in doctrine/annotations 2.0 autoloading should be deferred to the globally registered autoloader by then. For now, use @example AnnotationRegistry::registerLoader('class_exists')

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
76
        $this->serializer = SerializerBuilder::create()
77
            ->build();
78
    }
79
80
    /**
81
     * Gets serializer value.
82
     *
83
     * @return \JMS\Serializer\Serializer
84
     */
85
    public function getSerializer()
86
    {
87
        return $this->serializer;
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function getHeaders()
94
    {
95
        return $this->headers;
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function getMethod()
102
    {
103
        if (!isset($this->method)) {
104
            throw new \LogicException('Missing HTTP method');
105
        }
106
        return $this->method;
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     *
112
     * All occurrences of {id} pattern will be replaced with $this->id
113
     */
114
    public function getPath()
115
    {
116
        if (!isset($this->path)) {
117
            throw new \LogicException('Missing resource path');
118
        }
119
        // Get local var.
120
        $path = $this->path;
121
        // If ID is set replace {id} pattern with model's ID.
122
        if (isset($this->id)) {
123
            $path = str_replace('{id}', $this->id, $path);
124
        }
125
        return $path;
126
    }
127
128
    /**
129
     * @return string
130
     */
131
    public function getBody()
132
    {
133
        return $this->body;
134
    }
135
136
    /**
137
     * @param $path
138
     *
139
     * @return \Psr\Http\Message\UriInterface
140
     */
141
    public function getUri($path)
142
    {
143
        return $this->app->getClient()->getEndpoint()->getUri()->withPath($path);
144
    }
145
146
    /**
147
     * @return \Psr\Http\Message\ResponseInterface
148
     *
149
     * @throws \Vipps\Exceptions\VippsException
150
     */
151
    protected function makeCall()
152
    {
153
        try {
154
            $request = $this->getRequest();
155
            $response = $this->handleRequest($request);
156
        } catch (HttpException $e) {
157
            // Catch exceptions thrown by http client.
158
            // We must do that in order to normalize output.
159
            $response = $e->getResponse();
160
        } catch (\Exception $e) {
161
            // Something went really bad here.
162
            throw new VippsException($e->getMessage(), $e->getCode(), $e);
163
        }
164
        return $this->handleResponse($response);
165
    }
166
167
    /**
168
     * @param \Psr\Http\Message\RequestInterface $request
169
     *
170
     * @return \Psr\Http\Message\ResponseInterface
171
     */
172
    protected function handleRequest(RequestInterface $request)
173
    {
174
        // Get client.
175
        $client = $this->app->getClient()->getHttpClient();
176
177
        // Handle requests, sync precedence.
178
        if ($client instanceof HttpClient) {
179
            // Send sync request.
180
            $response = $client->sendRequest($request);
181
        } elseif ($client instanceof HttpAsyncClient) {
182
            // Send async request.
183
            $response = $client->sendAsyncRequest($request)->wait();
184
        } else {
185
            throw new \LogicException('Unknown HTTP Client type: '. implode(',', class_implements($client)));
186
        }
187
188
        return $response;
189
    }
190
191
    /**
192
     * @return \Psr\Http\Message\RequestInterface
193
     */
194
    protected function getRequest()
195
    {
196
        return $this->app->getClient()->getMessageFactory()->createRequest(
197
            $this->getMethod(),
198
            $this->getUri($this->getPath()),
199
            $this->getHeaders(),
200
            $this->getBody()
201
        );
202
    }
203
204
    /**
205
     * @param \Psr\Http\Message\ResponseInterface $response
206
     *
207
     * @return \Psr\Http\Message\ResponseInterface
208
     *
209
     * @throws \Vipps\Exceptions\VippsException
210
     */
211
    protected function handleResponse($response)
212
    {
213
        // @todo: Handle error.
214
        // Handle request errors.
215
        if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) {
216
            $error = $response->getBody()->getContents();
217
            throw new VippsException($error, $response->getStatusCode());
218
        }
219
220
        // Handle server errors.
221
        if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) {
222
            throw new VippsException(
223
                $response->getReasonPhrase(),
224
                $response->getStatusCode()
225
            );
226
        }
227
228
        // Sometimes VIPPS returns 200 with error message :/ They promised
229
        // to fix it but as a temporary fix we are gonna check if body is
230
        // "invalid" and throw exception in such a case.
231
        $exception = VippsException::createFromResponse($response);
232
        if ($exception instanceof VippsException) {
233
            throw $exception;
234
        }
235
236
        return $response;
237
    }
238
}
239