Passed
Push — master ( 4cb6ef...f6d694 )
by Jonathan
03:18
created

AbstractReportingCloud::buildMergeSettingsArray()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6.0045

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 25
ccs 19
cts 20
cp 0.95
rs 8.439
cc 6
eloc 15
nc 10
nop 1
crap 6.0045
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 © 2017 Text Control GmbH
12
 */
13
14
namespace TxTextControl\ReportingCloud;
15
16
use GuzzleHttp\Client;
17
use GuzzleHttp\RequestOptions;
18
use TxTextControl\ReportingCloud\Exception\RuntimeException;
19
use TxTextControl\ReportingCloud\Filter\StaticFilter;
20
use TxTextControl\ReportingCloud\PropertyMap\AbstractPropertyMap as PropertyMap;
21
use TxTextControl\ReportingCloud\PropertyMap\MergeSettings as MergeSettingsPropertyMap;
22
use TxTextControl\ReportingCloud\Validator\StaticValidator;
23
24
/**
25
 * Abstract ReportingCloud
26
 *
27
 * @package TxTextControl\ReportingCloud
28
 * @author  Jonathan Maron (@JonathanMaron)
29
 */
30
abstract class AbstractReportingCloud
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;
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 62
    public function __construct(array $options = [])
150
    {
151
        $methods = [
152 62
            'base_uri' => 'setBaseUri',
153 62
            'debug'    => 'setDebug',
154 62
            'password' => 'setPassword',
155 62
            'test'     => 'setTest',
156 62
            'timeout'  => 'setTimeout',
157 62
            'username' => 'setUsername',
158 62
            'version'  => 'setVersion',
159 62
        ];
160
161 62
        foreach ($methods as $key => $method) {
162 62
            if (array_key_exists($key, $options)) {
163 1
                $this->$method($options[$key]);
164 1
            }
165 62
        }
166 62
    }
167
168
    /**
169
     * Setters and getters
170
     * =================================================================================================================
171
     */
172
173
    /**
174
     * Request the URI with options
175
     *
176
     * @param string $method HTTP method
177
     * @param string $uri URI
178
     * @param array $options Options
179
     *
180
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
181
     *
182
     * @throws RuntimeException
183
     */
184 19
    protected function request($method, $uri, $options)
185
    {
186 19
        $ret = null;
187
188 19
        $client = $this->getClient();
189
190
        try {
191
192 19
            if ($this->getTest()) {
193
                $options[RequestOptions::QUERY]['test'] = StaticFilter::execute($this->getTest(), 'BooleanToString');
194
            }
195
196 19
            $ret = $client->request($method, $uri, $options);
197 19
        } catch (\Exception $exception) {
198
199
            // \GuzzleHttp\Exception\ClientException
200
            // \GuzzleHttp\Exception\ServerException
201
202 1
            $message = (string) $exception->getMessage();
203 1
            $code    = (integer) $exception->getCode();
204
205 1
            throw new RuntimeException($message, $code);
206
        }
207
208 18
        return $ret;
209
    }
210
211
    /**
212
     * Return the REST client of the backend web service
213
     *
214
     * @return \GuzzleHttp\Client
215
     */
216 20
    public function getClient()
217
    {
218 20
        if (null === $this->client) {
219
220 20
            $credentials   = sprintf('%s:%s', $this->getUsername(), $this->getPassword());
221 20
            $authorization = sprintf('Basic %s', base64_encode($credentials));
222
223 20
            $client = new Client([
224 20
                'base_uri'              => $this->getBaseUri(),
225 20
                RequestOptions::TIMEOUT => $this->getTimeout(),
226 20
                RequestOptions::DEBUG   => $this->getDebug(),
227 20
                RequestOptions::HEADERS => [
228 20
                    'Authorization' => $authorization,
229 20
                ],
230 20
            ]);
231
232 20
            $this->setClient($client);
233 20
        }
234
235 20
        return $this->client;
236
    }
237
238
    /**
239
     * Set the REST client of the backend web service
240
     *
241
     * @param Client $client REST client
242
     *
243
     * @return ReportingCloud
244
     */
245 20
    public function setClient(Client $client)
246
    {
247 20
        $this->client = $client;
248
249 20
        return $this;
250
    }
251
252
    /**
253
     * Return the username
254
     *
255
     * @return string
256
     */
257 23
    public function getUsername()
258
    {
259 23
        return $this->username;
260
    }
261
262
    /**
263
     * Set the username
264
     *
265
     * @param string $username Username
266
     *
267
     * @return ReportingCloud
268
     */
269 59
    public function setUsername($username)
270
    {
271 59
        $this->username = $username;
272
273 59
        return $this;
274
    }
275
276
    /**
277
     * Return the password
278
     *
279
     * @return string
280
     */
281 23
    public function getPassword()
282
    {
283 23
        return $this->password;
284
    }
285
286
    /**
287
     * Set the password
288
     *
289
     * @param string $password Password
290
     *
291
     * @return ReportingCloud
292
     */
293 59
    public function setPassword($password)
294
    {
295 59
        $this->password = $password;
296
297 59
        return $this;
298
    }
299
300
    /**
301
     * Return the base URI of the backend web service
302
     *
303
     * @return string
304
     */
305 24
    public function getBaseUri()
306
    {
307 24
        if (null === $this->baseUri) {
308 22
            $this->setBaseUri(self::DEFAULT_BASE_URI);
309 22
        }
310
311 24
        return $this->baseUri;
312
    }
313
314
    /**
315
     * Set the base URI of the backend web service
316
     *
317
     * @param string $baseUri Base URI
318
     *
319
     * @return ReportingCloud
320
     */
321 24
    public function setBaseUri($baseUri)
322
    {
323 24
        $this->baseUri = $baseUri;
324
325 24
        return $this;
326
    }
327
328
    /**
329
     * Get the timeout (in seconds) of the backend web service
330
     *
331
     * @return integer
332
     */
333 23
    public function getTimeout()
334
    {
335 23
        if (null === $this->timeout) {
336 21
            $this->setTimeout(self::DEFAULT_TIMEOUT);
337 21
        }
338
339 23
        return $this->timeout;
340
    }
341
342
    /**
343
     * Set the timeout (in seconds) of the backend web service
344
     *
345
     * @param integer $timeout Timeout
346
     *
347
     * @return ReportingCloud
348
     */
349 23
    public function setTimeout($timeout)
350
    {
351 23
        $this->timeout = (integer) $timeout;
352
353 23
        return $this;
354
    }
355
356
    /**
357
     * Return the debug flag
358
     *
359
     * @return mixed
360
     */
361 23
    public function getDebug()
362
    {
363 23
        if (null === $this->debug) {
364 21
            $this->setDebug(self::DEFAULT_DEBUG);
365 21
        }
366
367 23
        return $this->debug;
368
    }
369
370
    /**
371
     * Set the debug flag
372
     *
373
     * @param boolean $debug Debug flag
374
     *
375
     * @return ReportingCloud
376
     */
377 23
    public function setDebug($debug)
378
    {
379 23
        $this->debug = (boolean) $debug;
380
381 23
        return $this;
382
    }
383
384
    /**
385
     * Return the test flag
386
     *
387
     * @return mixed
388
     */
389 21
    public function getTest()
390
    {
391 21
        if (null === $this->test) {
392 19
            $this->setTest(self::DEFAULT_TEST);
393 19
        }
394
395 21
        return $this->test;
396
    }
397
398
    /**
399
     * Set the test flag
400
     *
401
     * @param boolean $test Test flag
402
     *
403
     * @return ReportingCloud
404
     */
405 21
    public function setTest($test)
406
    {
407 21
        $this->test = (boolean) $test;
408
409 21
        return $this;
410
    }
411
412
    /**
413
     * Construct URI with version number
414
     *
415
     * @param string $uri URI
416
     *
417
     * @return string
418
     */
419 19
    protected function uri($uri)
420
    {
421 19
        return sprintf('/%s%s', $this->getVersion(), $uri);
422
    }
423
424
425
    /**
426
     * Utility methods
427
     * =================================================================================================================
428
     */
429
430
    /**
431
     * Get the version string of the backend web service
432
     *
433
     * @return string
434
     */
435 22
    public function getVersion()
436
    {
437 22
        if (null === $this->version) {
438 20
            $this->version = self::DEFAULT_VERSION;
439 20
        }
440
441 22
        return $this->version;
442
    }
443
444
    /**
445
     * Set the version string of the backend web service
446
     *
447
     * @param string $version Version string
448
     *
449
     * @return ReportingCloud
450
     */
451 2
    public function setVersion($version)
452
    {
453 2
        $this->version = $version;
454
455 2
        return $this;
456
    }
457
458
    /**
459
     * Using the passed propertyMap, recursively build array
460
     *
461
     * @param array $array Array
462
     * @param PropertyMap $propertyMap PropertyMap
463
     *
464
     * @return array
465
     */
466 4
    protected function buildPropertyMapArray(array $array, PropertyMap $propertyMap)
467
    {
468 4
        $ret = [];
469
470 4
        foreach ($array as $key => $value) {
471 4
            $map = $propertyMap->getMap();
472 4
            if (isset($map[$key])) {
473 4
                $key = $map[$key];
474 4
            }
475 4
            if (is_array($value)) {
476 3
                $value = $this->buildPropertyMapArray($value, $propertyMap);
477 3
            }
478 4
            $ret[$key] = $value;
479 4
        }
480
481 4
        return $ret;
482
    }
483
484
    /**
485
     * Using passed mergeSettings array, build array for backend
486
     *
487
     * @param array $array MergeSettings array
488
     *
489
     * @return array
490
     */
491 9
    protected function buildMergeSettingsArray(array $array)
492
    {
493 9
        $ret = [];
494
495 9
        $propertyMap = new MergeSettingsPropertyMap();
496
497 9
        foreach ($propertyMap->getMap() as $property => $key) {
498 9
            if (isset($array[$key])) {
499 9
                $value = $array[$key];
500 9
                if ('culture' == $key) {
501 1
                    StaticValidator::execute($value, 'Culture');
502
                }
503 9
                if ('remove_' == substr($key, 0, 7)) {
504 6
                    StaticValidator::execute($value, 'TypeBoolean');
505 4
                }
506 9
                if ('_date' == substr($key, -5)) {
507 9
                    StaticValidator::execute($value, 'Timestamp');
508 7
                    $value = StaticFilter::execute($value, 'TimestampToDateTime');
509 7
                }
510 9
                $ret[$property] = $value;
511 9
            }
512 9
        }
513
514 4
        return $ret;
515
    }
516
517
    /**
518
     * Using passed findAndReplaceData associative array (key-value), build array for backend (list of string arrays)
519
     *
520
     * @param array $array FindAndReplaceData array
521
     *
522
     * @return array
523
     */
524 4
    protected function buildFindAndReplaceDataArray(array $array)
525
    {
526 4
        $ret = [];
527
528 4
        foreach ($array as $search => $replace) {
529 4
            array_push($ret, [
530 4
                $search,
531 4
                $replace,
532 4
            ]);
533 4
        }
534
535 4
        return $ret;
536
    }
537
}