Completed
Push — master ( c6a664...3473b8 )
by Alex
05:09
created

StringToArrayParser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 9
dl 0
loc 55
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A transformWrapInQuotes() 0 10 3
A transformDecode() 0 2 1
A transformWrapInArrayBrackets() 0 8 3
A getTransformerSteps() 0 3 1
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
     * @return string
22
     */
23
    protected static function transformWrapInQuotes(string $content) {
24
        // If string is already wrapped in quotes, we do nothing and
25
        // assume that it's a valid JSON formatted string or array of strings.
26
        if(starts_with($content, '"') && ends_with($content, '"')) {
27
            return $content;
28
        }
29
30
        // If it's not, then we should escape the string and wrap in quotes.
31
        // json_encode fits perfectly there.
32
        return json_encode($content);
33
    }
34
35
    /**
36
     * Replace `"string", "another"` with `["string", "another"]`
37
     *
38
     * @param string $content
39
     * @return string
40
     */
41
    protected static function transformWrapInArrayBrackets(string $content) {
42
        // Once again, if it's already wrapped we do nothing and
43
        // assume it's correct.
44
        if(starts_with($content, '[') && ends_with($content, ']')) {
45
            return $content;
46
        }
47
48
        return "[$content]";
49
    }
50
51
    /**
52
     * Decode JSON string into PHP array.
53
     *
54
     * @param $content
55
     *
56
     * @return array|null
57
     */
58
    protected static function transformDecode(string $content) {
59
        return json_decode($content, true);
60
    }
61
}