Decoder::decode()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 15
c 3
b 0
f 0
nc 5
nop 1
dl 0
loc 28
rs 9.4555
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cakasim\Payone\Sdk\Api\Format;
6
7
/**
8
 * Implementation of the API format decoder contract.
9
 *
10
 * @author Fabian Böttcher <[email protected]>
11
 * @since 0.1.0
12
 */
13
class Decoder implements DecoderInterface
14
{
15
    /**
16
     * @inheritDoc
17
     */
18
    public function decode(string $data): array
19
    {
20
        // Split data by line breaks.
21
        $data = preg_split('/\r?\n/i', $data);
22
23
        if (!is_array($data)) {
24
            throw new DecoderException("Failed decoding of data.");
25
        }
26
27
        // Split each line by param-value-separator and encode the value component.
28
        $lines = [];
29
        foreach ($data as $line) {
30
            $line = trim($line);
31
            if (strpos($line, '=') > 0) {
32
                $line = explode('=', $line, 2);
33
                $lines[] = "{$line[0]}=" . rawurlencode($line[1]);
34
            } elseif (!empty($line)) {
35
                throw new DecoderException("Failed decoding of data.");
36
            }
37
        }
38
39
        // Join the lines in order to use parse_str().
40
        $data = join('&', $lines);
41
42
        $result = [];
43
        parse_str($data, $result);
44
45
        return $result;
46
    }
47
}
48