Passed
Branch development-2.0 (6db025)
by Jonathan
04:33
created

PostTrait::mergeDocument()   B

Complexity

Conditions 9
Paths 48

Size

Total Lines 57
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 30
dl 0
loc 57
ccs 29
cts 29
cp 1
rs 8.0555
c 0
b 0
f 0
cc 9
nc 48
nop 6
crap 9

How to fix   Long Method   

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
declare(strict_types=1);
3
4
/**
5
 * ReportingCloud PHP Wrapper
6
 *
7
 * PHP wrapper for ReportingCloud Web API. Authored and supported by Text Control GmbH.
8
 *
9
 * @link      https://www.reporting.cloud to learn more about ReportingCloud
10
 * @link      https://github.com/TextControl/txtextcontrol-reportingcloud-php for the canonical source repository
11
 * @license   https://raw.githubusercontent.com/TextControl/txtextcontrol-reportingcloud-php/master/LICENSE.md
12
 * @copyright © 2019 Text Control GmbH
13
 */
14
15
namespace TxTextControl\ReportingCloud;
16
17
use GuzzleHttp\Psr7\Response;
18
use GuzzleHttp\RequestOptions;
19
use TxTextControl\ReportingCloud\Assert\Assert;
20
use TxTextControl\ReportingCloud\Filter\Filter;
21
use TxTextControl\ReportingCloud\PropertyMap\AbstractPropertyMap as PropertyMap;
22
23
/**
24
 * Trait PostTrait
25
 *
26
 * @package TxTextControl\ReportingCloud
27
 * @author  Jonathan Maron (@JonathanMaron)
28
 */
29
trait PostTrait
30
{
31
    /**
32
     * Abstract Methods
33
     * -----------------------------------------------------------------------------------------------------------------
34
     */
35
36
    /**
37
     * Construct URI with version number
38
     *
39
     * @param string $uri URI
40
     *
41
     * @return string
42
     */
43
    abstract protected function uri(string $uri): string;
44
45
    /**
46
     * Request the URI with options
47
     *
48
     * @param string $method  HTTP method
49
     * @param string $uri     URI
50
     * @param array  $options Options
51
     *
52
     * @return mixed|null|\Psr\Http\Message\ResponseInterface
53
     *
54
     * @throws RuntimeException
55
     */
56
    abstract protected function request(string $method, string $uri, array $options);
57
58
    /**
59
     * Using passed findAndReplaceData associative array (key-value), build array for backend (list of string arrays)
60
     *
61
     * @param array $array FindAndReplaceData array
62
     *
63
     * @return array
64
     */
65
    abstract protected function buildFindAndReplaceDataArray(array $array): array;
66
67
    /**
68
     * Using passed mergeSettings array, build array for backend
69
     *
70
     * @param array $array MergeSettings array
71
     *
72
     * @return array
73
     */
74
    abstract protected function buildMergeSettingsArray(array $array): array;
75
76
    /**
77
     * Using passed documentsData array, build array for backend
78
     *
79
     * @param array $array AppendDocument array
80
     *
81
     * @return array
82
     */
83
    abstract protected function buildDocumentsArray(array $array): array;
84
85
    /**
86
     * Using passed documentsSettings array, build array for backend
87
     *
88
     * @param array $array
89
     *
90
     * @return array
91
     */
92
    abstract protected function buildDocumentSettingsArray(array $array): array;
93
94
    /**
95
     * Using the passed propertyMap, recursively build array
96
     *
97
     * @param array       $array       Array
98
     * @param PropertyMap $propertyMap PropertyMap
99
     *
100
     * @return array
101
     */
102
    abstract protected function buildPropertyMapArray(array $array, PropertyMap $propertyMap): array;
103
104
    /**
105
     * POST Methods
106
     * -----------------------------------------------------------------------------------------------------------------
107
     */
108
109
    /**
110
     * Upload a base64 encoded template to template storage
111
     *
112
     * @param string $data         Template encoded as base64
113
     * @param string $templateName Template name
114
     *
115
     * @return bool
116
     * @throws TxTextControl\ReportingCloud\Exception\InvalidArgumentException
117
     */
118 9
    public function uploadTemplateFromBase64(string $data, string $templateName): bool
119
    {
120 9
        $ret = false;
121
122 9
        Assert::assertBase64Data($data);
123 9
        Assert::assertTemplateName($templateName);
124
125
        $options = [
126 9
            RequestOptions::QUERY => [
127 9
                'templateName' => $templateName,
128
            ],
129 9
            RequestOptions::JSON  => $data,
130
        ];
131
132 9
        $response = $this->request('POST', $this->uri('/templates/upload'), $options);
133
134 9
        if ($response instanceof Response && 201 === $response->getStatusCode()) {
135 9
            $ret = true;
136
        }
137
138 9
        return $ret;
139
    }
140
141
    /**
142
     * Upload a template to template storage
143
     *
144
     * @param string $templateFilename Template name
145
     *
146
     * @return bool
147
     * @throws TxTextControl\ReportingCloud\Exception\InvalidArgumentException
148
     */
149 13
    public function uploadTemplate(string $templateFilename): bool
150
    {
151 13
        Assert::assertTemplateExtension($templateFilename);
152 10
        Assert::filenameExists($templateFilename);
153
154 9
        $templateFilename = realpath($templateFilename);
155 9
        $templateName     = basename($templateFilename);
156
157 9
        $data = file_get_contents($templateFilename);
158 9
        $data = base64_encode($data);
159
160 9
        return $this->uploadTemplateFromBase64($data, $templateName);
161
    }
162
163
    /**
164
     * Convert a document on the local file system to a different format
165
     *
166
     * @param string $documentFilename Document filename
167
     * @param string $returnFormat     Return format
168
     *
169
     * @return string
170
     * @throws TxTextControl\ReportingCloud\Exception\InvalidArgumentException
171
     */
172 6
    public function convertDocument(string $documentFilename, string $returnFormat): string
173
    {
174 6
        $ret = '';
175
176 6
        Assert::assertDocumentExtension($documentFilename);
177 3
        Assert::filenameExists($documentFilename);
178 2
        Assert::assertReturnFormat($returnFormat);
179
180 1
        $documentFilename = realpath($documentFilename);
181
182 1
        $json = file_get_contents($documentFilename);
183 1
        $json = base64_encode($json);
184
185
        $options = [
186 1
            RequestOptions::QUERY => [
187 1
                'returnFormat' => $returnFormat,
188
            ],
189 1
            RequestOptions::JSON  => $json,
190
        ];
191
192 1
        $response = $this->request('POST', $this->uri('/document/convert'), $options);
193
194 1
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
195 1
            $ret = base64_decode($response->getBody()->getContents());
196
        }
197
198 1
        return $ret;
199
    }
200
201
    /**
202
     * Merge data into a template and return an array of binary data.
203
     * Each record in the array is the binary data of one document
204
     *
205
     * @param array       $mergeData        Array of merge data
206
     * @param string      $returnFormat     Return format
207
     * @param string|null $templateName     Template name
208
     * @param string|null $templateFilename Template filename on local file system
209
     * @param bool|null   $append           Append flag
210
     * @param array|null  $mergeSettings    Array of merge settings
211
     *
212
     * @return array
213
     * @throws TxTextControl\ReportingCloud\Exception\InvalidArgumentException
214
     */
215 12
    public function mergeDocument(
216
        array $mergeData,
217
        string $returnFormat,
218
        ?string $templateName = null,
219
        ?string $templateFilename = null,
220
        ?bool $append = null,
221
        ?array $mergeSettings = null
222
    ): array {
223
224 12
        $ret = [];
225
226 12
        $query = RequestOptions::QUERY;
227 12
        $json  = RequestOptions::JSON;
228
229
        $options = [
230 12
            $query => [],
231
            $json  => [],
232
        ];
233
234 12
        Assert::isArray($mergeData);
235 12
        $options[$json]['mergeData'] = $mergeData;
236
237 12
        Assert::assertReturnFormat($returnFormat);
238 11
        $options[$query]['returnFormat'] = $returnFormat;
239
240 11
        if (null !== $templateName) {
241 2
            Assert::assertTemplateName($templateName);
242 1
            $options[$query]['templateName'] = $templateName;
243
        }
244
245 10
        if (null !== $templateFilename) {
246 9
            Assert::assertTemplateExtension($templateFilename);
247 6
            Assert::filenameExists($templateFilename);
248 5
            $template                   = file_get_contents($templateFilename);
249 5
            $template                   = base64_encode($template);
250 5
            $options[$json]['template'] = $template;
251
        }
252
253 6
        if (null !== $append) {
254 5
            Assert::boolean($append);
255 5
            $options[$query]['append'] = Filter::filterBooleanToString($append);
256
        }
257
258 6
        if (is_array($mergeSettings)) {
259 5
            $options[$json]['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
260
        }
261
262 3
        $response = $this->request('POST', $this->uri('/document/merge'), $options);
263
264 3
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
265 3
            $body = json_decode($response->getBody()->getContents(), true);
266 3
            if (is_array($body) && count($body) > 0) {
267 3
                $ret = array_map('base64_decode', $body);
268
            }
269
        }
270
271 3
        return $ret;
272
    }
273
274
    /**
275
     * Combine documents to appending them, divided by a new section, paragraph or nothing
276
     *
277
     * @param array      $documentsData
278
     * @param string     $returnFormat
279
     * @param array|null $documentSettings
280
     *
281
     * @return string
282
     * @throws TxTextControl\ReportingCloud\Exception\InvalidArgumentException
283
     */
284 1
    public function appendDocument(
285
        array $documentsData,
286
        string $returnFormat,
287
        ?array $documentSettings = null
288
    ): string
289
    {
290 1
        $ret = '';
291
292 1
        Assert::isArray($documentsData);
293 1
        Assert::assertReturnFormat($returnFormat);
294
295 1
        if (null !== $documentSettings) {
296 1
            Assert::isArray($documentSettings);
297
        }
298
299
        $query = [
300 1
            'returnFormat' => $returnFormat,
301
        ];
302
303
        $json = [
304 1
            'documents' => $this->buildDocumentsArray($documentsData),
305
        ];
306
307 1
        if (is_array($documentSettings) && count($documentSettings) > 0) {
308 1
            $json['documentSettings'] = $this->buildDocumentSettingsArray($documentSettings);
309
        }
310
311
        $options = [
312 1
            RequestOptions::QUERY => $query,
313 1
            RequestOptions::JSON  => $json,
314
        ];
315
316 1
        $response = $this->request('POST', $this->uri('/document/append'), $options);
317
318 1
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
319 1
            $ret = base64_decode($response->getBody()->getContents());
320
        }
321
322 1
        return $ret;
323
    }
324
325
    /**
326
     * Perform find and replace in document and return binary data.
327
     *
328
     * @param array       $findAndReplaceData Array of find and replace data
329
     * @param string      $returnFormat       Return format
330
     * @param string|null $templateName       Template name
331
     * @param string|null $templateFilename   Template filename on local file system
332
     * @param array|null  $mergeSettings      Array of merge settings
333
     *
334
     * @return string
335
     * @throws TxTextControl\ReportingCloud\Exception\InvalidArgumentException
336
     */
337 10
    public function findAndReplaceDocument(
338
        array $findAndReplaceData,
339
        string $returnFormat,
340
        ?string $templateName = null,
341
        ?string $templateFilename = null,
342
        ?array $mergeSettings = null
343
    ): string {
344
345 10
        $ret = '';
346
347 10
        Assert::isArray($findAndReplaceData);
348 10
        Assert::assertReturnFormat($returnFormat);
349
350 9
        if (null !== $templateName) {
351 2
            Assert::assertTemplateName($templateName);
352
        }
353
354 8
        if (null !== $templateFilename) {
355 7
            Assert::assertTemplateExtension($templateFilename);
356 4
            Assert::filenameExists($templateFilename);
357 3
            $templateFilename = realpath($templateFilename);
358
        }
359
360 4
        if (null !== $mergeSettings) {
361 4
            Assert::isArray($mergeSettings);
362
        }
363
364
        $query = [
365 4
            'returnFormat' => $returnFormat,
366
        ];
367
368 4
        if (null !== $templateName) {
369 1
            $query['templateName'] = $templateName;
370
        }
371
372
        $json = [
373 4
            'findAndReplaceData' => $this->buildFindAndReplaceDataArray($findAndReplaceData),
374
        ];
375
376 4
        if (null !== $templateFilename) {
377 3
            $template         = file_get_contents($templateFilename);
378 3
            $template         = base64_encode($template);
379 3
            $json['template'] = $template;
380
        }
381
382 4
        if (is_array($mergeSettings) && count($mergeSettings) > 0) {
383 4
            $json['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
384
        }
385
386
        $options = [
387 2
            RequestOptions::QUERY => $query,
388 2
            RequestOptions::JSON  => $json,
389
        ];
390
391 2
        $response = $this->request('POST', $this->uri('/document/findandreplace'), $options);
392
393 2
        if ($response instanceof Response && 200 === $response->getStatusCode()) {
394 2
            $ret = base64_decode($response->getBody()->getContents());
395
        }
396
397 2
        return $ret;
398
    }
399
}
400