Passed
Push — master ( a15edb...2827e6 )
by Jonathan
03:41
created

ReportingCloud::mergeDocument()   D

Complexity

Conditions 12
Paths 256

Size

Total Lines 74
Code Lines 43

Duplication

Lines 10
Ratio 13.51 %

Code Coverage

Tests 52
CRAP Score 12

Importance

Changes 4
Bugs 0 Features 0
Metric Value
dl 10
loc 74
ccs 52
cts 52
cp 1
rs 4.0382
c 4
b 0
f 0
cc 12
eloc 43
nc 256
nop 6
crap 12

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\PropertyMap\AccountSettings as AccountSettingsPropertyMap;
20
use TxTextControl\ReportingCloud\PropertyMap\TemplateInfo as TemplateInfoPropertyMap;
21
use TxTextControl\ReportingCloud\PropertyMap\TemplateList as TemplateListPropertyMap;
22
use TxTextControl\ReportingCloud\Validator\StaticValidator;
23
use TxTextControl\ReportingCloud\Filter\BooleanToString as BooleanToStringFilter;
24
25
/**
26
 * ReportingCloud
27
 *
28
 * @package TxTextControl\ReportingCloud
29
 * @author  Jonathan Maron (@JonathanMaron)
30
 */
31
class ReportingCloud extends AbstractReportingCloud
32
{
33
34
    /**
35
     * GET methods
36
     * =================================================================================================================
37
     */
38
39
    /**
40
     * Return an array of merge blocks and merge fields in a template file in template storage.
41
     *
42
     * @param string  $templateName Template name
43
     *
44
     * @throws InvalidArgumentException
45
     *
46
     * @return array|null
47
     */
48 1
    public function getTemplateInfo($templateName)
49
    {
50 1
        $ret = null;
51
52 1
        $propertyMap = new TemplateInfoPropertyMap();
53
54 1
        StaticValidator::execute($templateName, 'TemplateName');
55
56
        $query = [
57 1
            'templateName' => $templateName,
58 1
        ];
59
60 1
        $records = $this->get('/templates/info', $query);
61
62 1
        if (is_array($records) && count($records) > 0) {
63 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
64 1
        }
65
66 1
        return $ret;
67
    }
68
69
    /**
70
     * Return an array of binary data.
71
     * Each record in the array is the binary data of a thumbnail image
72
     *
73
     * @param string  $templateName Template name
74
     * @param integer $zoomFactor   Zoom factor
75
     * @param integer $fromPage     From page
76
     * @param integer $toPage       To page
77
     * @param string  $imageFormat  Image format
78
     *
79
     * @throws InvalidArgumentException
80
     *
81
     * @return array|null
82
     */
83 6
    public function getTemplateThumbnails($templateName, $zoomFactor, $fromPage, $toPage, $imageFormat)
84
    {
85 6
        $ret = null;
86
87 6
        StaticValidator::execute($templateName, 'TemplateName');
88 5
        StaticValidator::execute($zoomFactor  , 'ZoomFactor');
89 4
        StaticValidator::execute($fromPage    , 'Page');
90 3
        StaticValidator::execute($toPage      , 'Page');
91 2
        StaticValidator::execute($imageFormat , 'ImageFormat');
92
93
        $query = [
94 1
            'templateName' => $templateName,
95 1
            'zoomFactor'   => $zoomFactor,
96 1
            'fromPage'     => $fromPage,
97 1
            'toPage'       => $toPage,
98 1
            'imageFormat'  => $imageFormat,
99 1
        ];
100
101 1
        $records = $this->get('/templates/thumbnails', $query);
102
103 1
        if (is_array($records) && count($records) > 0) {
104 1
            $ret = [];
105 1
            foreach ($records as $index => $data) {
106 1
                $ret[$index] = base64_decode($data);
107 1
            }
108 1
        }
109
110 1
        return $ret;
111
    }
112
113
    /**
114
     * Return the number of templates in template storage
115
     *
116
     * @return integer|null
117
     */
118 1
    public function getTemplateCount()
119
    {
120 1
        return $this->get('/templates/count');
121
    }
122
123
    /**
124
     * Return an array properties for the templates in template storage
125
     *
126
     * @return array|null
127
     */
128 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...
129
    {
130 1
        $ret = null;
131
132 1
        $propertyMap = new TemplateListPropertyMap();
133 1
        $filter      = new DateTimeToTimestampFilter();
134
135 1
        $records = $this->get('/templates/list');
136
137 1
        if (is_array($records) && count($records) > 0) {
138 1
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
139 1
            foreach ($ret as $index => $record) {
140 1
                $key = 'modified';
141 1
                if (isset($record[$key])) {
142 1
                    $ret[$index][$key] = $filter->filter($record[$key]);
143 1
                }
144 1
            }
145 1
        }
146
147 1
        return $ret;
148
    }
149
150
    /**
151
     * Return the number of pages in a template in template storage
152
     *
153
     * @param string $templateName Template name
154
     *
155
     * @throws InvalidArgumentException
156
     *
157
     * @return bool
158
     */
159 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...
160
    {
161 2
        StaticValidator::execute($templateName, 'TemplateName');
162
163
        $query = [
164 1
            'templateName' => $templateName,
165 1
        ];
166
167 1
        return (integer) $this->get('/templates/pagecount', $query);
168
    }
169
170
    /**
171
     * Return true, if the template exists in template storage
172
     *
173
     * @param string $templateName Template name
174
     *
175
     * @throws InvalidArgumentException
176
     *
177
     * @return bool
178
     */
179 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...
180
    {
181 2
        StaticValidator::execute($templateName, 'TemplateName');
182
183
        $query = [
184 1
            'templateName' => $templateName,
185 1
        ];
186
187 1
        return (boolean) $this->get('/templates/exists', $query);
188
    }
189
190
    /**
191
     * Return an array properties for the ReportingCloud account
192
     *
193
     * @return array|null
194
     */
195 3 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...
196
    {
197 3
        $ret = null;
198
199 3
        $propertyMap = new AccountSettingsPropertyMap();
200 3
        $filter      = new DateTimeToTimestampFilter();
201
202 3
        $records = $this->get('/account/settings');
203
204 3
        if (is_array($records) && count($records) > 0) {
205 3
            $ret = $this->normalizeArrayKeys($records, $propertyMap);
206 3
            foreach ($ret as $index => $record) {
207 3
                $key = 'valid_until';
208 3
                if (isset($record[$key])) {
209
                    $ret[$index][$key] = $filter->filter($record[$key]);
210
                }
211 3
            }
212 3
        }
213
214 3
        return $ret;
215
    }
216
217
    /**
218
     * Download the binary data of a template from template storage
219
     *
220
     * @param string $templateName Template name
221
     *
222
     * @throws InvalidArgumentException
223
     *
224
     * @return null|resource
225
     */
226 2
    public function downloadTemplate($templateName)
227
    {
228 2
        $ret = null;
229
230 2
        StaticValidator::execute($templateName, 'TemplateName');
231
232
        $query = [
233 1
            'templateName' => $templateName,
234 1
        ];
235
236 1
        $data = $this->get('/templates/download', $query);
237
238 1
        if (null !== $data) {
239 1
            $ret = base64_decode($data);
240 1
        }
241
242 1
        return $ret;
243
    }
244
245
    /**
246
     * Execute a GET request via REST client
247
     *
248
     * @param string $uri   URI
249
     * @param array  $query Query
250
     *
251
     * @return mixed|null
252
     */
253 10
    protected function get($uri, $query = [])
254
    {
255 10
        $ret = null;
256
257
        $options = [
258 10
            RequestOptions::QUERY => $query,
259 10
        ];
260
261 10
        $response = $this->request('GET', $this->uri($uri), $options);
262
263 10
        if ($response instanceof Response) {
264 10
            if (200 === $response->getStatusCode()) {
265 10
                $body = (string) $response->getBody();
266 10
                $ret  = json_decode($body, true);
267 10
            }
268 10
        }
269
270 10
        return $ret;
271
    }
272
273
274
    /**
275
     * POST methods
276
     * =================================================================================================================
277
     */
278
279
    /**
280
     * Upload a template to template storage
281
     *
282
     * @param string $templateFilename Template name
283
     *
284
     * @throws InvalidArgumentException
285
     *
286
     * @return bool
287
     */
288 13
    public function uploadTemplate($templateFilename)
289
    {
290 13
        $ret = false;
291
292 13
        StaticValidator::execute($templateFilename, 'TemplateExtension');
293 10
        StaticValidator::execute($templateFilename, 'FileExists');
294
295 9
        $templateFilename = realpath($templateFilename);
296 9
        $templateName     = basename($templateFilename);
297
298
        $query = [
299 9
            'templateName' => $templateName,
300 9
        ];
301
302 9
        $body = file_get_contents($templateFilename);
303 9
        $body = base64_encode($body);
304 9
        $body = json_encode($body);
305
306
        $options = [
307 9
            RequestOptions::QUERY => $query,
308 9
            RequestOptions::BODY  => $body,
309 9
        ];
310
311 9
        $response = $this->request('POST', $this->uri('/templates/upload'), $options);
312
313 9
        if ($response instanceof Response) {
314 9
            if (201 === $response->getStatusCode()) {
315 9
                $ret = true;
316 9
            }
317 9
        }
318
319 9
        return $ret;
320
    }
321
322
    /**
323
     * Convert a document on the local file system to a different format
324
     *
325
     * @param string $documentFilename Document filename
326
     * @param string $returnFormat     Return format
327
     *
328
     * @throws InvalidArgumentException
329
     *
330
     * @return null|resource
331
     */
332 6
    public function convertDocument($documentFilename, $returnFormat)
333
    {
334 6
        $ret = null;
335
336 6
        StaticValidator::execute($documentFilename, 'DocumentExtension');
337 3
        StaticValidator::execute($documentFilename, 'FileExists');
338 2
        StaticValidator::execute($returnFormat    , 'ReturnFormat');
339
340 1
        $booleanToStringFilter = new BooleanToStringFilter();
341
342
        $query = [
343 1
            'returnFormat' => $returnFormat,
344 1
            'test'         => $booleanToStringFilter->filter($this->getTest()),
0 ignored issues
show
Documentation introduced by
$this->getTest() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
345 1
        ];
346
347 1
        $documentFilename = realpath($documentFilename);
348
349 1
        $body = file_get_contents($documentFilename);
350 1
        $body = base64_encode($body);
351 1
        $body = json_encode($body);
352
353
        $options = [
354 1
            RequestOptions::QUERY => $query,
355 1
            RequestOptions::BODY  => $body,
356 1
        ];
357
358 1
        $response = $this->request('POST', $this->uri('/document/convert'), $options);
359
360 1
        if ($response instanceof Response) {
361 1
            if (200 === $response->getStatusCode()) {
362 1
                $body = (string) $response->getBody();
363 1
                $ret  = base64_decode($body);
364 1
            }
365 1
        }
366
367 1
        return $ret;
368
    }
369
370
    /**
371
     * Merge data into a template and return an array of binary data.
372
     * Each record in the array is the binary data of one document
373
     *
374
     * @param array   $mergeData        Array of merge data
375
     * @param string  $returnFormat     Return format
376
     * @param string  $templateName     Template name
377
     * @param string  $templateFilename Template filename on local file system
378
     * @param boolean $append           Append flag
379
     * @param array   $mergeSettings    Array of merge settings
380
     *
381
     * @throws InvalidArgumentException
382
     *
383
     * @return null|string
384
     */
385 15
    public function mergeDocument($mergeData, $returnFormat, $templateName = null, $templateFilename = null,
386
                                    $append = null, $mergeSettings = [])
387
    {
388 15
        $ret = null;
389
390 15
        StaticValidator::execute($mergeData   , 'TypeArray');
391 15
        StaticValidator::execute($returnFormat, 'ReturnFormat');
392
393 14
        if (null !== $templateName) {
394 2
            StaticValidator::execute($templateName, 'TemplateName');
395 1
        }
396
397 13 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...
398 12
            StaticValidator::execute($templateFilename, 'TemplateExtension');
399 9
            StaticValidator::execute($templateFilename, 'FileExists');
400 8
            $templateFilename = realpath($templateFilename);
401 8
        }
402
403 9
        $booleanToStringFilter = new BooleanToStringFilter();
404
405 9
        if (null !== $append) {
406 6
            $append = $booleanToStringFilter->filter($append);
0 ignored issues
show
Documentation introduced by
$append is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
407 5
        }
408
409 8
        StaticValidator::execute($mergeSettings, 'TypeArray');
410
411
        $query = [
412 7
            'returnFormat' => $returnFormat,
413 7
            'append'       => $append,
414 7
            'test'         => $booleanToStringFilter->filter($this->getTest()),
0 ignored issues
show
Documentation introduced by
$this->getTest() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
415 7
        ];
416
417 7
        if (null !== $templateName) {
418 1
            $query['templateName'] = $templateName;
419 1
        }
420
421
        $mergeBody = [
422 7
            'mergeData' => $mergeData,
423 7
        ];
424
425 7 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...
426 6
            $template = file_get_contents($templateFilename);
427 6
            $template = base64_encode($template);
428 6
            $mergeBody['template'] = $template;
429 6
        }
430
431 7
        if (count($mergeSettings) > 0) {
432 4
            $mergeBody['mergeSettings'] = $this->assembleMergeSettings($mergeSettings);
433 2
        }
434
435 5
        $body = json_encode($mergeBody);
436
437
        $options = [
438 5
            RequestOptions::QUERY => $query,
439 5
            RequestOptions::BODY  => $body,
440 5
        ];
441
442 5
        $response = $this->request('POST', $this->uri('/document/merge'), $options);
443
444 5
        if ($response instanceof Response) {
445 5
            if (200 === $response->getStatusCode()) {
446 5
                $body = (string) $response->getBody();
447 5
                $body = json_decode($body);
448 5
                if (is_array($body) && count($body) > 0) {
449 5
                    $ret = [];
450 5
                    foreach ($body as $record) {
451 5
                        array_push($ret, base64_decode($record));
452 5
                    }
453 5
                }
454 6
            }
455 5
        }
456
457 5
        return $ret;
458
    }
459
460
    /**
461
     * Perform find and replace in template and return binary data.
462
     *
463
     * @param array  $findAndReplaceData Array of find and replace data
464
     * @param string $returnFormat       Return format
465
     * @param string $templateName       Template name
466
     * @param string $templateFilename   Template filename on local file system
467
     * @param array  $mergeSettings      Array of merge settings
468
     *
469
     * @throws InvalidArgumentException
470
     *
471
     * @return null|string
472
     */
473 11
    public function findAndReplace($findAndReplaceData, $returnFormat, $templateName = null, $templateFilename = null,
474
                                   $mergeSettings = [])
475
    {
476 11
        $ret = null;
477
478 11
        StaticValidator::execute($findAndReplaceData, 'TypeArray');
479 11
        StaticValidator::execute($returnFormat      , 'ReturnFormat');
480
481 10
        if (null !== $templateName) {
482 2
            StaticValidator::execute($templateName, 'TemplateName');
483 1
        }
484
485 9 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...
486 8
            StaticValidator::execute($templateFilename, 'TemplateExtension');
487 5
            StaticValidator::execute($templateFilename, 'FileExists');
488 4
            $templateFilename = realpath($templateFilename);
489 4
        }
490
491 5
        StaticValidator::execute($mergeSettings, 'TypeArray');
492
493 4
        $booleanToStringFilter = new BooleanToStringFilter();
494
495
        $query = [
496 4
            'returnFormat' => $returnFormat,
497 4
            'test'         => $booleanToStringFilter->filter($this->getTest()),
0 ignored issues
show
Documentation introduced by
$this->getTest() is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
498 4
        ];
499
500 4
        if (null !== $templateName) {
501 1
            $query['templateName'] = $templateName;
502 1
        }
503
504 4
        $findAndReplaceDataRc = [];
505 4
        foreach ($findAndReplaceData as $key => $value) {
506 4
            array_push($findAndReplaceDataRc, [$key, $value]);
507 4
        }
508 4
        unset($findAndReplaceData);
509
510
        $findAndReplaceBody = [
511 4
            'findAndReplaceData' => $findAndReplaceDataRc,
512 4
        ];
513
514 4 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...
515 3
            $template = file_get_contents($templateFilename);
516 3
            $template = base64_encode($template);
517 3
            $findAndReplaceBody['template'] = $template;
518 3
        }
519
520 4
        if (count($mergeSettings) > 0) {
521 4
            $findAndReplaceBody['mergeSettings'] = $this->assembleMergeSettings($mergeSettings);
522 2
        }
523
524 2
        $body = json_encode($findAndReplaceBody);
525
526
        $options = [
527 2
            RequestOptions::QUERY => $query,
528 2
            RequestOptions::BODY  => $body,
529 2
        ];
530
531 2
        $response = $this->request('POST', $this->uri('/document/findandreplace'), $options);
532
533 2
        if ($response instanceof Response) {
534 2
            if (200 === $response->getStatusCode()) {
535 2
                $body = (string) $response->getBody();
536 2
                $ret = base64_decode($body);
537 2
            }
538 2
        }
539
540 2
        return $ret;
541
    }
542
543
544
    /**
545
     * DELETE methods
546
     * =================================================================================================================
547
     */
548
549
    /**
550
     * Delete a template in template storage
551
     *
552
     * @param string $templateName Template name
553
     *
554
     * @throws InvalidArgumentException
555
     *
556
     * @return bool
557
     */
558 11
    public function deleteTemplate($templateName)
559
    {
560 11
        $ret = false;
561
562 11
        StaticValidator::execute($templateName, 'TemplateName');
563
564
        $query = [
565 10
            'templateName' => $templateName,
566 10
        ];
567
568
        $options = [
569 10
            RequestOptions::QUERY => $query,
570 10
        ];
571
572 10
        $response = $this->request('DELETE', $this->uri('/templates/delete'), $options);
573
574 9
        if ($response instanceof Response) {
575 9
            if (204 === $response->getStatusCode()) {
576 9
                $ret = true;
577 9
            }
578 9
        }
579
580 9
        return $ret;
581
    }
582
}