Completed
Push — master ( cfbb4d...458589 )
by Dominik
02:35
created

NodeGenerator::appendChildrenToObjectNode()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 24
Code Lines 15

Duplication

Lines 12
Ratio 50 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 0
Metric Value
dl 12
loc 24
ccs 14
cts 14
cp 1
rs 8.5125
c 0
b 0
f 0
cc 6
eloc 15
nc 10
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Saxulum\ElasticSearchQueryBuilder\Generator;
6
7
use PhpParser\Node\Arg;
8
use PhpParser\Node\Expr;
9
use PhpParser\Node\Expr\Assign;
10
use PhpParser\Node\Expr\ConstFetch;
11
use PhpParser\Node\Expr\MethodCall;
12
use PhpParser\Node\Expr\New_;
13
use PhpParser\Node\Expr\Variable;
14
use PhpParser\Node\Name;
15
use PhpParser\Node\Scalar\DNumber;
16
use PhpParser\Node\Scalar\LNumber;
17
use PhpParser\Node\Scalar\String_;
18
use PhpParser\PrettyPrinter\Standard as PhpGenerator;
19
20
final class NodeGenerator
21
{
22
    /**
23
     * @var PhpGenerator
24
     */
25
    private $phpGenerator;
26
27
    /**
28
     * @param PhpGenerator $phpGenerator
29
     */
30 14
    public function __construct(PhpGenerator $phpGenerator)
31
    {
32 14
        $this->phpGenerator = $phpGenerator;
33 14
    }
34
35
    /**
36
     * @param $query
37
     * @return string
38
     */
39 14
    public function generateByJson($query): string
40
    {
41 14
        $data = json_decode($query, false);
42 14
        if (JSON_ERROR_NONE !== json_last_error()) {
43 1
            throw new \InvalidArgumentException(sprintf('Message: %s, query: %s', json_last_error_msg(), $query));
44
        }
45
46 13
        if ($data instanceof \stdClass) {
47 12
            $expr = $this->appendChildrenToObjectNode($data);
48
        } else {
49 1
            $expr = $this->appendChildrenToArrayNode($data);
50
        }
51
52 13
        $code = $this->phpGenerator->prettyPrint([new Assign(new Variable('node'), $expr)]);
53
54 13
        return $this->structureCode($code);
55
    }
56
57
    /**
58
     * @param string $code
59
     * @return string
60
     */
61 13
    private function structureCode(string $code): string
62
    {
63 13
        $codeWithLinebreaks = str_replace('->add', "\n->add", substr($code, 0, -1));
64
65 13
        $lines = explode("\n", $codeWithLinebreaks);
66
67 13
        $position = 0;
68
69 13
        $structuredLines = [];
70
71 13
        foreach ($lines as $i => $line) {
72 13
            $lastStructuredLine = $structuredLines[count($structuredLines) - 1] ?? '';
73 13
            if (0 === strpos($line, '->add') &&
74 13
                false === strpos($lastStructuredLine, ' )') &&
75 13
                false === strpos($lastStructuredLine, 'ScalarNode')) {
76 13
                $position++;
77
            }
78 13
            $lineLength = strlen($line);
79 13
            $braceCount = 0;
80 13
            while (')' === $line[--$lineLength]) {
81 13
                $braceCount++;
82
            }
83 13
            $prefix = str_pad('', $position * 4);
84 13
            if ($braceCount > 2) {
85 12
                $structuredLines[] = $prefix . substr($line, 0, - ($braceCount - 2));
86
            } else {
87 13
                $structuredLines[] = $prefix . $line;
88
            }
89
90 13
            while ($braceCount-- > 2) {
91 12
                $position--;
92 12
                $structuredLines[] = str_pad('', $position * 4) . ')';
93
            }
94
        }
95
96 13
        $structuredLines[count($structuredLines) - 1] .= ';';
97
98 13
        return implode("\n", $structuredLines);
99
    }
100
101
    /**
102
     * @return Expr
103
     */
104 12
    private function createObjectNode(): Expr
105
    {
106 12
        return new New_(new Name('ObjectNode'));
107
    }
108
109
    /**
110
     * @return Expr
111
     */
112 3
    private function createArrayNode(): Expr
113
    {
114 3
        return new New_(new Name('ArrayNode'));
115
    }
116
117
    /**
118
     * @param string|float|int|bool|null $value
119
     * @return Expr
120
     */
121 12 View Code Duplication
    private function createScalarNode($value): Expr
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
122
    {
123 12
        if (is_string($value)) {
124 10
            $valueExpr = new String_($value);
125 5
        } elseif (is_int($value)) {
126 5
            $valueExpr = new LNumber($value);
127 1
        } elseif (is_float($value)) {
128 1
            $valueExpr = new DNumber($value);
129 1
        } elseif (is_bool($value)) {
130 1
            $valueExpr = new ConstFetch(new Name($value ? 'true' : 'false'));
131
        } else {
132 1
            $valueExpr = new ConstFetch(new Name('null'));
133
        }
134
135 12
        return new New_(new Name('ScalarNode'), [new Arg($valueExpr)]);
136
    }
137
138
    /**
139
     * @param array $data
140
     * @return Expr
141
     */
142 3
    private function appendChildrenToArrayNode(array $data)
143
    {
144 3
        $expr = $this->createArrayNode();
145
146 3
        foreach ($data as $key => $value) {
147 3 View Code Duplication
            if ($value instanceof \stdClass) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148 1
                $nodeExpr = $this->createObjectNode();
149 3
            } elseif (is_array($value)) {
150 1
                $nodeExpr = $this->createArrayNode();
151
            } else {
152 2
                $nodeExpr = $this->createScalarNode($value);
153
            }
154
155 3 View Code Duplication
            if ($value instanceof \stdClass) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
156 1
                $nodeExpr = $this->appendChildrenToObjectNode($value);
157 3
            } elseif (is_array($value)) {
158 1
                $nodeExpr = $this->appendChildrenToArrayNode($value);
159
            }
160
161 3
            $expr = new MethodCall($expr, 'add', [new Arg($nodeExpr)]);
162
        }
163
164 3
        return $expr;
165
    }
166
167
    /**
168
     * @param \stdClass $data
169
     * @return Expr
170
     */
171 12
    private function appendChildrenToObjectNode(\stdClass $data)
172
    {
173 12
        $expr = $this->createObjectNode();
174
175 12
        foreach ($data as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $data of type object<stdClass> is not traversable.
Loading history...
176 12 View Code Duplication
            if ($value instanceof \stdClass) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177 12
                $nodeExpr = $this->createObjectNode();
178 11
            } elseif (is_array($value)) {
179 2
                $nodeExpr = $this->createArrayNode();
180
            } else {
181 11
                $nodeExpr = $this->createScalarNode($value);
182
            }
183
184 12 View Code Duplication
            if ($value instanceof \stdClass) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185 12
                $nodeExpr = $this->appendChildrenToObjectNode($value);
186 11
            } elseif (is_array($value)) {
187 2
                $nodeExpr = $this->appendChildrenToArrayNode($value);
188
            }
189
190 12
            $expr = new MethodCall($expr, 'add', [new Arg(new String_($key)), new Arg($nodeExpr)]);
191
        }
192
193 12
        return $expr;
194
    }
195
}
196