Completed
Push — master ( 8ee3b7...d2bdfa )
by Jonathan
04:57
created

AbstractReportingCloud::setVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 * ReportingCloud PHP Wrapper
5
 *
6
 * PHP wrapper for ReportingCloud Web API. Authored and supported by Text Control GmbH.
7
 *
8
 * @link      http://www.reporting.cloud to learn more about ReportingCloud
9
 * @link      https://github.com/TextControl/txtextcontrol-reportingcloud-php for the canonical source repository
10
 * @license   https://raw.githubusercontent.com/TextControl/txtextcontrol-reportingcloud-php/master/LICENSE.md
11
 * @copyright © 2016 Text Control GmbH
12
 */
13
namespace TxTextControl\ReportingCloud;
14
15
use GuzzleHttp\Client;
16
use GuzzleHttp\RequestOptions;
17
use TxTextControl\ReportingCloud\Exception\RuntimeException;
18
use TxTextControl\ReportingCloud\Filter\StaticFilter;
19
use TxTextControl\ReportingCloud\PropertyMap\AbstractPropertyMap as PropertyMap;
20
use TxTextControl\ReportingCloud\PropertyMap\MergeSettings as MergeSettingsPropertyMap;
21
use TxTextControl\ReportingCloud\Validator\StaticValidator;
22
23
/**
24
 * Abstract ReportingCloud
25
 *
26
 * @package TxTextControl\ReportingCloud
27
 * @author  Jonathan Maron (@JonathanMaron)
28
 */
29
abstract class AbstractReportingCloud
30
{
31
32
    /**
33
     * Default date/time format of backend is 'ISO 8601'
34
     *
35
     * Note, last letter is 'P' and not 'O':
36
     *
37
     * O - Difference to Greenwich time (GMT) in hours (e.g. +0200)
38
     * P - Difference to Greenwich time (GMT) with colon between hours and minutes (e.g. +02:00)
39
     *
40
     * Backend uses the 'P' variant
41
     *
42
     * @const DEFAULT_DATE_FORMAT
43
     */
44
    const DEFAULT_DATE_FORMAT = 'Y-m-d\TH:i:sP';
45
46
    /**
47
     * Default time zone of backend
48
     *
49
     * @const DEFAULT_TIME_ZONE
50
     */
51
    const DEFAULT_TIME_ZONE = 'UTC';
52
53
    /**
54
     * Default base URI of backend
55
     *
56
     * @const DEFAULT_BASE_URI
57
     */
58
    const DEFAULT_BASE_URI = 'https://api.reporting.cloud';
59
60
    /**
61
     * Default version string of backend
62
     *
63
     * @const DEFAULT_VERSION
64
     */
65
    const DEFAULT_VERSION = 'v1';
66
67
    /**
68
     * Default timeout of backend in seconds
69
     *
70
     * @const DEFAULT_TIMEOUT
71
     */
72
    const DEFAULT_TIMEOUT = 120; // seconds
73
74
    /**
75
     * Default test flag of backend
76
     *
77
     * @const DEFAULT_TEST
78
     */
79
    const DEFAULT_TEST = false;
80
81
    /**
82
     * Default debug flag of REST client
83
     *
84
     * @const DEFAULT_DEBUG
85
     */
86
    const DEFAULT_DEBUG = false;
87
88
    /**
89
     * Backend username
90
     *
91
     * @var string
92
     */
93
    protected $username;
94
95
    /**
96
     * Backend password
97
     *
98
     * @var string
99
     */
100
    protected $password;
101
102
    /**
103
     * When true, backend prints "TEST MODE" water mark into output document, and API call does not count against quota
104
     *
105
     * @var boolean
106
     */
107
    protected $test;
108
109
    /**
110
     * Backend base URI
111
     *
112
     * @var string
113
     */
114
    protected $baseUri;
115
116
    /**
117
     * Backend version string
118
     *
119
     * @var string
120
     */
121
    protected $version;
122
123
    /**
124
     * Backend timeout in seconds
125
     *
126
     * @var integer
127
     */
128
    protected $timeout;
129
130
    /**
131
     * REST client to backend
132
     *
133
     * @var Client
134
     */
135
    protected $client;
136
137
    /**
138
     * Debug flag of REST client
139
     *
140
     * @var boolean
141
     */
142
    protected $debug;
143
144
    /**
145
     * AbstractReportingCloud constructor
146
     *
147
     * @param array $options
148
     */
149 59
    public function __construct(array $options = [])
150
    {
151
        $methods = [
152 59
            'base_uri' => 'setBaseUri',
153 59
            'debug'    => 'setDebug',
154 59
            'password' => 'setPassword',
155 59
            'test'     => 'setTest',
156 59
            'timeout'  => 'setTimeout',
157 59
            'username' => 'setUsername',
158 59
            'version'  => 'setVersion',
159 59
        ];
160
161 59
        foreach ($methods as $key => $method) {
162 59
            if (array_key_exists($key, $options)) {
163 1
                $this->$method($options[$key]);
164 1
            }
165 59
        }
166
167 59
        return $this;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
168
    }
169
170
    /**
171
     * Setters and getters
172
     * =================================================================================================================
173
     */
174
175
    /**
176
     * Return the REST client of the backend web service
177
     *
178
     * @return \GuzzleHttp\Client
179
     */
180 18
    public function getClient()
181
    {
182 18
        if (null === $this->client) {
183
184 18
            $credentials   = sprintf('%s:%s', $this->getUsername(), $this->getPassword());
185 18
            $authorization = sprintf('Basic %s', base64_encode($credentials));
186
187 18
            $client = new Client([
188 18
                'base_uri'              => $this->getBaseUri(),
189 18
                RequestOptions::TIMEOUT => $this->getTimeout(),
190 18
                RequestOptions::DEBUG   => $this->getDebug(),
191 18
                RequestOptions::HEADERS => [
192 18
                    'Authorization' => $authorization,
193 18
                ],
194 18
            ]);
195
196 18
            $this->setClient($client);
197 18
        }
198
199 18
        return $this->client;
200
    }
201
202
    /**
203
     * Set the REST client of the backend web service
204
     *
205
     * @param Client $client REST client
206
     *
207
     * @return ReportingCloud
208
     */
209 18
    public function setClient(Client $client)
210
    {
211 18
        $this->client = $client;
212
213 18
        return $this;
214
    }
215
216
    /**
217
     * Return the base URI of the backend web service
218
     *
219
     * @return string
220
     */
221 22
    public function getBaseUri()
222
    {
223 22
        if (null === $this->baseUri) {
224 20
            $this->setBaseUri(self::DEFAULT_BASE_URI);
225 20
        }
226
227 22
        return $this->baseUri;
228
    }
229
230
    /**
231
     * Set the base URI of the backend web service
232
     *
233
     * @param string $baseUri Base URI
234
     *
235
     * @return ReportingCloud
236
     */
237 22
    public function setBaseUri($baseUri)
238
    {
239 22
        $this->baseUri = $baseUri;
240
241 22
        return $this;
242
    }
243
244
    /**
245
     * Get the timeout (in seconds) of the backend web service
246
     *
247
     * @return integer
248
     */
249 21
    public function getTimeout()
250
    {
251 21
        if (null === $this->timeout) {
252 19
            $this->setTimeout(self::DEFAULT_TIMEOUT);
253 19
        }
254
255 21
        return $this->timeout;
256
    }
257
258
    /**
259
     * Set the timeout (in seconds) of the backend web service
260
     *
261
     * @param integer $timeout Timeout
262
     *
263
     * @return ReportingCloud
264
     */
265 21
    public function setTimeout($timeout)
266
    {
267 21
        $this->timeout = (integer) $timeout;
268
269 21
        return $this;
270
    }
271
272
    /**
273
     * Return the username
274
     *
275
     * @return string
276
     */
277 21
    public function getUsername()
278
    {
279 21
        return $this->username;
280
    }
281
282
    /**
283
     * Set the username
284
     *
285
     * @param string $username Username
286
     *
287
     * @return ReportingCloud
288
     */
289 56
    public function setUsername($username)
290
    {
291 56
        $this->username = $username;
292
293 56
        return $this;
294
    }
295
296
    /**
297
     * Return the password
298
     *
299
     * @return string
300
     */
301 21
    public function getPassword()
302
    {
303 21
        return $this->password;
304
    }
305
306
    /**
307
     * Set the password
308
     *
309
     * @param string $password Password
310
     *
311
     * @return ReportingCloud
312
     */
313 56
    public function setPassword($password)
314
    {
315 56
        $this->password = $password;
316
317 56
        return $this;
318
    }
319
320
    /**
321
     * Return the test flag
322
     *
323
     * @return mixed
324
     */
325 19
    public function getTest()
326
    {
327 19
        if (null === $this->test) {
328 16
            $this->setTest(self::DEFAULT_TEST);
329 16
        }
330
331 19
        return $this->test;
332
    }
333
334
    /**
335
     * Set the test flag
336
     *
337
     * @param boolean $test Test flag
338
     *
339
     * @return ReportingCloud
340
     */
341 19
    public function setTest($test)
342
    {
343 19
        $this->test = (boolean) $test;
344
345 19
        return $this;
346
    }
347
348
    /**
349
     * Return the debug flag
350
     *
351
     * @return mixed
352
     */
353 21
    public function getDebug()
354
    {
355 21
        if (null === $this->debug) {
356 19
            $this->setDebug(self::DEFAULT_DEBUG);
357 19
        }
358
359 21
        return $this->debug;
360
    }
361
362
    /**
363
     * Set the debug flag
364
     *
365
     * @param boolean $debug Debug flag
366
     *
367
     * @return ReportingCloud
368
     */
369 21
    public function setDebug($debug)
370
    {
371 21
        $this->debug = (boolean) $debug;
372
373 21
        return $this;
374
    }
375
376
    /**
377
     * Get the version string of the backend web service
378
     *
379
     * @return string
380
     */
381 20
    public function getVersion()
382
    {
383 20
        if (null === $this->version) {
384 18
            $this->version = self::DEFAULT_VERSION;
385 18
        }
386
387 20
        return $this->version;
388
    }
389
390
    /**
391
     * Set the version string of the backend web service
392
     *
393
     * @param string $version Version string
394
     *
395
     * @return ReportingCloud
396
     */
397 2
    public function setVersion($version)
398
    {
399 2
        $this->version = $version;
400
401 2
        return $this;
402
    }
403
404
405
    /**
406
     * Utility methods
407
     * =================================================================================================================
408
     */
409
410
    /**
411
     * Request the URI with options
412
     *
413
     * @param string $method  HTTP method
414
     * @param string $uri     URI
415
     * @param array  $options Options
416
     *
417
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
418
     *
419
     * @throws RuntimeException
420
     */
421 17
    protected function request($method, $uri, $options)
422
    {
423 17
        $ret = null;
424
425 17
        $client = $this->getClient();
426
427
        try {
428
429 17
            if (getenv('TRAVIS')) {
430
                $options['curl'][CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_1;
431
            }
432
433 17
            if ($this->getTest()) {
434 1
                $options[RequestOptions::QUERY]['test'] = StaticFilter::execute($this->getTest(), 'BooleanToString');
435 1
            }
436
437 17
            $ret = $client->request($method, $uri, $options);
438
439 17
        } catch (\Exception $exception) {
440
441
            // \GuzzleHttp\Exception\ClientException
442
            // \GuzzleHttp\Exception\ServerException
443
444 1
            $message = (string)  $exception->getMessage();
445 1
            $code    = (integer) $exception->getCode();
446
447 1
            throw new RuntimeException($message, $code);
448
        }
449
450 16
        return $ret;
451
    }
452
453
    /**
454
     * Construct URI with version number
455
     *
456
     * @param string $uri URI
457
     *
458
     * @return string
459
     */
460 17
    protected function uri($uri)
461
    {
462 17
        return sprintf('/%s%s', $this->getVersion(), $uri);
463
    }
464
465
    /**
466
     * Using the passed propertyMap, recursively build array
467
     *
468
     * @param array       $array       Array
469
     * @param PropertyMap $propertyMap PropertyMap
470
     *
471
     * @return array
472
     */
473 5
    protected function buildPropertyMapArray($array, PropertyMap $propertyMap)
474
    {
475 5
        $ret = [];
476
477 5
        foreach ($array as $key => $value) {
478 5
            $map = $propertyMap->getMap();
479 5
            if (isset($map[$key])) {
480 5
                $key = $map[$key];
481 5
            }
482 5
            if (is_array($value)) {
483 2
                $value = $this->buildPropertyMapArray($value, $propertyMap);
484 2
            }
485 5
            $ret[$key] = $value;
486 5
        }
487
488 5
        return $ret;
489
    }
490
491
    /**
492
     * Using passed mergeSettings array, build array for backend
493
     *
494
     * @param array $array MergeSettings array
495
     *
496
     * @return array
497
     */
498 8
    protected function buildMergeSettingsArray($array)
499
    {
500 8
        $ret = [];
501
502 8
        $propertyMap = new MergeSettingsPropertyMap();
503
504 8
        foreach ($propertyMap->getMap() as $property => $key) {
505 8
            if (isset($array[$key])) {
506 8
                $value = $array[$key];
507 8
                if ('remove_' == substr($key, 0, 7)) {
508 6
                    StaticValidator::execute($value, 'TypeBoolean');
509 4
                }
510 8
                if ('_date' == substr($key, -5)) {
511 8
                    StaticValidator::execute($value, 'Timestamp');
512 6
                    $value = StaticFilter::execute($value, 'TimestampToDateTime');
513 6
                }
514 8
                $ret[$property] = $value;
515 8
            }
516 8
        }
517
518 4
        return $ret;
519
    }
520
521
    /**
522
     * Using passed findAndReplaceData associative array (key-value), build array for backend (list of string arrays)
523
     *
524
     * @param array $array FindAndReplaceData array
525
     *
526
     * @return array
527
     */
528 4
    protected function buildFindAndReplaceDataArray($array)
529
    {
530 4
        $ret = [];
531
532 4
        foreach ($array as $search => $replace) {
533 4
            array_push($ret, [$search, $replace]);
534 4
        }
535
536 4
        return $ret;
537
    }
538
539
}