Passed
Push — master ( e0a48b...50471a )
by Jonathan
16:31
created

PostTrait::getDocumentThumbnails()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 32
ccs 17
cts 17
cp 1
rs 9.7
c 0
b 0
f 0
cc 2
nc 2
nop 5
crap 2
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * ReportingCloud PHP SDK
6
 *
7
 * PHP SDK 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\RequestOptions;
18
use Psr\Http\Message\ResponseInterface;
19
use TxTextControl\ReportingCloud\Assert\Assert;
20
use TxTextControl\ReportingCloud\Exception\InvalidArgumentException;
21
use TxTextControl\ReportingCloud\Exception\RuntimeException;
22
use TxTextControl\ReportingCloud\Filter\Filter;
23
use TxTextControl\ReportingCloud\PropertyMap\AbstractPropertyMap as PropertyMap;
24
use TxTextControl\ReportingCloud\StatusCode\StatusCode;
25
use TxTextControl\ReportingCloud\Stdlib\FileUtils;
26
27
/**
28
 * Trait PostTrait
29
 *
30
 * @package TxTextControl\ReportingCloud
31
 * @author  Jonathan Maron (@JonathanMaron)
32
 */
33
trait PostTrait
34
{
35
    // <editor-fold desc="Abstract methods">
36
37
    /**
38
     * Construct URI with version number
39
     *
40
     * @param string $uri URI
41
     *
42
     * @return string
43
     */
44
    abstract protected function uri(string $uri): string;
45
46
    /**
47
     * Request the URI with options
48
     *
49
     * @param string $method  HTTP method
50
     * @param string $uri     URI
51
     * @param array  $options Options
52
     *
53
     * @return ResponseInterface
54
     * @throws RuntimeException
55
     */
56
    abstract protected function request(string $method, string $uri, array $options): ResponseInterface;
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
    // </editor-fold>
105
106
    // <editor-fold desc="Methods">
107
108
    /**
109
     * Upload a base64 encoded template to template storage
110
     *
111
     * @param string $data         Template encoded as base64
112
     * @param string $templateName Template name
113
     *
114
     * @return bool
115
     * @throws InvalidArgumentException
116
     */
117 36
    public function uploadTemplateFromBase64(string $data, string $templateName): bool
118
    {
119 36
        Assert::assertBase64Data($data);
120 36
        Assert::assertTemplateName($templateName);
121
122
        $query = [
123 36
            'templateName' => $templateName,
124
        ];
125
126 36
        $result = $this->post('/templates/upload', $query, $data, StatusCode::CREATED);
127
128 36
        return (null === $result) ? true : false;
129
    }
130
131
    /**
132
     * Upload a template to template storage
133
     *
134
     * @param string $templateFilename Template name
135
     *
136
     * @return bool
137
     * @throws InvalidArgumentException
138
     */
139 45
    public function uploadTemplate(string $templateFilename): bool
140
    {
141 45
        Assert::assertTemplateExtension($templateFilename);
142 36
        Assert::filenameExists($templateFilename);
143
144 33
        $templateName = basename($templateFilename);
145
146 33
        $data = FileUtils::read($templateFilename, true);
147
148 33
        return $this->uploadTemplateFromBase64($data, $templateName);
149
    }
150
151
    /**
152
     * Convert a document on the local file system to a different format
153
     *
154
     * @param string $documentFilename Document filename
155
     * @param string $returnFormat     Return format
156
     *
157
     * @return string
158
     * @throws InvalidArgumentException
159
     */
160 21
    public function convertDocument(string $documentFilename, string $returnFormat): string
161
    {
162 21
        Assert::assertDocumentExtension($documentFilename);
163 12
        Assert::filenameExists($documentFilename);
164 9
        Assert::assertReturnFormat($returnFormat);
165
166
        $query  = [
167 6
            'returnFormat' => $returnFormat,
168
        ];
169
170 6
        $data   = FileUtils::read($documentFilename, true);
171
172 6
        $result = (string) $this->post('/document/convert', $query, $data, StatusCode::OK);
173
174 6
        $ret    = (string) base64_decode($result);
175
176 6
        return $ret;
177
    }
178
179
    /**
180
     * Merge data into a template and return an array of binary data.
181
     * Each record in the array is the binary data of one document
182
     *
183
     * @param array       $mergeData        Array of merge data
184
     * @param string      $returnFormat     Return format
185
     * @param string|null $templateName     Template name
186
     * @param string|null $templateFilename Template filename on local file system
187
     * @param bool|null   $append           Append flag
188
     * @param array|null  $mergeSettings    Array of merge settings
189
     *
190
     * @return array
191
     * @throws InvalidArgumentException
192
     */
193 34
    public function mergeDocument(
194
        array $mergeData,
195
        string $returnFormat,
196
        ?string $templateName = null,
197
        ?string $templateFilename = null,
198
        ?bool $append = null,
199
        ?array $mergeSettings = null
200
    ): array {
201 34
        $ret = [];
202
203 34
        $query = [];
204 34
        $json  = [];
205
206 34
        Assert::isArray($mergeData);
207 34
        $json['mergeData'] = $mergeData;
208
209 34
        Assert::assertReturnFormat($returnFormat);
210 31
        $query['returnFormat'] = $returnFormat;
211
212 31
        if (null !== $templateName) {
213 6
            Assert::assertTemplateName($templateName);
214 3
            $query['templateName'] = $templateName;
215
        }
216
217 28
        if (null !== $templateFilename) {
218 25
            Assert::assertTemplateExtension($templateFilename);
219 16
            Assert::filenameExists($templateFilename);
220 13
            $json['template'] = FileUtils::read($templateFilename, true);
221
        }
222
223 16
        if (null !== $append) {
224 15
            Assert::boolean($append);
225 15
            $query['append'] = Filter::filterBooleanToString($append);
226
        }
227
228 16
        if (is_array($mergeSettings)) {
229 15
            $json['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
230
        }
231
232 7
        $result = $this->post('/document/merge', $query, $json, StatusCode::OK);
233
234 7
        if (is_array($result)) {
235 7
            $ret = array_map('base64_decode', $result);
236
        }
237
238 7
        return $ret;
239
    }
240
241
    /**
242
     * Combine documents to appending them, divided by a new section, paragraph or nothing
243
     *
244
     * @param array      $documentsData
245
     * @param string     $returnFormat
246
     * @param array|null $documentSettings
247
     *
248
     * @return string
249
     * @throws InvalidArgumentException
250
     */
251 3
    public function appendDocument(
252
        array $documentsData,
253
        string $returnFormat,
254
        ?array $documentSettings = null
255
    ): string {
256 3
        $query = [];
257 3
        $json  = [];
258
259 3
        Assert::isArray($documentsData);
260 3
        $json['documents'] = $this->buildDocumentsArray($documentsData);
261
262 3
        Assert::assertReturnFormat($returnFormat);
263 3
        $query['returnFormat'] = $returnFormat;
264
265 3
        if (is_array($documentSettings)) {
266 3
            $json['documentSettings'] = $this->buildDocumentSettingsArray($documentSettings);
267
        }
268
269 3
        $result = (string) $this->post('/document/append', $query, $json, StatusCode::OK);
270
271 3
        $ret    = (string) base64_decode($result);
272
273 3
        return $ret;
274
    }
275
276
    /**
277
     * Perform find and replace in document and return binary data.
278
     *
279
     * @param array       $findAndReplaceData Array of find and replace data
280
     * @param string      $returnFormat       Return format
281
     * @param string|null $templateName       Template name
282
     * @param string|null $templateFilename   Template filename on local file system
283
     * @param array|null  $mergeSettings      Array of merge settings
284
     *
285
     * @return string
286
     * @throws InvalidArgumentException
287
     */
288 30
    public function findAndReplaceDocument(
289
        array $findAndReplaceData,
290
        string $returnFormat,
291
        ?string $templateName = null,
292
        ?string $templateFilename = null,
293
        ?array $mergeSettings = null
294
    ): string {
295 30
        $query = [];
296 30
        $json  = [];
297
298 30
        Assert::isArray($findAndReplaceData);
299 30
        $json['findAndReplaceData'] = $this->buildFindAndReplaceDataArray($findAndReplaceData);
300
301 30
        Assert::assertReturnFormat($returnFormat);
302 27
        $query['returnFormat'] = $returnFormat;
303
304 27
        if (null !== $templateName) {
305 6
            Assert::assertTemplateName($templateName);
306 3
            $query['templateName'] = $templateName;
307
        }
308
309 24
        if (null !== $templateFilename) {
310 21
            Assert::assertTemplateExtension($templateFilename);
311 12
            Assert::filenameExists($templateFilename);
312 9
            $json['template'] = FileUtils::read($templateFilename, true);
313
        }
314
315 12
        if (is_array($mergeSettings)) {
316 12
            $json['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
317
        }
318
319 6
        $result = (string) $this->post('/document/findandreplace', $query, $json, StatusCode::OK);
320
321 6
        $ret    = (string) base64_decode($result);
322
323 6
        return $ret;
324
    }
325
326
    /**
327
     * Execute a POST request via REST client
328
     *
329
     * @param string     $uri        URI
330
     * @param array|null $query      Query
331
     * @param mixed|null $json       JSON
332
     * @param int|null   $statusCode Required HTTP status code for response
333
     *
334
     * @return mixed|null
335
     */
336 55
    private function post(
337
        string $uri,
338
        ?array $query = null,
339
        $json = null,
340
        ?int $statusCode = null
341
    ) {
342 55
        $ret = '';
343
344
        $options = [
345 55
            RequestOptions::QUERY => $query,
346 55
            RequestOptions::JSON  => $json,
347
        ];
348
349 55
        $response = $this->request('POST', $this->uri($uri), $options);
350
351 55
        if ($statusCode === $response->getStatusCode()) {
352 55
            $ret = json_decode($response->getBody()->getContents(), true);
353
        }
354
355 55
        return $ret;
356
    }
357
358
    /**
359
     * Generate a thumbnail image per page of specified document filename.
360
     * Return an array of binary data with each record containing one thumbnail.
361
     *
362
     * @param string $documentFilename Document filename
363
     * @param int    $zoomFactor       Zoom factor
364
     * @param int    $fromPage         From page
365
     * @param int    $toPage           To page
366
     * @param string $imageFormat      Image format
367
     *
368
     * @throws InvalidArgumentException
369
     * @return array
370
     */
371 3
    public function getDocumentThumbnails(
372
        string $documentFilename,
373
        int $zoomFactor,
374
        int $fromPage,
375
        int $toPage,
376
        string $imageFormat
377
    ): array {
378 3
        $ret = [];
379
380 3
        Assert::assertDocumentThumbnailExtension($documentFilename);
381 3
        Assert::filenameExists($documentFilename);
382 3
        Assert::assertZoomFactor($zoomFactor);
383 3
        Assert::assertPage($fromPage);
384 3
        Assert::assertPage($toPage);
385 3
        Assert::assertImageFormat($imageFormat);
386
387
        $query = [
388 3
            'zoomFactor'   => $zoomFactor,
389 3
            'fromPage'     => $fromPage,
390 3
            'toPage'       => $toPage,
391 3
            'imageFormat'  => $imageFormat,
392
        ];
393
394 3
        $data   = FileUtils::read($documentFilename, true);
395
396 3
        $result = $this->post('/document/thumbnails', $query, $data, StatusCode::OK);
397
398 3
        if (is_array($result)) {
399 3
            $ret = array_map('base64_decode', $result);
400
        }
401
402 3
        return $ret;
403
    }
404
405
    // </editor-fold>
406
}
407