File size: 7,801 Bytes
52d9fb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
<?php

/**
 * This file is part of the TextmagicRestClient package.
 *
 * Copyright (c) 2015 TextMagic Ltd. All rights reserved.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Notify\Textmagic\Services;

use App\Notify\Textmagic\Services\RestException;
use App\Notify\Textmagic\Services\HttpClient\HttpCurl;
use App\Notify\Textmagic\Services\HttpClient\HttpStream;

/**
 * @author Denis <denis@textmagic.biz>
 */

spl_autoload_register(function ($class) {
    $prefix = __NAMESPACE__ . '\\';

    // process only classes with same namespace
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relativeClass = substr($class, $len);
    $file = str_replace('\\', '/',  __DIR__ . DIRECTORY_SEPARATOR . $relativeClass) . '.php';

    // if the file exists, require it
    if (file_exists($file)) {
        require_once($file);
    }
});

class TextmagicRestClient {

    /**
     * Http client instance
     * @var object
     */
    protected $http;

    /**
     * Used version
     * @var string
     */
    protected $version;

    /**
     * Allowed versions
     * @var array
     */
    protected $versions = array('v2');

    /**
     * User agent
     * @var string
     */
    protected $userAgent = 'textmagic-rest-php';

    /**
     * Previous request time for prevent limit exceed error
     * @var integer
     */
    protected $previousRequestTime = 0;

    /**
     * Get the API URI for this client.
     *
     * @return string
     */
    private function getApiUri() {
        return 'https://rest.textmagic.com/api/' . $this->version;
    }

    /**
     * Full user agent with the current PHP Version.
     *
     * @param string $userAgent Application user agent
     * @return string
     */
    private function getFullUserAgent() {
        return $this->userAgent . '/'  . $this->version . ' (php ' . phpversion() . ')';
    }

    /**
     * TextmagicRestClient constructor
     *
     * @param string $username API username
     * @param string $token API token
     * @param string $version API version
     * @param object $http Custom http object
     */
    public function __construct(
        $username,
        $token,
        $version = null,
        $http = null
    ) {
        $this->version = in_array($version, $this->versions) ? $version : end($this->versions);
        $this->http = $http;
        if (null === $this->http) {
            if (!in_array('openssl', get_loaded_extensions())) {
                throw new \ErrorException('The OpenSSL extension is required but not currently enabled. For more information, see http://php.net/manual/en/book.openssl.php');
            }
            if (in_array('curl', get_loaded_extensions())) {
                $this->http = new HttpCurl(
                    $this->getApiUri(),
                    array(
                        'curl_options' => array(
                            CURLOPT_USERAGENT => $this->getFullUserAgent(),
                            CURLOPT_HTTPHEADER => array(
                                'Accept-Charset: utf-8',
                                'Accept-Language: en-US'
                            )
                        )
                    )
                );
            } else {
                $this->http = new HttpStream(
                    $this->getApiUri(),
                    array(
                        'http_options' => array(
                            'http' => array(
                                'user_agent' => $this->getFullUserAgent(),
                                'header' => array(
                                    'Accept-Charset: utf-8',
                                    'Accept-Language: en-US'
                                )
                            ),
                            'ssl' => array(
                                'verify_peer' => true,
                                'verify_depth' => 5
                            )
                        )
                    )
                );
            }
        }

        $this->http->authenticate($username, $token);
    }

    /**
     * Overload method for access to models
     *
     * @param string $name Model name
     * @return object
     */
    public function __get($name) {
        $name = strtolower($name);
        if (!isset($this->$name)) {
            $className = __NAMESPACE__ . '\\Models\\' . ucfirst($name);
            $this->$name = new $className($this);
        }

        return $this->$name;
    }

    /**
     * POST to resource at the specified path
     *
     * @param string $path Path to resource
     * @param array  $params Query string parameters
     * @return array
     */
    public function createData($path, $params = array()) {
        return $this->makeRequest(
            'POST',
            $path,
            array('Content-Type' => 'application/x-www-form-urlencoded'),
            http_build_query($params)
        );
    }

    /**
     * DELETE resource at the specified path
     *
     * @param string $path Path to resource
     * @param array  $params Query string parameters
     * @return array
     */
    public function deleteData($path, $params = array()) {
        return $this->makeRequest(
            'DELETE',
            $path,
            array('Content-Type' => 'application/x-www-form-urlencoded'),
            http_build_query($params)
        );
    }

    /**
     * GET resource at the specified path
     *
     * @param string $path Path to resource
     * @param array  $params Query string parameters
     * @return array
     */
    public function retrieveData($path, $params = array()) {
        return $this->makeRequest(
            'GET',
            $path,
            array(),
            http_build_query($params)
        );
    }

    /**
     * PUT resource at the specified path
     *
     * @param string $path Path to resource
     * @param array  $params Query string parameters
     * @return array
     */
    public function updateData($path, $params = array()) {
        return $this->makeRequest(
            'PUT',
            $path,
            array('Content-Type' => 'application/x-www-form-urlencoded'),
            http_build_query($params)
        );
    }

    /**
     * Method for implementing request retry logic
     *
     * @param string $method HTTP request method
     * @param string $path Path to resource
     * @return array
     */
    private function makeRequest($method, $path, $headers = array(), $params = '') {
        if (time() - $this->previousRequestTime < 1) {
            sleep(1);
        }
        $response = call_user_func_array(array($this->http, $method), array($path, $headers, $params));
        $this->previousRequestTime = time();
        list($status, $headers, $body) = $response;
        return $this->processResponse($response);
    }

    /**
     * Convert the JSON encoded response into a PHP object.
     *
     * @param array $response JSON encoded server response
     * @return array
     */
    private function processResponse($response) {
        list($status, $headers, $body) = $response;
        // if empty response just return boolean
        if ($status == 204) {
            return true;
        }

        $decoded = json_decode($body, true);
        if ($decoded === null) {
            throw new RestException('Could not decode response body as JSON.', $status);
        }
        if (200 <= $status && $status < 300) {
            return $decoded;
        }

        throw new RestException(
            $decoded['message'],
            $decoded['code'],
            (isset($decoded['errors']) ? $decoded['errors'] : null)
        );
    }
}