Completed
Push — master ( df95c6...f74e51 )
by
unknown
13s
created

MoipResource::generateListPath()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 20
nop 3
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
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
     * @var \Moip\Moip
29
     */
30
    protected $moip;
31
32
    /**
33
     * @var \stdClass
34
     */
35
    protected $data;
36
37
    /**
38
     * Initialize a new instance.
39
     */
40
    abstract protected function initialize();
41
42
    /**
43
     * Mount information of a determined object.
44
     *
45
     * @param \stdClass $response
46
     *
47
     * @return mixed
48
     */
49
    abstract protected function populate(stdClass $response);
50
51
    /**
52
     * Create a new instance.
53
     *
54
     * @param \Moip\Moip $moip
55
     */
56
    public function __construct(Moip $moip)
57
    {
58
        $this->moip = $moip;
59
        $this->data = new stdClass();
60
        $this->initialize();
61
    }
62
63
    /**
64
     * Get a key of an object if it exists.
65
     *
66
     * @param string         $key
67
     * @param \stdClass|null $data
68
     *
69
     * @return mixed
70
     */
71
    protected function getIfSet($key, stdClass $data = null)
72
    {
73
        if (empty($data)) {
74
            $data = $this->data;
75
        }
76
77
        if (isset($data->$key)) {
78
            return $data->$key;
79
        }
80
    }
81
82
    /**
83
     * @return \Moip\Helper\Links
84
     */
85
    public function getLinks()
86
    {
87
        $links = $this->getIfSet('_links');
88
89
        if ($links !== null) {
90
            return new Links($links);
91
        }
92
    }
93
94
    /**
95
     * @param $key
96
     * @param $fmt
97
     * @param stdClass|null $data
98
     *
99
     * @return bool|\DateTime|null
100
     */
101
    protected function getIfSetDateFmt($key, $fmt, stdClass $data = null)
102
    {
103
        $val = $this->getIfSet($key, $data);
104
        if (!empty($val)) {
105
            $dt = \DateTime::createFromFormat($fmt, $val);
106
107
            return $dt ? $dt : null;
108
        }
109
    }
110
111
    /**
112
     * Get a key, representing a date (Y-m-d), of an object if it exists.
113
     *
114
     * @param string        $key
115
     * @param stdClass|null $data
116
     *
117
     * @return \DateTime|null
118
     */
119
    protected function getIfSetDate($key, stdClass $data = null)
120
    {
121
        return $this->getIfSetDateFmt($key, 'Y-m-d', $data);
122
    }
123
124
    /**
125
     * Get a key representing a datetime (\Datetime::ATOM), of an object if it exists.
126
     *
127
     * @param string        $key
128
     * @param stdClass|null $data
129
     *
130
     * @return \DateTime|null
131
     */
132
    protected function getIfSetDateTime($key, stdClass $data = null)
133
    {
134
        $rawDateTime = $this->getIfSet($key, $data);
135
136
        if (!empty($rawDateTime)) {
137
            $dateTime = new \DateTime($rawDateTime);
138
        }
139
140
        return $dateTime;
0 ignored issues
show
Bug introduced by
The variable $dateTime does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
141
    }
142
143
    /**
144
     * Specify data which should be serialized to JSON.
145
     *
146
     * @return \stdClass
147
     */
148
    public function jsonSerialize()
149
    {
150
        return $this->data;
151
    }
152
153
    /**
154
     * Generate URL to request.
155
     *
156
     * @param $action
157
     * @param $id
158
     *
159
     * @return string
160
     */
161
    public function generatePath($action, $id = null)
162
    {
163
        if (!is_null($id)) {
164
            return sprintf('%s/%s/%s/%s', self::VERSION, static::PATH, $action, $id);
165
        }
166
167
        return sprintf('%s/%s/%s', self::VERSION, static::PATH, $action);
168
    }
169
170
    /**
171
     * Generate URL to request a get list.
172
     *
173
     * @param Pagination $pagination
174
     * @param Filters    $filters
175
     * @param string     $qParam     Query a specific value.
176
     *
177
     * @return string
178
     */
179
    public function generateListPath(Pagination $pagination = null, Filters $filters = null, $qParam = '')
180
    {
181
        $queryParams = [];
182
183
        if (!is_null($pagination)) {
184
            if ($pagination->getLimit() != 0) {
185
                $queryParams['limit'] = $pagination->getLimit();
186
            }
187
188
            if ($pagination->getOffset() >= 0) {
189
                $queryParams['offset'] = $pagination->getOffset();
190
            }
191
        }
192
193
        if (!is_null($filters)) {
194
            $queryParams['filters'] = $filters->__toString();
195
        }
196
197
        if (!empty($qParam)) {
198
            $queryParams['q'] = $qParam;
199
        }
200
201
        return sprintf('/%s/%s?%s', self::VERSION, static::PATH, http_build_query($queryParams));
202
    }
203
204
    /**
205
     * Execute a http request. If payload == null no body will be sent. Empty body ('{}') is supported by sending a
206
     * empty stdClass.
207
     *
208
     * @param string     $path
209
     * @param string     $method
210
     * @param mixed|null $payload
211
     *
212
     * @throws Exceptions\ValidationException  if the API returns a 4xx http status code. Usually means invalid data was sent.
213
     * @throws Exceptions\UnautorizedException if the API returns a 401 http status code. Check API token and key.
214
     * @throws Exceptions\UnexpectedException  if the API returns a 500 http status code or something unexpected happens (ie.: Network error).
215
     *
216
     * @return stdClass
217
     */
218
    protected function httpRequest($path, $method, $payload = null)
219
    {
220
        $http_sess = $this->moip->getSession();
221
        $headers = [];
222
        $body = null;
223
        if ($payload !== null) {
224
            $body = json_encode($payload, JSON_UNESCAPED_SLASHES);
225
            if ($body) {// if it's json serializable
226
                $headers['Content-Type'] = 'application/json';
227
            } else {
228
                $body = null;
229
            }
230
        }
231
232
        try {
233
            $http_response = $http_sess->request($path, $headers, $body, $method);
234
        } catch (Requests_Exception $e) {
235
            throw new Exceptions\UnexpectedException($e);
236
        }
237
238
        $code = $http_response->status_code;
239
        $response_body = $http_response->body;
240
        if ($code >= 200 && $code < 300) {
241
            return json_decode($response_body);
242
        } elseif ($code == 401) {
243
            throw new Exceptions\UnautorizedException();
244
        } elseif ($code >= 400 && $code <= 499) {
245
            $errors = Exceptions\Error::parseErrors($response_body);
246
            throw new Exceptions\ValidationException($code, $errors);
247
        }
248
        throw new Exceptions\UnexpectedException();
249
    }
250
251
    /**
252
     * Find by path.
253
     *
254
     * @param string $path
255
     *
256
     * @return stdClass
257
     */
258
    public function getByPath($path)
259
    {
260
        $response = $this->httpRequest($path, Requests::GET);
261
262
        return $this->populate($response);
263
    }
264
265
    /**
266
     * Create a new item in Moip.
267
     *
268
     * @param string $path
269
     *
270
     * @return stdClass
271
     */
272
    public function createResource($path)
273
    {
274
        $response = $this->httpRequest($path, Requests::POST, $this);
275
276
        return $this->populate($response);
277
    }
278
279
    /**
280
     * Delete a new item in Moip.
281
     *
282
     * @param $path
283
     *
284
     * @return mixed
285
     */
286
    public function deleteByPath($path)
287
    {
288
        return $this->httpRequest($path, Requests::DELETE);
289
    }
290
}
291