Completed
Push — master ( e78a07...82539f )
by Jean C.
02:16
created

MoipResource::getIfSet()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 4 Features 1
Metric Value
c 7
b 4
f 1
dl 0
loc 12
rs 9.4285
cc 3
eloc 6
nc 4
nop 2
1
<?php
2
3
namespace Moip\Resource;
4
5
use JsonSerializable;
6
use Moip\Exceptions;
7
use Moip\Http\HTTPConnection;
8
use Moip\Http\HTTPRequest;
9
use Moip\Moip;
10
use stdClass;
11
12
abstract class MoipResource implements JsonSerializable
13
{
14
    /**
15
     * Version of API.
16
     *
17
     * @const string
18
     */
19
    const VERSION = 'v2';
20
21
    /**
22
     * @var \Moip\Moip
23
     */
24
    protected $moip;
25
26
    /**
27
     * @var \stdClass
28
     */
29
    protected $data;
30
31
    /**
32
     * Initialize a new instance.
33
     */
34
    abstract protected function initialize();
35
36
    /**
37
     * Mount information of a determined object.
38
     *
39
     * @param \stdClass $response
40
     *
41
     * @return mixed
42
     */
43
    abstract protected function populate(stdClass $response);
44
45
    /**
46
     * Create a new instance.
47
     *
48
     * @param \Moip\Moip $moip
49
     */
50
    public function __construct(Moip $moip)
51
    {
52
        $this->moip = $moip;
53
        $this->data = new stdClass();
54
        $this->initialize();
55
    }
56
57
    /**
58
     * Create a new connecttion.
59
     *
60
     * @return \Moip\Http\HTTPConnection
61
     */
62
    protected function createConnection()
63
    {
64
        return $this->moip->createConnection(new HTTPConnection());
65
    }
66
67
    /**
68
     * Get a key of an object if it exists.
69
     *
70
     * @param string         $key
71
     * @param \stdClass|null $data
72
     *
73
     * @return mixed
74
     */
75
    protected function getIfSet($key, stdClass $data = null)
76
    {
77
        if (empty($data)) {
78
            $data = $this->data;
79
        }
80
81
        if (isset($data->$key)) {
82
            return $data->$key;
83
        }
84
85
        return;
86
    }
87
88
    protected function getIfSetDateFmt($key, $fmt, stdClass $data = null)
89
    {
90
        $val = $this->getIfSet($key, $data);
91
        if (!empty($val)) {
92
            $dt = \DateTime::createFromFormat($fmt, $val);
93
94
            return $dt ? $dt : null;
95
        }
96
97
        return;
98
    }
99
100
    /**
101
     * Get a key, representing a date (Y-m-d), of an object if it exists.
102
     *
103
     * @param string        $key
104
     * @param stdClass|null $data
105
     *
106
     * @return \DateTime|null
107
     */
108
    protected function getIfSetDate($key, stdClass $data = null)
109
    {
110
        return $this->getIfSetDateFmt($key, 'Y-m-d', $data);
111
    }
112
113
    /**
114
     * Get a key representing a datetime (\Datetime::ATOM), of an object if it exists.
115
     *
116
     * @param string        $key
117
     * @param stdClass|null $data
118
     *
119
     * @return \DateTime|null
120
     */
121
    protected function getIfSetDateTime($key, stdClass $data = null)
122
    {
123
        return $this->getIfSetDateFmt($key, \DateTime::ATOM, $data);
124
    }
125
126
    /**
127
     * Specify data which should be serialized to JSON.
128
     *
129
     * @return \stdClass
130
     */
131
    public function jsonSerialize()
132
    {
133
        return $this->data;
134
    }
135
136
    /**
137
     * Execute a http request. If payload == null no body will be sent. Empty body ('{}') is supported by sending a
138
     * empty stdClass.
139
     *
140
     * @param            $path
141
     * @param            $method
142
     * @param mixed|null $payload
143
     *
144
     * @throws Exceptions\ValidationException  if the API returns a 4xx http status code. Usually means invalid data was sent.
145
     * @throws Exceptions\UnautorizedException if the API returns a 401 http status code. Check API token and key
146
     * @throws Exceptions\UnexpectedException  if the API returns a 500 http status code, this is not suppose to happen. Please report the error to moip
147
     *
148
     * @return stdClass
149
     */
150
    protected function httpRequest($path, $method, $payload = null)
151
    {
152
        $httpConnection = $this->createConnection();
153
        $httpConnection->addHeader('Content-Type', 'application/json');
154
        if ($payload !== null) {
155
            // if it's json serializable
156
            $body = json_encode($payload, JSON_UNESCAPED_SLASHES);
157
            if ($body) {
158
                $httpConnection->addHeader('Content-Length', strlen($body));
159
                $httpConnection->setRequestBody($body);
160
            }
161
        }
162
163
        /*
164
         * @var \Moip\Http\HTTPResponse
165
         */
166
        $http_response = $httpConnection->execute($path, $method);
167
168
        $code = $http_response->getStatusCode();
169
170
        $response_body = $http_response->getContent();
171
        if ($code >= 200 && $code < 299) {
172
            return json_decode($response_body);
173
        } elseif ($code == 401) {
174
            throw new Exceptions\UnautorizedException();
175
        } elseif ($code >= 400 && $code <= 499) {
176
            $errors = Exceptions\Error::parseErrors($response_body);
177
            throw new Exceptions\ValidationException($code, $http_response->getStatusMessage(), $errors);
178
        }
179
        throw new Exceptions\UnexpectedException();
180
    }
181
182
    /**
183
     * Find by path.
184
     *
185
     * @param string $path
186
     *
187
     * @return stdClass
188
     */
189
    public function getByPath($path)
190
    {
191
        $response = $this->httpRequest($path, HTTPRequest::GET);
192
193
        return $this->populate($response);
194
    }
195
196
    /**
197
     * Create a new item in Moip.
198
     *
199
     * @param string $path
200
     *
201
     * @return stdClass
202
     */
203
    public function createResource($path)
204
    {
205
        $response = $this->httpRequest($path, HTTPRequest::POST, $this);
206
207
        return $this->populate($response);
208
    }
209
}
210