Completed
Push — master ( 2ac606...daf487 )
by Jonathan
08:49
created

ReportingCloud::getTemplateInfo()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 20
ccs 11
cts 11
cp 1
rs 9.4285
cc 3
eloc 10
nc 2
nop 1
crap 3
1
<?php
2
3
/**
4
 * ReportingCloud PHP Wrapper
5
 *
6
 * Official wrapper (authored by Text Control GmbH, publisher of ReportingCloud) to access ReportingCloud in PHP.
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\Psr7\Response;
16
use GuzzleHttp\RequestOptions;
17
18
use TxTextControl\ReportingCloud\Exception\InvalidArgumentException;
19
20
use TxTextControl\ReportingCloud\Filter\DateTimeToTimestamp  as DateTimeToTimestampFilter;
21
use TxTextControl\ReportingCloud\Filter\TimestampToDateTime  as TimestampToDateTimeFilter;
22
23
use TxTextControl\ReportingCloud\PropertyMap\MergeSettings   as MergeSettingsPropertyMap;
24
use TxTextControl\ReportingCloud\PropertyMap\AccountSettings as AccountSettingsPropertyMap;
25
use TxTextControl\ReportingCloud\PropertyMap\TemplateInfo    as TemplateInfoPropertyMap;
26
use TxTextControl\ReportingCloud\PropertyMap\TemplateList    as TemplateListPropertyMap;
27
28
use TxTextControl\ReportingCloud\Validator\StaticValidator;
29
30
/**
31
 * ReportingCloud
32
 *
33
 * @package TxTextControl\ReportingCloud
34
 * @author  Jonathan Maron (@JonathanMaron)
35
 */
36
class ReportingCloud extends AbstractReportingCloud
37
{
38
39
    /**
40
     * GET methods
41
     * =================================================================================================================
42
     */
43
44
    /**
45
     * Return an array of merge blocks and merge fields in a template file in template storage.
46
     *
47
     * @param string  $templateName Template name
48
     *
49
     * @throws InvalidArgumentException
50
     *
51
     * @return array|null
52
     */
53 1
    public function getTemplateInfo($templateName)
54
    {
55 1
        $ret = null;
56
57 1
        $propertyMap = new TemplateInfoPropertyMap();
58
59 1
        StaticValidator::execute($templateName, 'TemplateName');
60
61
        $query = [
62 1
            'templateName' => $templateName,
63 1
        ];
64
65 1
        $records = $this->get('/templates/info', $query);
66
67 1
        if (is_array($records) && count($records) > 0) {
68 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
69 1
        }
70
71 1
        return $ret;
72
    }
73
74
    /**
75
     * Return an array of binary data.
76
     * Each record in the array is the binary data of a thumbnail image
77
     *
78
     * @param string  $templateName Template name
79
     * @param integer $zoomFactor   Zoom factor
80
     * @param integer $fromPage     From page
81
     * @param integer $toPage       To page
82
     * @param string  $imageFormat  Image format
83
     *
84
     * @throws InvalidArgumentException
85
     *
86
     * @return array|null
87
     */
88 6
    public function getTemplateThumbnails($templateName, $zoomFactor, $fromPage, $toPage, $imageFormat)
89
    {
90 6
        $ret = null;
91
92 6
        StaticValidator::execute($templateName, 'TemplateName');
93 5
        StaticValidator::execute($zoomFactor  , 'ZoomFactor');
94 4
        StaticValidator::execute($fromPage    , 'Page');
95 3
        StaticValidator::execute($toPage      , 'Page');
96 2
        StaticValidator::execute($imageFormat , 'ImageFormat');
97
98
        $query = [
99 1
            'templateName' => $templateName,
100 1
            'zoomFactor'   => $zoomFactor,
101 1
            'fromPage'     => $fromPage,
102 1
            'toPage'       => $toPage,
103 1
            'imageFormat'  => $imageFormat,
104 1
        ];
105
106 1
        $records = $this->get('/templates/thumbnails', $query);
107
108 1
        if (is_array($records) && count($records) > 0) {
109 1
            $ret = [];
110 1
            foreach ($records as $index => $data) {
111 1
                $ret[$index] = base64_decode($data);
112 1
            }
113 1
        }
114
115 1
        return $ret;
116
    }
117
118
    /**
119
     * Return the number of templates in template storage
120
     *
121
     * @return integer|null
122
     */
123 1
    public function getTemplateCount()
124
    {
125 1
        return $this->get('/templates/count');
126
    }
127
128
    /**
129
     * Return an array properties for the templates in template storage
130
     *
131
     * @return array|null
132
     */
133 1 View Code Duplication
    public function getTemplateList()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
    {
135 1
        $ret = null;
136
137 1
        $propertyMap = new TemplateListPropertyMap();
138 1
        $filter      = new DateTimeToTimestampFilter();
139
140 1
        $records = $this->get('/templates/list');
141
142 1
        if (is_array($records) && count($records) > 0) {
143 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
144 1
            foreach ($ret as $index => $record) {
145 1
                $key = 'modified';
146 1
                if (isset($record[$key])) {
147 1
                    $ret[$index][$key] = $filter->filter($record[$key]);
148 1
                }
149 1
            }
150 1
        }
151
152 1
        return $ret;
153
    }
154
155
    /**
156
     * Return the number of pages in a template in template storage
157
     *
158
     * @param string $templateName Template name
159
     *
160
     * @throws InvalidArgumentException
161
     *
162
     * @return bool
163
     */
164 2 View Code Duplication
    public function getTemplatePageCount($templateName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
165
    {
166 2
        StaticValidator::execute($templateName, 'TemplateName');
167
168
        $query = [
169 1
            'templateName' => $templateName,
170 1
        ];
171
172 1
        return (integer) $this->get('/templates/pagecount', $query);
173
    }
174
175
    /**
176
     * Return true, if the template exists in template storage
177
     *
178
     * @param string $templateName Template name
179
     *
180
     * @throws InvalidArgumentException
181
     *
182
     * @return bool
183
     */
184 2 View Code Duplication
    public function templateExists($templateName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
    {
186 2
        StaticValidator::execute($templateName, 'TemplateName');
187
188
        $query = [
189 1
            'templateName' => $templateName,
190 1
        ];
191
192 1
        return (boolean) $this->get('/templates/exists', $query);
193
    }
194
195
    /**
196
     * Return an array properties for the ReportingCloud account
197
     *
198
     * @return array|null
199
     */
200 1 View Code Duplication
    public function getAccountSettings()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
201
    {
202 1
        $ret = null;
203
204 1
        $propertyMap = new AccountSettingsPropertyMap();
205 1
        $filter      = new DateTimeToTimestampFilter();
206
207 1
        $records = $this->get('/account/settings');
208
209 1
        if (is_array($records) && count($records) > 0) {
210 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
211 1
            foreach ($ret as $index => $record) {
212 1
                $key = 'valid_until';
213 1
                if (isset($record[$key])) {
214
                    $ret[$index][$key] = $filter->filter($record[$key]);
215
                }
216 1
            }
217 1
        }
218
219 1
        return $ret;
220
    }
221
222
    /**
223
     * Download the binary data of a template from template storage
224
     *
225
     * @param string $templateName Template name
226
     *
227
     * @throws InvalidArgumentException
228
     *
229
     * @return null|resource
230
     */
231 2
    public function downloadTemplate($templateName)
232
    {
233 2
        $ret = null;
234
235 2
        StaticValidator::execute($templateName, 'TemplateName');
236
237
        $query = [
238 1
            'templateName' => $templateName,
239 1
        ];
240
241 1
        $data = $this->get('/templates/download', $query);
242
243 1
        if (null !== $data) {
244 1
            $ret = base64_decode($data);
245 1
        }
246
247 1
        return $ret;
248
    }
249
250
    /**
251
     * Execute a GET request via REST client
252
     *
253
     * @param string $uri   URI
254
     * @param array  $query Query
255
     *
256
     * @return mixed|null
257
     */
258 8
    protected function get($uri, $query = [])
259
    {
260 8
        $ret = null;
261
262
        $options = [
263 8
            RequestOptions::QUERY => $query,
264 8
        ];
265
266 8
        $response = $this->request('GET', $this->uri($uri), $options);
267
268 8
        if ($response instanceof Response) {
269 8
            if (200 === $response->getStatusCode()) {
270 8
                $body = (string) $response->getBody();
271 8
                $ret  = json_decode($body, true);
272 8
            }
273 8
        }
274
275 8
        return $ret;
276
    }
277
278
279
    /**
280
     * POST methods
281
     * =================================================================================================================
282
     */
283
284
    /**
285
     * Upload a template to template storage
286
     *
287
     * @param string $templateFilename Template name
288
     *
289
     * @throws InvalidArgumentException
290
     *
291
     * @return bool
292
     */
293 12 View Code Duplication
    public function uploadTemplate($templateFilename)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
294
    {
295 12
        $ret = false;
296
297 12
        StaticValidator::execute($templateFilename, 'TemplateExtension');
298 9
        StaticValidator::execute($templateFilename, 'FileExists');
299
300 8
        $templateFilename = realpath($templateFilename);
301 8
        $templateName     = basename($templateFilename);
302
303
        $headers = [
304 8
            'Content-Type' => 'application/json',
305 8
        ];
306
307
        $query = [
308 8
            'templateName' => $templateName,
309 8
        ];
310
311 8
        $body = file_get_contents($templateFilename);
312 8
        $body = base64_encode($body);
313 8
        $body = json_encode($body);
314
315
        $options = [
316 8
            RequestOptions::HEADERS => $headers,
317 8
            RequestOptions::QUERY   => $query,
318 8
            RequestOptions::BODY    => $body,
319 8
        ];
320
321 8
        $response = $this->request('POST', $this->uri('/templates/upload'), $options);
322
323 8
        if ($response instanceof Response) {
324 8
            if (201 === $response->getStatusCode()) {
325 8
                $ret = true;
326 8
            }
327 8
        }
328
329 8
        return $ret;
330
    }
331
332
    /**
333
     * Convert a document on the local file system to a different format
334
     *
335
     * @param string $documentFilename Document filename
336
     * @param string $returnFormat     Return format
337
     *
338
     * @throws InvalidArgumentException
339
     *
340
     * @return null|resource
341
     */
342 6 View Code Duplication
    public function convertDocument($documentFilename, $returnFormat)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
343
    {
344 6
        $ret = null;
345
346 6
        StaticValidator::execute($documentFilename, 'DocumentExtension');
347 3
        StaticValidator::execute($documentFilename, 'FileExists');
348 2
        StaticValidator::execute($returnFormat    , 'ReturnFormat');
349
350
        $headers = [
351 1
            'Content-Type' => 'application/json',
352 1
        ];
353
354
        $query = [
355 1
            'returnFormat' => $returnFormat,
356 1
        ];
357
358 1
        $documentFilename = realpath($documentFilename);
359
360 1
        $body = file_get_contents($documentFilename);
361 1
        $body = base64_encode($body);
362 1
        $body = json_encode($body);
363
364
        $options = [
365 1
            RequestOptions::HEADERS => $headers,
366 1
            RequestOptions::QUERY   => $query,
367 1
            RequestOptions::BODY    => $body,
368 1
        ];
369
370 1
        $response = $this->request('POST', $this->uri('/document/convert'), $options);
371
372 1
        if ($response instanceof Response) {
373 1
            if (200 === $response->getStatusCode()) {
374 1
                $body = (string) $response->getBody();
375 1
                $ret  = base64_decode($body);
376 1
            }
377 1
        }
378
379 1
        return $ret;
380
    }
381
382
    /**
383
     * Merge data into a template and return an array of binary data.
384
     * Each record in the array is the binary data of one document
385
     *
386
     * @param array   $mergeData         Array of merge data
387
     * @param string  $returnFormat      Return format
388
     * @param string  $templateName      Template name
389
     * @param string  $templateFilename  Template filename on local file system
390
     * @param boolean $append            Append flag
391
     * @param array   $mergeSettings     Array of merge settings
392
     *
393
     * @throws InvalidArgumentException
394
     *
395
     * @return null|string
396
     */
397 13
    public function mergeDocument($mergeData, $returnFormat, $templateName = null, $templateFilename = null,
398
                                    $append = null, $mergeSettings = [])
399
    {
400 13
        $ret = null;
401
402 13
        StaticValidator::execute($mergeData   , 'TypeArray');
403 13
        StaticValidator::execute($returnFormat, 'ReturnFormat');
404
405 12
        if (null !== $templateName) {
406 2
            StaticValidator::execute($templateName, 'TemplateName');
407 1
        }
408
409 11
        if (null !== $templateFilename) {
410 10
            StaticValidator::execute($templateFilename, 'TemplateExtension');
411 7
            StaticValidator::execute($templateFilename, 'FileExists');
412 6
            $templateFilename = realpath($templateFilename);
413 6
        }
414
415
        // This boolean value MUST be passed as a string to prevent Guzzle converting the
416
        // query parameter to ?append=0 or ?append=1, which the backend does not recognize.
417
        // The backend only recognizes query parameter ?append=true and ?append=false.
418 7
        if (null !== $append) {
419 6
            StaticValidator::execute($append, 'TypeBoolean');
420 5
            if (true === $append) {
421 1
                $append = 'true';
422 1
            } else {
423 4
                $append = 'false';
424
            }
425 5
        }
426
427 6
        StaticValidator::execute($mergeSettings, 'TypeArray');
428
429
        $headers = [
430 5
            'Content-Type' => 'application/json',
431 5
        ];
432
433
        $query = [
434 5
            'returnFormat' => $returnFormat,
435 5
            'append'       => $append,
436 5
        ];
437
438 5
        if (null !== $templateName) {
439 1
            $query['templateName'] = $templateName;
440 1
        }
441
442 5
        $mergeSettingsRc = null;
443
444 5
        if (count($mergeSettings) > 0) {
445
446 4
            $filter = new TimestampToDateTimeFilter();
447
448 4
            $mergeSettingsRc = []; // 'Rc' - this array is passed to ReportingCloud
449
450 4
            $propertyMap = new MergeSettingsPropertyMap();
451
452 4
            foreach ($propertyMap->getMap() as $property => $key) {
453 4
                if (isset($mergeSettings[$key])) {
454 4
                    $value = $mergeSettings[$key];
455 4
                    if ('remove_' == substr($key, 0, 7)) {
456 3
                        StaticValidator::execute($value, 'TypeBoolean');
457 2
                    }
458 4
                    if ('_date' == substr($key, -5)) {
459 4
                        StaticValidator::execute($value, 'Timestamp');
460 3
                        $value = $filter->filter($value);
461 3
                    }
462 4
                    $mergeSettingsRc[$property] = $value;
463 4
                }
464 4
            }
465 2
        }
466
        
467 3
        unset($mergeSettings);
468
469
        $mergeBody = [
470 3
            'mergeData' => $mergeData,
471 3
        ];
472
473 3
        if (null !== $templateFilename) {
474 2
            $template = file_get_contents($templateFilename);
475 2
            $template = base64_encode($template);
476 2
            $mergeBody['template'] = $template;
477 2
        }
478
479 3
        if (null !== $mergeSettingsRc) {
480 2
            $mergeBody['mergeSettings'] = $mergeSettingsRc;
481 2
        }
482
483 3
        $body = json_encode($mergeBody);
484
485
        $options = [
486 3
            RequestOptions::HEADERS => $headers,
487 3
            RequestOptions::QUERY   => $query,
488 3
            RequestOptions::BODY    => $body,
489 3
        ];
490
491 3
        $response = $this->request('POST', $this->uri('/document/merge'), $options);
492
493 3
        if ($response instanceof Response) {
494 3
            if (200 === $response->getStatusCode()) {
495 3
                $body = (string) $response->getBody();
496 3
                $body = json_decode($body);
497 3
                if (is_array($body) && count($body) > 0) {
498 3
                    $ret = [];
499 3
                    foreach ($body as $record) {
500 3
                        array_push($ret, base64_decode($record));
501 3
                    }
502 3
                }
503 3
            }
504 3
        }
505
506 3
        return $ret;
507
    }
508
509
510
    /**
511
     * DELETE methods
512
     * =================================================================================================================
513
     */
514
515
    /**
516
     * Delete a template in template storage
517
     *
518
     * @param string $templateName Template name
519
     *
520
     * @throws InvalidArgumentException
521
     *
522
     * @return bool
523
     */
524 10
    public function deleteTemplate($templateName)
525
    {
526 10
        $ret = false;
527
528 10
        StaticValidator::execute($templateName, 'TemplateName');
529
530
        $query = [
531 9
            'templateName' => $templateName,
532 9
        ];
533
534
        $options = [
535 9
            RequestOptions::QUERY => $query,
536 9
        ];
537
538 9
        $response = $this->request('DELETE', $this->uri('/templates/delete'), $options);
539
540 8
        if ($response instanceof Response) {
541 8
            if (204 === $response->getStatusCode()) {
542 8
                $ret = true;
543 8
            }
544 8
        }
545
546 8
        return $ret;
547
    }
548
}