Completed
Push — master ( 973b2b...b10734 )
by Jonathan
04:46
created

ReportingCloud::mergeDocument()   C

Complexity

Conditions 11
Paths 192

Size

Total Lines 67
Code Lines 39

Duplication

Lines 13
Ratio 19.4 %

Code Coverage

Tests 46
CRAP Score 11

Importance

Changes 7
Bugs 0 Features 0
Metric Value
c 7
b 0
f 0
dl 13
loc 67
ccs 46
cts 46
cp 1
rs 5.4917
cc 11
eloc 39
nc 192
nop 6
crap 11

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\BooleanToString as BooleanToStringFilter;
19
use TxTextControl\ReportingCloud\Filter\DateTimeToTimestamp as DateTimeToTimestampFilter;
20
use TxTextControl\ReportingCloud\PropertyMap\AccountSettings as AccountSettingsPropertyMap;
21
use TxTextControl\ReportingCloud\PropertyMap\TemplateInfo as TemplateInfoPropertyMap;
22
use TxTextControl\ReportingCloud\PropertyMap\TemplateList as TemplateListPropertyMap;
23
use TxTextControl\ReportingCloud\Validator\StaticValidator;
24
25
/**
26
 * ReportingCloud
27
 *
28
 * @package TxTextControl\ReportingCloud
29
 * @author  Jonathan Maron (@JonathanMaron)
30
 */
31
class ReportingCloud extends AbstractReportingCloud
32
{
33
    use ReportingCloudTrait;
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->buildPropertyMapArray($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 View Code Duplication
        if (is_array($records) && count($records) > 0) {
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...
105 1
            $ret = array_map('base64_decode', $records);
106 1
        }
107
108 1
        return $ret;
109
    }
110
111
    /**
112
     * Return the number of templates in template storage
113
     *
114
     * @return integer|null
115
     */
116 1
    public function getTemplateCount()
117
    {
118 1
        return $this->get('/templates/count');
119
    }
120
121
    /**
122
     * Return an array properties for the templates in template storage
123
     *
124
     * @return array|null
125
     */
126 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...
127
    {
128 1
        $ret = null;
129
130 1
        $propertyMap = new TemplateListPropertyMap();
131 1
        $filter      = new DateTimeToTimestampFilter();
132
133 1
        $records = $this->get('/templates/list');
134
135 1
        if (is_array($records) && count($records) > 0) {
136 1
            $ret = $this->buildPropertyMapArray($records, $propertyMap);
137
            array_walk($ret, function (&$record) use ($filter) {
138 1
                $key = 'modified';
139 1
                if (isset($record[$key])) {
140 1
                    $filter->filter($record[$key]);
141 1
                }
142 1
            });
143 1
        }
144
145 1
        return $ret;
146
    }
147
148
    /**
149
     * Return the number of pages in a template in template storage
150
     *
151
     * @param string $templateName Template name
152
     *
153
     * @throws InvalidArgumentException
154
     *
155
     * @return bool
156
     */
157 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...
158
    {
159 2
        StaticValidator::execute($templateName, 'TemplateName');
160
161
        $query = [
162 1
            'templateName' => $templateName,
163 1
        ];
164
165 1
        return (integer) $this->get('/templates/pagecount', $query);
166
    }
167
168
    /**
169
     * Return true, if the template exists in template storage
170
     *
171
     * @param string $templateName Template name
172
     *
173
     * @throws InvalidArgumentException
174
     *
175
     * @return bool
176
     */
177 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...
178
    {
179 2
        StaticValidator::execute($templateName, 'TemplateName');
180
181
        $query = [
182 1
            'templateName' => $templateName,
183 1
        ];
184
185 1
        return (boolean) $this->get('/templates/exists', $query);
186
    }
187
188
    /**
189
     * Return an array properties for the ReportingCloud account
190
     *
191
     * @return array|null
192
     */
193 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...
194
    {
195 3
        $ret = null;
196
197 3
        $propertyMap = new AccountSettingsPropertyMap();
198 3
        $filter      = new DateTimeToTimestampFilter();
199
200 3
        $records = $this->get('/account/settings');
201
202 3
        if (is_array($records) && count($records) > 0) {
203 3
            $ret = $this->buildPropertyMapArray($records, $propertyMap);
204 3
            array_walk($ret, function (&$record) use ($filter) {
205 3
                $key = 'valid_until';
206 3
                if (isset($record[$key])) {
207
                    $filter->filter($record[$key]);
208
                }
209 3
            });
210 3
        }
211
212 3
        return $ret;
213
    }
214
215
    /**
216
     * Download the binary data of a template from template storage
217
     *
218
     * @param string $templateName Template name
219
     *
220
     * @throws InvalidArgumentException
221
     *
222
     * @return null|resource
223
     */
224 2
    public function downloadTemplate($templateName)
225
    {
226 2
        $ret = null;
227
228 2
        StaticValidator::execute($templateName, 'TemplateName');
229
230
        $query = [
231 1
            'templateName' => $templateName,
232 1
        ];
233
234 1
        $data = $this->get('/templates/download', $query);
235
236 1
        if (null !== $data) {
237 1
            $ret = base64_decode($data);
238 1
        }
239
240 1
        return $ret;
241
    }
242
243
    /**
244
     * Execute a GET request via REST client
245
     *
246
     * @param string $uri   URI
247
     * @param array  $query Query
248
     *
249
     * @return mixed|null
250
     */
251 10
    protected function get($uri, $query = [])
252
    {
253 10
        $ret = null;
254
255
        $options = [
256 10
            RequestOptions::QUERY => $query,
257 10
        ];
258
259 10
        $response = $this->request('GET', $this->uri($uri), $options);
260
261 10
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
262 10
            $body = (string) $response->getBody();
263 10
            $ret  = json_decode($body, true);
264 10
        }
265
266 10
        return $ret;
267
    }
268
269
270
    /**
271
     * POST methods
272
     * =================================================================================================================
273
     */
274
275
    /**
276
     * Upload a template to template storage
277
     *
278
     * @param string $templateFilename Template name
279
     *
280
     * @throws InvalidArgumentException
281
     *
282
     * @return bool
283
     */
284 13 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...
285
    {
286 13
        $ret = false;
287
288 13
        StaticValidator::execute($templateFilename, 'TemplateExtension');
289 10
        StaticValidator::execute($templateFilename, 'FileExists');
290
291 9
        $templateFilename = realpath($templateFilename);
292 9
        $templateName     = basename($templateFilename);
293
294
        $query = [
295 9
            'templateName' => $templateName,
296 9
        ];
297
298 9
        $body = file_get_contents($templateFilename);
299 9
        $body = base64_encode($body);
300 9
        $body = json_encode($body);
301
302
        $options = [
303 9
            RequestOptions::QUERY => $query,
304 9
            RequestOptions::BODY  => $body,
305 9
        ];
306
307 9
        $response = $this->request('POST', $this->uri('/templates/upload'), $options);
308
309 9
        if ($response instanceof Response && 201 === $response->getStatusCode()) {
310 9
            $ret = true;
311 9
        }
312
313 9
        return $ret;
314
    }
315
316
    /**
317
     * Convert a document on the local file system to a different format
318
     *
319
     * @param string $documentFilename Document filename
320
     * @param string $returnFormat     Return format
321
     *
322
     * @throws InvalidArgumentException
323
     *
324
     * @return null|resource
325
     */
326 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...
327
    {
328 6
        $ret = null;
329
330 6
        StaticValidator::execute($documentFilename, 'DocumentExtension');
331 3
        StaticValidator::execute($documentFilename, 'FileExists');
332 2
        StaticValidator::execute($returnFormat    , 'ReturnFormat');
333
334
        $query = [
335 1
            'returnFormat' => $returnFormat,
336 1
        ];
337
338 1
        $documentFilename = realpath($documentFilename);
339
340 1
        $body = file_get_contents($documentFilename);
341 1
        $body = base64_encode($body);
342 1
        $body = json_encode($body);
343
344
        $options = [
345 1
            RequestOptions::QUERY => $query,
346 1
            RequestOptions::BODY  => $body,
347 1
        ];
348
349 1
        $response = $this->request('POST', $this->uri('/document/convert'), $options);
350
351 1
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
352 1
            $body = (string) $response->getBody();
353 1
            $ret  = base64_decode($body);
354 1
        }
355
356 1
        return $ret;
357
    }
358
359
    /**
360
     * Merge data into a template and return an array of binary data.
361
     * Each record in the array is the binary data of one document
362
     *
363
     * @param array   $mergeData        Array of merge data
364
     * @param string  $returnFormat     Return format
365
     * @param string  $templateName     Template name
366
     * @param string  $templateFilename Template filename on local file system
367
     * @param boolean $append           Append flag
368
     * @param array   $mergeSettings    Array of merge settings
369
     *
370
     * @throws InvalidArgumentException
371
     *
372
     * @return null|string
373
     */
374 15
    public function mergeDocument($mergeData, $returnFormat, $templateName = null, $templateFilename = null,
375
                                    $append = null, $mergeSettings = [])
376
    {
377 15
        $ret = null;
378
379 15
        StaticValidator::execute($mergeData   , 'TypeArray');
380 15
        StaticValidator::execute($returnFormat, 'ReturnFormat');
381
382 14
        if (null !== $templateName) {
383 2
            StaticValidator::execute($templateName, 'TemplateName');
384 1
        }
385
386 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...
387 12
            StaticValidator::execute($templateFilename, 'TemplateExtension');
388 9
            StaticValidator::execute($templateFilename, 'FileExists');
389 8
            $templateFilename = realpath($templateFilename);
390 8
        }
391
392 9
        if (null !== $append) {
393 6
            $filter = new BooleanToStringFilter();
394 6
            $append = $filter->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...
395 5
        }
396
397 8
        StaticValidator::execute($mergeSettings, 'TypeArray');
398
399
        $query = [
400 7
            'returnFormat' => $returnFormat,
401 7
            'append'       => $append,
402 7
        ];
403
404 7
        if (null !== $templateName) {
405 1
            $query['templateName'] = $templateName;
406 1
        }
407
408
        $body = [
409 7
            'mergeData' => $mergeData,
410 7
        ];
411
412 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...
413 6
            $template = file_get_contents($templateFilename);
414 6
            $template = base64_encode($template);
415 6
            $body['template'] = $template;
416 6
        }
417
418 7
        if (count($mergeSettings) > 0) {
419 4
            $body['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
420 2
        }
421
422 5
        $body = json_encode($body);
423
424
        $options = [
425 5
            RequestOptions::QUERY => $query,
426 5
            RequestOptions::BODY  => $body,
427 5
        ];
428
429 5
        $response = $this->request('POST', $this->uri('/document/merge'), $options);
430
431 5
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
432 5
            $body = (string) $response->getBody();
433 5
            $body = json_decode($body, true);
434 5 View Code Duplication
            if (is_array($body) && count($body) > 0) {
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...
435 5
                $ret = array_map('base64_decode', $body);
436 5
            }
437 5
        }
438
439 5
        return $ret;
440
    }
441
442
    /**
443
     * Perform find and replace in template and return binary data.
444
     *
445
     * @param array  $findAndReplaceData Array of find and replace data
446
     * @param string $returnFormat       Return format
447
     * @param string $templateName       Template name
448
     * @param string $templateFilename   Template filename on local file system
449
     * @param array  $mergeSettings      Array of merge settings
450
     *
451
     * @throws InvalidArgumentException
452
     *
453
     * @return null|string
454
     */
455 11
    public function findAndReplace($findAndReplaceData, $returnFormat, $templateName = null, $templateFilename = null,
456
                                   $mergeSettings = [])
457
    {
458 11
        $ret = null;
459
460 11
        StaticValidator::execute($findAndReplaceData, 'TypeArray');
461 11
        StaticValidator::execute($returnFormat      , 'ReturnFormat');
462
463 10
        if (null !== $templateName) {
464 2
            StaticValidator::execute($templateName, 'TemplateName');
465 1
        }
466
467 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...
468 8
            StaticValidator::execute($templateFilename, 'TemplateExtension');
469 5
            StaticValidator::execute($templateFilename, 'FileExists');
470 4
            $templateFilename = realpath($templateFilename);
471 4
        }
472
473 5
        StaticValidator::execute($mergeSettings, 'TypeArray');
474
475
        $query = [
476 4
            'returnFormat' => $returnFormat,
477 4
        ];
478
479 4
        if (null !== $templateName) {
480 1
            $query['templateName'] = $templateName;
481 1
        }
482
483
        $body = [
484 4
            'findAndReplaceData' => $this->buildFindAndReplaceDataArray($findAndReplaceData),
485 4
        ];
486
487 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...
488 3
            $template = file_get_contents($templateFilename);
489 3
            $template = base64_encode($template);
490 3
            $body['template'] = $template;
491 3
        }
492
493 4
        if (count($mergeSettings) > 0) {
494 4
            $body['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
495 2
        }
496
497 2
        $body = json_encode($body);
498
499
        $options = [
500 2
            RequestOptions::QUERY => $query,
501 2
            RequestOptions::BODY  => $body,
502 2
        ];
503
504 2
        $response = $this->request('POST', $this->uri('/document/findandreplace'), $options);
505
506 2
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
507 2
            $body = (string) $response->getBody();
508 2
            $ret  = base64_decode($body);
509 2
        }
510
511 2
        return $ret;
512
    }
513
514
515
    /**
516
     * DELETE methods
517
     * =================================================================================================================
518
     */
519
520
    /**
521
     * Delete a template in template storage
522
     *
523
     * @param string $templateName Template name
524
     *
525
     * @throws InvalidArgumentException
526
     *
527
     * @return bool
528
     */
529 11
    public function deleteTemplate($templateName)
530
    {
531 11
        $ret = false;
532
533 11
        StaticValidator::execute($templateName, 'TemplateName');
534
535
        $query = [
536 10
            'templateName' => $templateName,
537 10
        ];
538
539
        $options = [
540 10
            RequestOptions::QUERY => $query,
541 10
        ];
542
543 10
        $response = $this->request('DELETE', $this->uri('/templates/delete'), $options);
544
545 9
        if ($response instanceof Response && 204 === $response->getStatusCode()) {
546 9
            $ret = true;
547 9
        }
548
549 9
        return $ret;
550
    }
551
}