Passed
Push — master ( b8e2b8...5d024f )
by Jonathan
17:35
created

GetTrait::getTemplateList()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 11
c 3
b 0
f 0
dl 0
loc 20
ccs 13
cts 13
cp 1
rs 9.9
cc 3
nc 2
nop 0
crap 3
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://git.io/Jejj2 for the canonical source repository
11
 * @license   https://git.io/Jejjr
12
 * @copyright © 2021 Text Control GmbH
13
 */
14
15
namespace TxTextControl\ReportingCloud;
16
17
use Ctw\Http\HttpMethod;
18
use Ctw\Http\HttpStatus;
19
use GuzzleHttp\RequestOptions;
20
use Psr\Http\Message\ResponseInterface;
21
use TxTextControl\ReportingCloud\Assert\Assert;
22
use TxTextControl\ReportingCloud\Exception\InvalidArgumentException;
23
use TxTextControl\ReportingCloud\Exception\RuntimeException;
24
use TxTextControl\ReportingCloud\Filter\Filter;
25
use TxTextControl\ReportingCloud\PropertyMap\AbstractPropertyMap as PropertyMap;
26
use TxTextControl\ReportingCloud\PropertyMap\AccountSettings as AccountSettingsPropertyMap;
27
use TxTextControl\ReportingCloud\PropertyMap\ApiKey as ApiKeyPropertyMap;
28
use TxTextControl\ReportingCloud\PropertyMap\IncorrectWord as IncorrectWordMap;
29
use TxTextControl\ReportingCloud\PropertyMap\TemplateInfo as TemplateInfoPropertyMap;
30
use TxTextControl\ReportingCloud\PropertyMap\TemplateList as TemplateListPropertyMap;
31
32
/**
33
 * Trait GetTrait
34
 *
35
 * @package TxTextControl\ReportingCloud
36
 * @author  Jonathan Maron (@JonathanMaron)
37
 */
38
trait GetTrait
39
{
40
    // <editor-fold desc="Abstract methods">
41
42
    /**
43
     * Construct URI with version number
44
     *
45
     * @param string $uri URI
46
     *
47
     * @return string
48
     */
49
    abstract protected function uri(string $uri): string;
50
51
    /**
52
     * Request the URI with options
53
     *
54
     * @param string $method  HTTP method
55
     * @param string $uri     URI
56
     * @param array  $options Options
57
     *
58
     * @return ResponseInterface
59
     * @throws RuntimeException
60
     */
61
    abstract protected function request(string $method, string $uri, array $options): ResponseInterface;
62
63
    /**
64
     * Using the passed propertyMap, recursively build array
65
     *
66
     * @param array       $array       Array
67
     * @param PropertyMap $propertyMap PropertyMap
68
     *
69
     * @return array
70
     */
71
    abstract protected function buildPropertyMapArray(array $array, PropertyMap $propertyMap): array;
72
73
    // </editor-fold>
74
75
    // <editor-fold desc="Methods">
76
77
    /**
78
     * Return an associative array of API keys associated with the Reporting Cloud account
79
     *
80
     * @return array<int, array<int|string, array|bool|int|string>>
81
     */
82 10
    public function getApiKeys(): array
83
    {
84 10
        $ret = [];
85
86 10
        $propertyMap = new ApiKeyPropertyMap();
87
88 10
        $result = $this->get('/account/apikeys', [], '', HttpStatus::STATUS_OK);
89
90 10
        if (is_array($result)) {
91 10
            foreach ($result as $record) {
92 10
                if (!is_array($record)) {
93
                    continue;
94
                }
95 10
                $ret[] = $this->buildPropertyMapArray($record, $propertyMap);
96
            }
97
        }
98
99 10
        return $ret;
100
    }
101
102
    /**
103
     * Check a corpus of text for spelling errors.
104
     *
105
     * Return an array of misspelled words, if spelling errors are found in the corpus of text.
106
     *
107
     * Return an empty array, if no misspelled words are found in the corpus of text.
108
     *
109
     * @param string $text     Corpus of text that should be spell checked
110
     * @param string $language Language of specified text
111
     *
112
     * @return array<int|string, array|bool|int|string>
113
     * @throws InvalidArgumentException
114
     */
115 2
    public function proofingCheck(string $text, string $language): array
116
    {
117 2
        $ret = [];
118
119 2
        Assert::assertLanguage($language);
120
121 2
        $propertyMap = new IncorrectWordMap();
122
123 1
        $query = [
124 2
            'text'     => $text,
125 2
            'language' => $language,
126
        ];
127
128 2
        $result = $this->get('/proofing/check', $query, '', HttpStatus::STATUS_OK);
129
130 2
        if (is_array($result)) {
131 2
            $ret = $this->buildPropertyMapArray($result, $propertyMap);
132
        }
133
134 2
        return $ret;
135
    }
136
137
    /**
138
     * Return an array of available dictionaries on the Reporting Cloud service
139
     *
140
     * @return array<int, string>
141
     */
142 2
    public function getAvailableDictionaries(): array
143
    {
144 2
        $ret = [];
145
146 2
        $result = $this->get('/proofing/availabledictionaries', [], '', HttpStatus::STATUS_OK);
147
148 2
        if (is_array($result)) {
149 2
            $ret = array_map('trim', $result);
150
        }
151
152 2
        return $ret;
153
    }
154
155
    /**
156
     * Return an array of suggestions for a misspelled word
157
     *
158
     * @param string $word     Word that should be spell checked
159
     * @param string $language Language of specified text
160
     * @param int    $max      Maximum number of suggestions to return
161
     *
162
     * @return array<int, string>
163
     * @throws InvalidArgumentException
164
     */
165 2
    public function getProofingSuggestions(string $word, string $language, int $max = 10): array
166
    {
167 2
        $ret = [];
168
169 2
        Assert::assertLanguage($language);
170
171 1
        $query = [
172 2
            'word'     => $word,
173 2
            'language' => $language,
174 2
            'max'      => $max,
175
        ];
176
177 2
        $result = $this->get('/proofing/suggestions', $query, '', HttpStatus::STATUS_OK);
178
179 2
        if (is_array($result)) {
180 2
            $ret = array_map('trim', $result);
181
        }
182
183 2
        return $ret;
184
    }
185
186
    /**
187
     * Return an array of merge blocks and merge fields in a template file in template storage
188
     *
189
     * @param string $templateName Template name
190
     *
191
     * @return array<int|string, array|bool|int|string>
192
     * @throws InvalidArgumentException
193
     */
194 2
    public function getTemplateInfo(string $templateName): array
195
    {
196 2
        $ret = [];
197
198 2
        $propertyMap = new TemplateInfoPropertyMap();
199
200 2
        Assert::assertTemplateName($templateName);
201
202 1
        $query = [
203 2
            'templateName' => $templateName,
204
        ];
205
206 2
        $result = $this->get('/templates/info', $query, '', HttpStatus::STATUS_OK);
207
208 2
        if (is_array($result)) {
209 2
            $ret = $this->buildPropertyMapArray($result, $propertyMap);
210
        }
211
212 2
        return $ret;
213
    }
214
215
    /**
216
     * Generate a thumbnail image per page of specified template in template storage.
217
     * Return an array of binary data with each record containing one thumbnail.
218
     *
219
     * @param string $templateName Template name
220
     * @param int    $zoomFactor   Zoom factor
221
     * @param int    $fromPage     From page
222
     * @param int    $toPage       To page
223
     * @param string $imageFormat  Image format
224
     *
225
     * @throws InvalidArgumentException
226
     * @return array<int, string>
227
     */
228 12
    public function getTemplateThumbnails(
229
        string $templateName,
230
        int $zoomFactor,
231
        int $fromPage,
232
        int $toPage,
233
        string $imageFormat
234
    ): array {
235
236 12
        Assert::assertTemplateName($templateName);
237 10
        Assert::assertZoomFactor($zoomFactor);
238 8
        Assert::assertPage($fromPage);
239 6
        Assert::assertPage($toPage);
240 4
        Assert::assertImageFormat($imageFormat);
241
242 1
        $query = [
243 2
            'templateName' => $templateName,
244 2
            'zoomFactor'   => $zoomFactor,
245 2
            'fromPage'     => $fromPage,
246 2
            'toPage'       => $toPage,
247 2
            'imageFormat'  => $imageFormat,
248
        ];
249
250 2
        $result = $this->get('/templates/thumbnails', $query, '', HttpStatus::STATUS_OK);
251
252 2
        if (is_array($result)) {
253 2
            foreach ($result as $key => $value) {
254 2
                $value = base64_decode($value, true);
255 2
                assert(is_string($value));
256 2
                $result[$key] = $value;
257
            }
258
        }
259
260 2
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result could return the type string which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
261
    }
262
263
    /**
264
     * Return the number of templates in template storage
265
     *
266
     * @return int
267
     */
268 2
    public function getTemplateCount(): int
269
    {
270 2
        return (int) $this->get('/templates/count', [], '', HttpStatus::STATUS_OK);
271
    }
272
273
    /**
274
     * Return an array properties for the templates in template storage
275
     *
276
     * @return array<int|string, array|bool|int|string>
277
     */
278 4
    public function getTemplateList(): array
279
    {
280 4
        $ret = [];
281
282 4
        $propertyMap = new TemplateListPropertyMap();
283
284 4
        $result = $this->get('/templates/list', [], '', HttpStatus::STATUS_OK);
285
286 4
        if (is_array($result)) {
287 4
            $ret = $this->buildPropertyMapArray($result, $propertyMap);
288 4
            array_walk($ret, function (array &$record): void {
289 4
                $key = 'modified';
290 4
                if (isset($record[$key])) {
291 4
                    Assert::assertDateTime($record[$key]);
292 4
                    $record[$key] = Filter::filterDateTimeToTimestamp($record[$key]);
293
                }
294 4
            });
295
        }
296
297 4
        return $ret;
298
    }
299
300
    /**
301
     * Return the number of pages in a template in template storage
302
     *
303
     * @param string $templateName Template name
304
     *
305
     * @return int
306
     * @throws InvalidArgumentException
307
     */
308 4
    public function getTemplatePageCount(string $templateName): int
309
    {
310 4
        Assert::assertTemplateName($templateName);
311
312 1
        $query = [
313 2
            'templateName' => $templateName,
314
        ];
315
316 2
        return (int) $this->get('/templates/pagecount', $query, '', HttpStatus::STATUS_OK);
317
    }
318
319
    /**
320
     * Return true, if the template exists in template storage
321
     *
322
     * @param string $templateName Template name
323
     *
324
     * @return bool
325
     * @throws InvalidArgumentException
326
     */
327 4
    public function templateExists(string $templateName): bool
328
    {
329 4
        Assert::assertTemplateName($templateName);
330
331 1
        $query = [
332 2
            'templateName' => $templateName,
333
        ];
334
335 2
        return (bool) $this->get('/templates/exists', $query, '', HttpStatus::STATUS_OK);
336
    }
337
338
    /**
339
     * Return an array of available fonts on the Reporting Cloud service
340
     *
341
     * @return array<int, string>
342
     */
343 6
    public function getFontList(): array
344
    {
345 6
        $ret = [];
346
347 6
        $result = $this->get('/fonts/list', [], '', HttpStatus::STATUS_OK);
348
349 4
        if (is_array($result)) {
350 4
            $ret = array_map('trim', $result);
351
        }
352
353 4
        return $ret;
354
    }
355
356
    /**
357
     * Return an array properties for the ReportingCloud account
358
     *
359
     * @return array<int|string, array|bool|int|string>
360
     * @throws InvalidArgumentException
361
     */
362 2
    public function getAccountSettings(): array
363
    {
364 2
        $ret = [];
365
366 2
        $propertyMap = new AccountSettingsPropertyMap();
367
368 2
        $result = $this->get('/account/settings', [], '', HttpStatus::STATUS_OK);
369
370 2
        if (is_array($result)) {
371 2
            $ret = $this->buildPropertyMapArray($result, $propertyMap);
372 2
            $key = 'valid_until';
373 2
            if (isset($ret[$key]) && is_string($ret[$key])) {
374 2
                Assert::assertDateTime($ret[$key]);
375 2
                $ret[$key] = Filter::filterDateTimeToTimestamp($ret[$key]);
376
            }
377
        }
378
379 2
        return $ret;
380
    }
381
382
    /**
383
     * Download the binary data of a template from template storage
384
     *
385
     * @param string $templateName Template name
386
     *
387
     * @return string
388
     * @throws InvalidArgumentException
389
     */
390 4
    public function downloadTemplate(string $templateName): string
391
    {
392 4
        Assert::assertTemplateName($templateName);
393
394 1
        $query = [
395 2
            'templateName' => $templateName,
396
        ];
397
398 2
        $result = (string) $this->get('/templates/download', $query, '', HttpStatus::STATUS_OK);
399
400 2
        if (strlen($result) > 0) {
401 2
            $decoded = base64_decode($result, true);
402 2
            if (is_string($decoded)) {
0 ignored issues
show
introduced by
The condition is_string($decoded) is always true.
Loading history...
403 2
                $result = $decoded;
404
            }
405
        }
406
407 2
        return $result;
408
    }
409
410
    /**
411
     * Execute a GET request via REST client
412
     *
413
     * @param string                    $uri        URI
414
     * @param array<string, int|string> $query      Query
415
     * @param mixed                     $json       JSON
416
     * @param int                       $statusCode Required HTTP status code for response
417
     *
418
     * @return mixed
419
     */
420 38
    private function get(
421
        string $uri,
422
        array $query = [],
423
        $json = '',
424
        int $statusCode = 0
425
    ) {
426
427 38
        $ret = '';
428
429 19
        $options = [
430 38
            RequestOptions::QUERY => $query,
431 38
            RequestOptions::JSON  => $json,
432
        ];
433
434 38
        $response = $this->request(HttpMethod::METHOD_GET, $this->uri($uri), $options);
435
436 36
        if ($statusCode === $response->getStatusCode()) {
437 36
            $ret = json_decode($response->getBody()->getContents(), true);
438
        }
439
440 36
        return $ret;
441
    }
442
443
    // </editor-fold>
444
}
445