Completed
Push — master ( 9e7e8e...296b9a )
by Jonathan
03:56
created

ReportingCloud::deleteTemplate()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 14
cts 14
cp 1
rs 8.9713
c 0
b 0
f 0
cc 3
eloc 12
nc 3
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
use TxTextControl\ReportingCloud\Exception\InvalidArgumentException;
18
use TxTextControl\ReportingCloud\Filter\DateTimeToTimestamp as DateTimeToTimestampFilter;
19
use TxTextControl\ReportingCloud\Filter\TimestampToDateTime as TimestampToDateTimeFilter;
20
use TxTextControl\ReportingCloud\PropertyMap\AccountSettings as AccountSettingsPropertyMap;
21
use TxTextControl\ReportingCloud\PropertyMap\MergeSettings as MergeSettingsPropertyMap;
22
use TxTextControl\ReportingCloud\PropertyMap\TemplateInfo as TemplateInfoPropertyMap;
23
use TxTextControl\ReportingCloud\PropertyMap\TemplateList as TemplateListPropertyMap;
24
use TxTextControl\ReportingCloud\Validator\StaticValidator;
25
26
/**
27
 * ReportingCloud
28
 *
29
 * @package TxTextControl\ReportingCloud
30
 * @author  Jonathan Maron (@JonathanMaron)
31
 */
32
class ReportingCloud extends AbstractReportingCloud
33
{
34
35
    /**
36
     * GET methods
37
     * =================================================================================================================
38
     */
39
40
    /**
41
     * Return an array of merge blocks and merge fields in a template file in template storage.
42
     *
43
     * @param string  $templateName Template name
44
     *
45
     * @throws InvalidArgumentException
46
     *
47
     * @return array|null
48
     */
49 1
    public function getTemplateInfo($templateName)
50
    {
51 1
        $ret = null;
52
53 1
        $propertyMap = new TemplateInfoPropertyMap();
54
55 1
        StaticValidator::execute($templateName, 'TemplateName');
56
57
        $query = [
58 1
            'templateName' => $templateName,
59 1
        ];
60
61 1
        $records = $this->get('/templates/info', $query);
62
63 1
        if (is_array($records) && count($records) > 0) {
64 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
65 1
        }
66
67 1
        return $ret;
68
    }
69
70
    /**
71
     * Return an array of binary data.
72
     * Each record in the array is the binary data of a thumbnail image
73
     *
74
     * @param string  $templateName Template name
75
     * @param integer $zoomFactor   Zoom factor
76
     * @param integer $fromPage     From page
77
     * @param integer $toPage       To page
78
     * @param string  $imageFormat  Image format
79
     *
80
     * @throws InvalidArgumentException
81
     *
82
     * @return array|null
83
     */
84 6
    public function getTemplateThumbnails($templateName, $zoomFactor, $fromPage, $toPage, $imageFormat)
85
    {
86 6
        $ret = null;
87
88 6
        StaticValidator::execute($templateName, 'TemplateName');
89 5
        StaticValidator::execute($zoomFactor  , 'ZoomFactor');
90 4
        StaticValidator::execute($fromPage    , 'Page');
91 3
        StaticValidator::execute($toPage      , 'Page');
92 2
        StaticValidator::execute($imageFormat , 'ImageFormat');
93
94
        $query = [
95 1
            'templateName' => $templateName,
96 1
            'zoomFactor'   => $zoomFactor,
97 1
            'fromPage'     => $fromPage,
98 1
            'toPage'       => $toPage,
99 1
            'imageFormat'  => $imageFormat,
100 1
        ];
101
102 1
        $records = $this->get('/templates/thumbnails', $query);
103
104 1
        if (is_array($records) && count($records) > 0) {
105 1
            $ret = [];
106 1
            foreach ($records as $index => $data) {
107 1
                $ret[$index] = base64_decode($data);
108 1
            }
109 1
        }
110
111 1
        return $ret;
112
    }
113
114
    /**
115
     * Return the number of templates in template storage
116
     *
117
     * @return integer|null
118
     */
119 1
    public function getTemplateCount()
120
    {
121 1
        return $this->get('/templates/count');
122
    }
123
124
    /**
125
     * Return an array properties for the templates in template storage
126
     *
127
     * @return array|null
128
     */
129 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...
130
    {
131 1
        $ret = null;
132
133 1
        $propertyMap = new TemplateListPropertyMap();
134 1
        $filter      = new DateTimeToTimestampFilter();
135
136 1
        $records = $this->get('/templates/list');
137
138 1
        if (is_array($records) && count($records) > 0) {
139 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
140 1
            foreach ($ret as $index => $record) {
141 1
                $key = 'modified';
142 1
                if (isset($record[$key])) {
143 1
                    $ret[$index][$key] = $filter->filter($record[$key]);
144 1
                }
145 1
            }
146 1
        }
147
148 1
        return $ret;
149
    }
150
151
    /**
152
     * Return the number of pages in a template in template storage
153
     *
154
     * @param string $templateName Template name
155
     *
156
     * @throws InvalidArgumentException
157
     *
158
     * @return bool
159
     */
160 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...
161
    {
162 2
        StaticValidator::execute($templateName, 'TemplateName');
163
164
        $query = [
165 1
            'templateName' => $templateName,
166 1
        ];
167
168 1
        return (integer) $this->get('/templates/pagecount', $query);
169
    }
170
171
    /**
172
     * Return true, if the template exists in template storage
173
     *
174
     * @param string $templateName Template name
175
     *
176
     * @throws InvalidArgumentException
177
     *
178
     * @return bool
179
     */
180 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...
181
    {
182 2
        StaticValidator::execute($templateName, 'TemplateName');
183
184
        $query = [
185 1
            'templateName' => $templateName,
186 1
        ];
187
188 1
        return (boolean) $this->get('/templates/exists', $query);
189
    }
190
191
    /**
192
     * Return an array properties for the ReportingCloud account
193
     *
194
     * @return array|null
195
     */
196 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...
197
    {
198 1
        $ret = null;
199
200 1
        $propertyMap = new AccountSettingsPropertyMap();
201 1
        $filter      = new DateTimeToTimestampFilter();
202
203 1
        $records = $this->get('/account/settings');
204
205 1
        if (is_array($records) && count($records) > 0) {
206 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
207 1
            foreach ($ret as $index => $record) {
208 1
                $key = 'valid_until';
209 1
                if (isset($record[$key])) {
210
                    $ret[$index][$key] = $filter->filter($record[$key]);
211
                }
212 1
            }
213 1
        }
214
215 1
        return $ret;
216
    }
217
218
    /**
219
     * Download the binary data of a template from template storage
220
     *
221
     * @param string $templateName Template name
222
     *
223
     * @throws InvalidArgumentException
224
     *
225
     * @return null|resource
226
     */
227 2
    public function downloadTemplate($templateName)
228
    {
229 2
        $ret = null;
230
231 2
        StaticValidator::execute($templateName, 'TemplateName');
232
233
        $query = [
234 1
            'templateName' => $templateName,
235 1
        ];
236
237 1
        $data = $this->get('/templates/download', $query);
238
239 1
        if (null !== $data) {
240 1
            $ret = base64_decode($data);
241 1
        }
242
243 1
        return $ret;
244
    }
245
246
    /**
247
     * Execute a GET request via REST client
248
     *
249
     * @param string $uri   URI
250
     * @param array  $query Query
251
     *
252
     * @return mixed|null
253
     */
254 8
    protected function get($uri, $query = [])
255
    {
256 8
        $ret = null;
257
258
        $options = [
259 8
            RequestOptions::QUERY => $query,
260 8
        ];
261
262 8
        $response = $this->request('GET', $this->uri($uri), $options);
263
264 8
        if ($response instanceof Response) {
265 8
            if (200 === $response->getStatusCode()) {
266 8
                $body = (string) $response->getBody();
267 8
                $ret  = json_decode($body, true);
268 8
            }
269 8
        }
270
271 8
        return $ret;
272
    }
273
274
275
    /**
276
     * POST methods
277
     * =================================================================================================================
278
     */
279
280
    /**
281
     * Upload a template to template storage
282
     *
283
     * @param string $templateFilename Template name
284
     *
285
     * @throws InvalidArgumentException
286
     *
287
     * @return bool
288
     */
289 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...
290
    {
291 12
        $ret = false;
292
293 12
        StaticValidator::execute($templateFilename, 'TemplateExtension');
294 9
        StaticValidator::execute($templateFilename, 'FileExists');
295
296 8
        $templateFilename = realpath($templateFilename);
297 8
        $templateName     = basename($templateFilename);
298
299
        $headers = [
300 8
            'Content-Type' => 'application/json',
301 8
        ];
302
303
        $query = [
304 8
            'templateName' => $templateName,
305 8
        ];
306
307 8
        $body = file_get_contents($templateFilename);
308 8
        $body = base64_encode($body);
309 8
        $body = json_encode($body);
310
311
        $options = [
312 8
            RequestOptions::HEADERS => $headers,
313 8
            RequestOptions::QUERY   => $query,
314 8
            RequestOptions::BODY    => $body,
315 8
        ];
316
317 8
        $response = $this->request('POST', $this->uri('/templates/upload'), $options);
318
319 8
        if ($response instanceof Response) {
320 8
            if (201 === $response->getStatusCode()) {
321 8
                $ret = true;
322 8
            }
323 8
        }
324
325 8
        return $ret;
326
    }
327
328
    /**
329
     * Convert a document on the local file system to a different format
330
     *
331
     * @param string $documentFilename Document filename
332
     * @param string $returnFormat     Return format
333
     *
334
     * @throws InvalidArgumentException
335
     *
336
     * @return null|resource
337
     */
338 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...
339
    {
340 6
        $ret = null;
341
342 6
        StaticValidator::execute($documentFilename, 'DocumentExtension');
343 3
        StaticValidator::execute($documentFilename, 'FileExists');
344 2
        StaticValidator::execute($returnFormat    , 'ReturnFormat');
345
346
        $headers = [
347 1
            'Content-Type' => 'application/json',
348 1
        ];
349
350
        $query = [
351 1
            'returnFormat' => $returnFormat,
352 1
        ];
353
354 1
        $documentFilename = realpath($documentFilename);
355
356 1
        $body = file_get_contents($documentFilename);
357 1
        $body = base64_encode($body);
358 1
        $body = json_encode($body);
359
360
        $options = [
361 1
            RequestOptions::HEADERS => $headers,
362 1
            RequestOptions::QUERY   => $query,
363 1
            RequestOptions::BODY    => $body,
364 1
        ];
365
366 1
        $response = $this->request('POST', $this->uri('/document/convert'), $options);
367
368 1
        if ($response instanceof Response) {
369 1
            if (200 === $response->getStatusCode()) {
370 1
                $body = (string) $response->getBody();
371 1
                $ret  = base64_decode($body);
372 1
            }
373 1
        }
374
375 1
        return $ret;
376
    }
377
378
    /**
379
     * Merge data into a template and return an array of binary data.
380
     * Each record in the array is the binary data of one document
381
     *
382
     * @param array   $mergeData         Array of merge data
383
     * @param string  $returnFormat      Return format
384
     * @param string  $templateName      Template name
385
     * @param string  $templateFilename  Template filename on local file system
386
     * @param boolean $append            Append flag
387
     * @param array   $mergeSettings     Array of merge settings
388
     *
389
     * @throws InvalidArgumentException
390
     *
391
     * @return null|string
392
     */
393 13
    public function mergeDocument($mergeData, $returnFormat, $templateName = null, $templateFilename = null,
394
                                    $append = null, $mergeSettings = [])
395
    {
396 13
        $ret = null;
397
398 13
        StaticValidator::execute($mergeData   , 'TypeArray');
399 13
        StaticValidator::execute($returnFormat, 'ReturnFormat');
400
401 12
        if (null !== $templateName) {
402 2
            StaticValidator::execute($templateName, 'TemplateName');
403 1
        }
404
405 11 View Code Duplication
        if (null !== $templateFilename) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
406 10
            StaticValidator::execute($templateFilename, 'TemplateExtension');
407 7
            StaticValidator::execute($templateFilename, 'FileExists');
408 6
            $templateFilename = realpath($templateFilename);
409 6
        }
410
411
        // This boolean value MUST be passed as a string to prevent Guzzle converting the
412
        // query parameter to ?append=0 or ?append=1, which the backend does not recognize.
413
        // The backend only recognizes query parameter ?append=true and ?append=false.
414 7
        if (null !== $append) {
415 6
            StaticValidator::execute($append, 'TypeBoolean');
416 5
            if (true === $append) {
417 1
                $append = 'true';
418 1
            } else {
419 4
                $append = 'false';
420
            }
421 5
        }
422
423 6
        StaticValidator::execute($mergeSettings, 'TypeArray');
424
425
        $headers = [
426 5
            'Content-Type' => 'application/json',
427 5
        ];
428
429
        $query = [
430 5
            'returnFormat' => $returnFormat,
431 5
            'append'       => $append,
432 5
        ];
433
434 5
        if (null !== $templateName) {
435 1
            $query['templateName'] = $templateName;
436 1
        }
437
438
        $mergeBody = [
439 5
            'mergeData' => $mergeData,
440 5
        ];
441
442 5 View Code Duplication
        if (null !== $templateFilename) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
443 4
            $template = file_get_contents($templateFilename);
444 4
            $template = base64_encode($template);
445 4
            $mergeBody['template'] = $template;
446 4
        }
447
448 5
        if (count($mergeSettings) > 0) {
449 4
            $mergeBody['mergeSettings'] = $this->assembleMergeSettings($mergeSettings);
450 2
        }
451
452 3
        $body = json_encode($mergeBody);
453
454
        $options = [
455 3
            RequestOptions::HEADERS => $headers,
456 3
            RequestOptions::QUERY   => $query,
457 3
            RequestOptions::BODY    => $body,
458 3
        ];
459
460 3
        $response = $this->request('POST', $this->uri('/document/merge'), $options);
461
462 3
        if ($response instanceof Response) {
463 3
            if (200 === $response->getStatusCode()) {
464 3
                $body = (string) $response->getBody();
465 3
                $body = json_decode($body);
466 3
                if (is_array($body) && count($body) > 0) {
467 3
                    $ret = [];
468 3
                    foreach ($body as $record) {
469 3
                        array_push($ret, base64_decode($record));
470 3
                    }
471 3
                }
472 3
            }
473 3
        }
474
475 3
        return $ret;
476
    }
477
478
    /**
479
     * Perform find and replace in template and return an array of binary data.
480
     *
481
     * @param array   $findAndReplaceData  Array of findAndReplaceData
482
     * @param string  $returnFormat        Return format
483
     * @param string  $templateName        Template name
484
     * @param string  $templateFilename    Template filename on local file system
485
     * @param array   $mergeSettings       Array of merge settings
486
     *
487
     * @throws InvalidArgumentException
488
     *
489
     * @return null|string
490
     */
491
    public function findAndReplace($findAndReplaceData, $returnFormat, $templateName = null, $templateFilename = null,
492
                                   $mergeSettings = [])
493
    {
494
        $ret = null;
495
496
        StaticValidator::execute($findAndReplaceData   , 'TypeArray');
497
        StaticValidator::execute($returnFormat, 'ReturnFormat');
498
499
        if (null !== $templateName) {
500
            StaticValidator::execute($templateName, 'TemplateName');
501
        }
502
503 View Code Duplication
        if (null !== $templateFilename) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
504
            StaticValidator::execute($templateFilename, 'TemplateExtension');
505
            StaticValidator::execute($templateFilename, 'FileExists');
506
            $templateFilename = realpath($templateFilename);
507
        }
508
509
        StaticValidator::execute($mergeSettings, 'TypeArray');
510
511
        $headers = [
512
            'Content-Type' => 'application/json',
513
        ];
514
515
        $query = [
516
            'returnFormat' => $returnFormat,
517
        ];
518
519
        if (null !== $templateName) {
520
            $query['templateName'] = $templateName;
521
        }
522
523
524
525
        $findAndReplaceBody = [
526
            'findAndReplaceData' => $findAndReplaceData,
527
        ];
528
529 View Code Duplication
        if (null !== $templateFilename) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
530
            $template = file_get_contents($templateFilename);
531
            $template = base64_encode($template);
532
            $findAndReplaceBody['template'] = $template;
533
        }
534
535
        if (count($mergeSettings) > 0) {
536
            $findAndReplaceBody['mergeSettings'] = $this->assembleMergeSettings($mergeSettings);
537
        }
538
539
        $body = json_encode($findAndReplaceBody);
540
541
        $options = [
542
            RequestOptions::HEADERS => $headers,
543
            RequestOptions::QUERY   => $query,
544
            RequestOptions::BODY    => $body,
545
        ];
546
547
        $response = $this->request('POST', $this->uri('/document/findandreplace'), $options);
548
549
        if ($response instanceof Response) {
550
            if (200 === $response->getStatusCode()) {
551
                $body = (string) $response->getBody();
552
                $ret = base64_decode($body);
553
            }
554
        }
555
556
        return $ret;
557
    }
558
559 4
    protected function assembleMergeSettings($mergeSettings)
560
    {
561 4
        $ret = [];
562
563 4
        $filter      = new TimestampToDateTimeFilter();
564 4
        $propertyMap = new MergeSettingsPropertyMap();
565
566 4
        foreach ($propertyMap->getMap() as $property => $key) {
567 4
            if (isset($mergeSettings[$key])) {
568 4
                $value = $mergeSettings[$key];
569 4
                if ('remove_' == substr($key, 0, 7)) {
570 3
                    StaticValidator::execute($value, 'TypeBoolean');
571 2
                }
572 4
                if ('_date' == substr($key, -5)) {
573 4
                    StaticValidator::execute($value, 'Timestamp');
574 3
                    $value = $filter->filter($value);
575 3
                }
576 4
                $ret[$property] = $value;
577 4
            }
578 4
        }
579
580 2
        return $ret;
581
    }
582
583
584
    /**
585
     * DELETE methods
586
     * =================================================================================================================
587
     */
588
589
    /**
590
     * Delete a template in template storage
591
     *
592
     * @param string $templateName Template name
593
     *
594
     * @throws InvalidArgumentException
595
     *
596
     * @return bool
597
     */
598 10
    public function deleteTemplate($templateName)
599
    {
600 10
        $ret = false;
601
602 10
        StaticValidator::execute($templateName, 'TemplateName');
603
604
        $query = [
605 9
            'templateName' => $templateName,
606 9
        ];
607
608
        $options = [
609 9
            RequestOptions::QUERY => $query,
610 9
        ];
611
612 9
        $response = $this->request('DELETE', $this->uri('/templates/delete'), $options);
613
614 8
        if ($response instanceof Response) {
615 8
            if (204 === $response->getStatusCode()) {
616 8
                $ret = true;
617 8
            }
618 8
        }
619
620 8
        return $ret;
621
    }
622
}