AbstractStepTransformer::parse()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 17
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 0
1
<?php
2
3
namespace AlexWells\ApiDocsGenerator\Parsers;
4
5
use AlexWells\ApiDocsGenerator\Exceptions\InvalidFormat;
6
7
abstract class AbstractStepTransformer
8
{
9
    /**
10
     * Steps that should be taken to transform the string from raw to end result.
11
     *
12
     * @return array
13
     */
14
    abstract protected static function getTransformerSteps();
15
16
    /**
17
     * Content to be parsed.
18
     *
19
     * @var string
20
     */
21
    protected $content;
22
23
    /**
24
     * AbstractStep constructor.
25
     *
26
     * @param string $content content to be parsed
27
     */
28
    public function __construct(string $content)
29
    {
30
        $this->content = $content;
31
    }
32
33
    /**
34
     * Parse the content.
35
     *
36
     * @throws InvalidFormat
37
     *
38
     * @return array
39
     */
40
    public function parse()
41
    {
42
        $content = $this->content;
43
44
        foreach (static::getTransformerSteps() as $step) {
45
            $content = static::callTransformer($step, $content);
46
47
            if($content === null) {
48
                throw new InvalidFormat("Format is invalid. Failed at step: $step");
49
            }
50
51
            if(empty($content)) {
52
                return $content;
53
            }
54
        }
55
56
        return $content;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $content also could return the type string which is incompatible with the documented return type array.
Loading history...
57
    }
58
59
    /**
60
     * Call transformer method by it's partial name.
61
     *
62
     * @param string $name Transformer name
63
     *
64
     * @return string|array
65
     */
66
    protected static function callTransformer($name, $content)
67
    {
68
        $transformer = static::getTransformerMethodName($name);
69
70
        if(! method_exists(static::class, $transformer)) {
71
            return $content;
72
        }
73
74
        return static::$transformer($content);
75
    }
76
77
    /**
78
     * Get method name for transformer by it's partial name.
79
     *
80
     * @param string $name Transformer name
81
     *
82
     * @return string
83
     */
84
    protected static function getTransformerMethodName($name)
85
    {
86
        // Convert snake_case (if present) to camelCase
87
        $name = camel_case($name);
88
89
        // Capitalize first letter
90
        $name = ucfirst($name);
91
92
        return "transform$name";
93
    }
94
}
95