Passed
Push — master ( fbc447...748ca4 )
by Jonathan
18:21
created

PostTrait   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 330
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 18
eloc 87
dl 0
loc 330
c 0
b 0
f 0
ccs 90
cts 90
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A uploadTemplateFromBase64() 0 12 2
A findAndReplaceDocument() 0 37 4
A uploadTemplate() 0 11 1
A appendDocument() 0 22 2
A post() 0 20 2
A convertDocument() 0 17 1
B mergeDocument() 0 48 6
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
use TxTextControl\ReportingCloud\StatusCode\StatusCode;
23
24
/**
25
 * Trait PostTrait
26
 *
27
 * @package TxTextControl\ReportingCloud
28
 * @author  Jonathan Maron (@JonathanMaron)
29
 */
30
trait PostTrait
31
{
32
    /**
33
     * Abstract Methods
34
     * -----------------------------------------------------------------------------------------------------------------
35
     */
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 mixed|null|\Psr\Http\Message\ResponseInterface
54
     * @throws \TxTextControl\ReportingCloud\Exception\RuntimeException
55
     */
56
    abstract protected function request(string $method, string $uri, array $options): Response;
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 27
    public function uploadTemplateFromBase64(string $data, string $templateName): bool
119
    {
120 27
        Assert::assertBase64Data($data);
121 27
        Assert::assertTemplateName($templateName);
122
123
        $query = [
124 27
            'templateName' => $templateName,
125
        ];
126
127 27
        $result = $this->post('/templates/upload', $query, $data, StatusCode::CREATED);
128
129 27
        return (null === $result) ? true : false;
130
    }
131
132
    /**
133
     * Upload a template to template storage
134
     *
135
     * @param string $templateFilename Template name
136
     *
137
     * @return bool
138
     * @throws \TxTextControl\ReportingCloud\Exception\InvalidArgumentException
139
     */
140 39
    public function uploadTemplate(string $templateFilename): bool
141
    {
142 39
        Assert::assertTemplateExtension($templateFilename);
143 30
        Assert::filenameExists($templateFilename);
144
145 27
        $templateName = basename($templateFilename);
146
147 27
        $data = file_get_contents($templateFilename);
148 27
        $data = base64_encode($data);
149
150 27
        return $this->uploadTemplateFromBase64($data, $templateName);
151
    }
152
153
    /**
154
     * Convert a document on the local file system to a different format
155
     *
156
     * @param string $documentFilename Document filename
157
     * @param string $returnFormat     Return format
158
     *
159
     * @return string
160
     * @throws \TxTextControl\ReportingCloud\Exception\InvalidArgumentException
161
     */
162 18
    public function convertDocument(string $documentFilename, string $returnFormat): string
163
    {
164 18
        Assert::assertDocumentExtension($documentFilename);
165 9
        Assert::filenameExists($documentFilename);
166 6
        Assert::assertReturnFormat($returnFormat);
167
168
        $query = [
169 3
            'returnFormat' => $returnFormat,
170
        ];
171
172 3
        $data = file_get_contents($documentFilename);
173 3
        $data = base64_encode($data);
174
175 3
        $result = $this->post('/document/convert', $query, $data, StatusCode::OK);
176 3
        settype($result, 'string');
177
178 3
        return (string) base64_decode($result);
179
    }
180
181
    /**
182
     * Merge data into a template and return an array of binary data.
183
     * Each record in the array is the binary data of one document
184
     *
185
     * @param array       $mergeData        Array of merge data
186
     * @param string      $returnFormat     Return format
187
     * @param string|null $templateName     Template name
188
     * @param string|null $templateFilename Template filename on local file system
189
     * @param bool|null   $append           Append flag
190
     * @param array|null  $mergeSettings    Array of merge settings
191
     *
192
     * @return array
193
     * @throws \TxTextControl\ReportingCloud\Exception\InvalidArgumentException
194
     */
195 34
    public function mergeDocument(
196
        array $mergeData,
197
        string $returnFormat,
198
        ?string $templateName = null,
199
        ?string $templateFilename = null,
200
        ?bool $append = null,
201
        ?array $mergeSettings = null
202
    ): array {
203 34
        $ret = [];
204
205 34
        $query = [];
206 34
        $json  = [];
207
208 34
        Assert::isArray($mergeData);
209 34
        $json['mergeData'] = $mergeData;
210
211 34
        Assert::assertReturnFormat($returnFormat);
212 31
        $query['returnFormat'] = $returnFormat;
213
214 31
        if (null !== $templateName) {
215 6
            Assert::assertTemplateName($templateName);
216 3
            $query['templateName'] = $templateName;
217
        }
218
219 28
        if (null !== $templateFilename) {
220 25
            Assert::assertTemplateExtension($templateFilename);
221 16
            Assert::filenameExists($templateFilename);
222 13
            $data             = file_get_contents($templateFilename);
223 13
            $data             = base64_encode($data);
224 13
            $json['template'] = $data;
225
        }
226
227 16
        if (null !== $append) {
228 15
            Assert::boolean($append);
229 15
            $query['append'] = Filter::filterBooleanToString($append);
230
        }
231
232 16
        if (is_array($mergeSettings)) {
233 15
            $json['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
234
        }
235
236 7
        $result = $this->post('/document/merge', $query, $json, StatusCode::OK);
237
238 7
        if (is_array($result)) {
239 7
            $ret = array_map('base64_decode', $result);
240
        }
241
242 7
        return $ret;
243
    }
244
245
    /**
246
     * Combine documents to appending them, divided by a new section, paragraph or nothing
247
     *
248
     * @param array      $documentsData
249
     * @param string     $returnFormat
250
     * @param array|null $documentSettings
251
     *
252
     * @return string
253
     * @throws \TxTextControl\ReportingCloud\Exception\InvalidArgumentException
254
     */
255 3
    public function appendDocument(
256
        array $documentsData,
257
        string $returnFormat,
258
        ?array $documentSettings = null
259
    ): string {
260 3
        $query = [];
261 3
        $json  = [];
262
263 3
        Assert::isArray($documentsData);
264 3
        $json['documents'] = $this->buildDocumentsArray($documentsData);
265
266 3
        Assert::assertReturnFormat($returnFormat);
267 3
        $query['returnFormat'] = $returnFormat;
268
269 3
        if (is_array($documentSettings)) {
270 3
            $json['documentSettings'] = $this->buildDocumentSettingsArray($documentSettings);
271
        }
272
273 3
        $result = $this->post('/document/append', $query, $json, StatusCode::OK);
274 3
        settype($result, 'string');
275
276 3
        return (string) base64_decode($result);
277
    }
278
279
    /**
280
     * Perform find and replace in document and return binary data.
281
     *
282
     * @param array       $findAndReplaceData Array of find and replace data
283
     * @param string      $returnFormat       Return format
284
     * @param string|null $templateName       Template name
285
     * @param string|null $templateFilename   Template filename on local file system
286
     * @param array|null  $mergeSettings      Array of merge settings
287
     *
288
     * @return string
289
     * @throws \TxTextControl\ReportingCloud\Exception\InvalidArgumentException
290
     */
291 30
    public function findAndReplaceDocument(
292
        array $findAndReplaceData,
293
        string $returnFormat,
294
        ?string $templateName = null,
295
        ?string $templateFilename = null,
296
        ?array $mergeSettings = null
297
    ): string {
298 30
        $query = [];
299 30
        $json  = [];
300
301 30
        Assert::isArray($findAndReplaceData);
302 30
        $json['findAndReplaceData'] = $this->buildFindAndReplaceDataArray($findAndReplaceData);
303
304 30
        Assert::assertReturnFormat($returnFormat);
305 27
        $query['returnFormat'] = $returnFormat;
306
307 27
        if (null !== $templateName) {
308 6
            Assert::assertTemplateName($templateName);
309 3
            $query['templateName'] = $templateName;
310
        }
311
312 24
        if (null !== $templateFilename) {
313 21
            Assert::assertTemplateExtension($templateFilename);
314 12
            Assert::filenameExists($templateFilename);
315 9
            $data             = file_get_contents($templateFilename);
316 9
            $data             = base64_encode($data);
317 9
            $json['template'] = $data;
318
        }
319
320 12
        if (is_array($mergeSettings)) {
321 12
            $json['mergeSettings'] = $this->buildMergeSettingsArray($mergeSettings);
322
        }
323
324 6
        $result = $this->post('/document/findandreplace', $query, $json, StatusCode::OK);
325 6
        settype($result, 'string');
326
327 6
        return (string) base64_decode($result);
328
    }
329
330
    /**
331
     * Execute a POST request via REST client
332
     *
333
     * @param string       $uri        URI
334
     * @param array        $query      Query
335
     * @param string|array $json       JSON
336
     * @param int          $statusCode Required HTTP status code for response
337
     *
338
     * @return mixed|null
339
     */
340 40
    private function post(
341
        string $uri,
342
        ?array $query = null,
343
        $json = null,
344
        ?int $statusCode = null
345
    ) {
346 40
        $ret = '';
347
348
        $options = [
349 40
            RequestOptions::QUERY => $query,
350 40
            RequestOptions::JSON  => $json,
351
        ];
352
353 40
        $response = $this->request('POST', $this->uri($uri), $options);
354
355 40
        if ($statusCode === $response->getStatusCode()) {
356 40
            $ret = json_decode($response->getBody()->getContents(), true);
357
        }
358
359 40
        return $ret;
360
    }
361
}
362