MoipResource::getByPathNoPopulate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Moip\Resource;
4
5
use JsonSerializable;
6
use Moip\Exceptions;
7
use Moip\Helper\Filters;
8
use Moip\Helper\Links;
9
use Moip\Helper\Pagination;
10
use Moip\Moip;
11
use Requests;
12
use Requests_Exception;
13
use stdClass;
14
15
/**
16
 * Class MoipResource.
17
 */
18
abstract class MoipResource implements JsonSerializable
19
{
20
    /**
21
     * Version of API.
22
     *
23
     * @const string
24
     */
25
    const VERSION = 'v2';
26
27
    /**
28
     * Api version content type.
29
     *
30
     * @cont string
31
     */
32
    const ACCEPT_VERSION = 'application/json;version=2.1';
33
34
    /**
35
     * @var \Moip\Moip
36
     */
37
    protected $moip;
38
39
    /**
40
     * @var \stdClass
41
     */
42
    protected $data;
43
44
    /**
45
     * Initialize a new instance.
46
     */
47
    abstract protected function initialize();
48
49
    /**
50
     * Mount information of a determined object.
51
     *
52
     * @param \stdClass $response
53
     *
54
     * @return mixed
55
     */
56
    abstract protected function populate(stdClass $response);
57
58
    /**
59
     * Create a new instance.
60
     *
61
     * @param \Moip\Moip $moip
62
     */
63
    public function __construct(Moip $moip)
64
    {
65
        $this->moip = $moip;
66
        $this->data = new stdClass();
67
        $this->initialize();
68
    }
69
70
    /**
71
     * Get a key of an object if it exists.
72
     *
73
     * @param string         $key
74
     * @param \stdClass|null $data
75
     *
76
     * @return mixed
77
     */
78
    protected function getIfSet($key, stdClass $data = null)
79
    {
80
        if (empty($data)) {
81
            $data = $this->data;
82
        }
83
84
        if (isset($data->$key)) {
85
            return $data->$key;
86
        }
87
    }
88
89
    /**
90
     * @return \Moip\Helper\Links
91
     */
92
    public function getLinks()
93
    {
94
        $links = $this->getIfSet('_links');
95
96
        if ($links !== null) {
97
            return new Links($links);
98
        }
99
    }
100
101
    /**
102
     * @param $key
103
     * @param $fmt
104
     * @param stdClass|null $data
105
     *
106
     * @return bool|\DateTime|null
107
     */
108 View Code Duplication
    protected function getIfSetDateFmt($key, $fmt, stdClass $data = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
    {
110
        $val = $this->getIfSet($key, $data);
111
        if (!empty($val)) {
112
            $dt = \DateTime::createFromFormat($fmt, $val);
113
114
            return $dt ? $dt : null;
115
        }
116
    }
117
118
    /**
119
     * Get a key, representing a date (Y-m-d), of an object if it exists.
120
     *
121
     * @param string        $key
122
     * @param stdClass|null $data
123
     *
124
     * @return \DateTime|null
125
     */
126
    protected function getIfSetDate($key, stdClass $data = null)
127
    {
128
        return $this->getIfSetDateFmt($key, 'Y-m-d', $data);
129
    }
130
131
    /**
132
     * Get a key representing a datetime (\Datetime::ATOM), of an object if it exists.
133
     *
134
     * @param string        $key
135
     * @param stdClass|null $data
136
     *
137
     * @return \DateTime|null
138
     */
139 View Code Duplication
    protected function getIfSetDateTime($key, stdClass $data = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
140
    {
141
        $rawDateTime = $this->getIfSet($key, $data);
142
143
        $dateTime = null;
144
        if (!empty($rawDateTime)) {
145
            $dateTime = new \DateTime($rawDateTime);
146
        }
147
148
        return $dateTime;
149
    }
150
151
    /**
152
     * Specify data which should be serialized to JSON.
153
     *
154
     * @return \stdClass
155
     */
156
    public function jsonSerialize()
157
    {
158
        return $this->data;
159
    }
160
161
    /**
162
     * Generate URL to request.
163
     *
164
     * @param $action
165
     * @param $id
166
     *
167
     * @return string
168
     */
169
    public function generatePath($action, $id = null)
170
    {
171
        if (!is_null($id)) {
172
            return sprintf('%s/%s/%s/%s', self::VERSION, static::PATH, $action, $id);
173
        }
174
175
        return sprintf('%s/%s/%s', self::VERSION, static::PATH, $action);
176
    }
177
178
    /**
179
     * Generate URL to request a get list.
180
     *
181
     * @param Pagination $pagination
182
     * @param Filters    $filters
183
     * @param array      $params
184
     *
185
     * @return string
186
     */
187
    public function generateListPath(Pagination $pagination = null, Filters $filters = null, $params = [])
188
    {
189
        $queryParams = [];
190
191
        if (!is_null($pagination)) {
192
            if ($pagination->getLimit() != 0) {
193
                $queryParams['limit'] = $pagination->getLimit();
194
            }
195
196
            if ($pagination->getOffset() >= 0) {
197
                $queryParams['offset'] = $pagination->getOffset();
198
            }
199
        }
200
201
        if (!is_null($filters)) {
202
            $queryParams['filters'] = $filters->__toString();
203
        }
204
205
        if (!empty($params)) {
206
            $queryParams = array_merge($queryParams, $params);
207
        }
208
209
        if (!empty($queryParams)) {
210
            return sprintf('/%s/%s?%s', self::VERSION, static::PATH, http_build_query($queryParams));
211
        }
212
213
        return sprintf('/%s/%s', self::VERSION, static::PATH);
214
    }
215
216
    /**
217
     * Execute a http request. If payload == null no body will be sent. Empty body ('{}') is supported by sending a
218
     * empty stdClass.
219
     *
220
     * @param string     $path    request path
221
     * @param string     $method  http method
222
     * @param mixed|null $payload request body
223
     * @param array      $headers request headers
224
     *
225
     * @throws Exceptions\ValidationException  if the API returns a 4xx http status code. Usually means invalid data was sent.
226
     * @throws Exceptions\UnautorizedException if the API returns a 401 http status code. Check API token and key.
227
     * @throws Exceptions\UnexpectedException  if the API returns a 500 http status code or something unexpected happens (ie.: Network error).
228
     *
229
     * @return stdClass
230
     */
231
    protected function httpRequest($path, $method, $payload = null, $headers = [])
232
    {
233
        $http_sess = $this->moip->getSession();
234
        $body = null;
235
        if ($payload !== null) {
236
            $body = json_encode($payload, JSON_UNESCAPED_SLASHES);
237
            if ($body) {    // if it's json serializable
238
                $headers['Content-Type'] = 'application/json';
239
            } else {
240
                $body = null;
241
            }
242
        }
243
244
        try {
245
            $http_response = $http_sess->request($path, $headers, $body, $method);
246
        } catch (Requests_Exception $e) {
247
            throw new Exceptions\UnexpectedException($e);
248
        }
249
250
        $code = $http_response->status_code;
251
        $response_body = $http_response->body;
252
        if ($code >= 200 && $code < 300) {
253
            return json_decode($response_body);
254
        } elseif ($code == 401) {
255
            throw new Exceptions\UnautorizedException();
256
        } elseif ($code >= 400 && $code <= 499) {
257
            $errors = Exceptions\Error::parseErrors($response_body);
258
259
            throw new Exceptions\ValidationException($code, $errors);
260
        }
261
262
        throw new Exceptions\UnexpectedException();
263
    }
264
265
    /**
266
     * Find by path.
267
     *
268
     * @param string $path    resource path
269
     * @param array  $headers request headers
270
     *
271
     * @return stdClass
272
     */
273
    public function getByPath($path, $headers = [])
274
    {
275
        $response = $this->httpRequest($path, Requests::GET, null, $headers);
276
277
        if (is_array($response)) {
278
            $response = (object) $response;
279
        }
280
281
        return $this->populate($response);
282
    }
283
284
    /**
285
     * Find by path with no populate method.
286
     *
287
     * @param string $path
288
     *
289
     * @return stdClass
290
     */
291
    public function getByPathNoPopulate($path)
292
    {
293
        return $this->httpRequest($path, Requests::GET);
294
    }
295
296
    /**
297
     * Create a new item in Moip.
298
     *
299
     * @param string $path
300
     *
301
     * @return stdClass
302
     */
303
    public function createResource($path)
304
    {
305
        $response = $this->httpRequest($path, Requests::POST, $this);
306
307
        return $this->populate($response);
308
    }
309
310
    /**
311
     * Update an item in Moip.
312
     *
313
     * @param string $path
314
     *
315
     * @return stdClass
316
     */
317
    public function updateByPath($path)
318
    {
319
        $response = $this->httpRequest($path, Requests::PUT, $this);
320
321
        return $this->populate($response);
322
    }
323
324
    /**
325
     * Delete a new item in Moip.
326
     *
327
     * @param $path
328
     *
329
     * @return mixed
330
     */
331
    public function deleteByPath($path)
332
    {
333
        return $this->httpRequest($path, Requests::DELETE);
334
    }
335
}
336