StringToArrayParser::getTransformerSteps()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace AlexWells\ApiDocsGenerator\Parsers;
4
5
class StringToArrayParser extends AbstractStepTransformer
6
{
7
    /**
8
     * Steps that should be taken to transform the string from raw to end result.
9
     *
10
     * @return array
11
     */
12
    protected static function getTransformerSteps()
13
    {
14
        return ['wrapInQuotes', 'wrapInArrayBrackets', 'decode'];
15
    }
16
17
    /**
18
     * Replace `string with "quotes" inside` with `"string with \"quotes\" inside"`.
19
     *
20
     * @param string $string
21
     *
22
     * @return string
23
     */
24
    protected static function transformWrapInQuotes(string $content) {
25
        // If string is already wrapped in quotes, we do nothing and
26
        // assume that it's a valid JSON formatted string or array of strings.
27
        if(starts_with($content, '"') && ends_with($content, '"')) {
28
            return $content;
29
        }
30
31
        // If it's not, then we should escape the string and wrap in quotes.
32
        // json_encode fits perfectly there.
33
        return json_encode($content);
34
    }
35
36
    /**
37
     * Replace `"string", "another"` with `["string", "another"]`.
38
     *
39
     * @param string $content
40
     *
41
     * @return string
42
     */
43
    protected static function transformWrapInArrayBrackets(string $content) {
44
        // Once again, if it's already wrapped we do nothing and
45
        // assume it's correct.
46
        if(starts_with($content, '[') && ends_with($content, ']')) {
47
            return $content;
48
        }
49
50
        return "[$content]";
51
    }
52
53
    /**
54
     * Decode JSON string into PHP array.
55
     *
56
     * @param $content
57
     *
58
     * @return array|null
59
     */
60
    protected static function transformDecode(string $content) {
61
        return json_decode($content, true);
62
    }
63
}
64