Completed
Push — master ( 25839e...4857c1 )
by Dominik
02:15
created

NodeGenerator::appendChildrenToObjectNode()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 24
Code Lines 15

Duplication

Lines 12
Ratio 50 %

Importance

Changes 0
Metric Value
dl 12
loc 24
rs 8.5125
c 0
b 0
f 0
cc 6
eloc 15
nc 10
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Saxulum\ElasticSearchQueryBuilder;
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
    public function __construct(PhpGenerator $phpGenerator)
31
    {
32
        $this->phpGenerator = $phpGenerator;
33
    }
34
35
    /**
36
     * @param $query
37
     * @return string
38
     */
39
    public function generateByJson($query): string
40
    {
41
        $data = json_decode($query, false);
42
        if (JSON_ERROR_NONE !== json_last_error()) {
43
            throw new \InvalidArgumentException(sprintf('Message: %s, query: %s', json_last_error_msg(), $query));
44
        }
45
46
        if ($data instanceof \stdClass) {
47
            $expr = $this->appendChildrenToObjectNode($data);
48
        } else {
49
            $expr = $this->appendChildrenToArrayNode($data);
50
        }
51
52
        $code = $this->phpGenerator->prettyPrint([new Assign(new Variable('node'), $expr)]);
53
54
        return $this->structureCode($code);
55
    }
56
57
    /**
58
     * @param string $code
59
     * @return string
60
     */
61
    private function structureCode(string $code): string
62
    {
63
        $codeWithLinebreaks = str_replace('->add', "\n->add", substr($code, 0, -1));
64
65
        $lines = explode("\n", $codeWithLinebreaks);
66
67
        $position = 0;
68
69
        $structuredLines = [];
70
71
        foreach ($lines as $i => $line) {
72
            $lastStructuredLine = $structuredLines[count($structuredLines) - 1] ?? '';
73
            if (0 === strpos($line, '->add') &&
74
                false === strpos($lastStructuredLine, ' )') &&
75
                false === strpos($lastStructuredLine, 'ScalarNode')) {
76
                $position++;
77
            }
78
            $lineLength = strlen($line);
79
            $braceCount = 0;
80
            while (')' === $line[--$lineLength]) {
81
                $braceCount++;
82
            }
83
            $prefix = str_pad('', $position * 4);
84
            if ($braceCount > 2) {
85
                $structuredLines[] = $prefix . substr($line, 0, ($braceCount - 2 * -1));
86
            } else {
87
                $structuredLines[] = $prefix . $line;
88
            }
89
90
            while ($braceCount-- > 2) {
91
                $position--;
92
                $structuredLines[] = str_pad('', $position * 4) . ')';
93
            }
94
        }
95
96
        $structuredLines[count($structuredLines) - 1] .= ';';
97
98
        return implode("\n", $structuredLines);
99
    }
100
101
    /**
102
     * @return Expr
103
     */
104
    private function createObjectNode(): Expr
105
    {
106
        return new New_(new Name('ObjectNode'));
107
    }
108
109
    /**
110
     * @return Expr
111
     */
112
    private function createArrayNode(): Expr
113
    {
114
        return new New_(new Name('ArrayNode'));
115
    }
116
117
    /**
118
     * @param string|float|int|bool|null $value
119
     * @return Expr
120
     */
121 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
        if (is_string($value)) {
124
            $valueExpr = new String_($value);
125
        } elseif (is_int($value)) {
126
            $valueExpr = new LNumber($value);
127
        } elseif (is_float($value)) {
128
            $valueExpr = new DNumber($value);
129
        } elseif (is_bool($value)) {
130
            $valueExpr = new ConstFetch(new Name($value ? 'true' : 'false'));
131
        } else {
132
            $valueExpr = new ConstFetch(new Name('null'));
133
        }
134
135
        return new New_(new Name('ScalarNode'), [new Arg($valueExpr)]);
136
    }
137
138
    /**
139
     * @param array $data
140
     * @return Expr
141
     */
142
    private function appendChildrenToArrayNode(array $data)
143
    {
144
        $expr = $this->createArrayNode();
145
146
        foreach ($data as $key => $value) {
147 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
                $nodeExpr = $this->createObjectNode();
149
            } elseif (is_array($value)) {
150
                $nodeExpr = $this->createArrayNode();
151
            } else {
152
                $nodeExpr = $this->createScalarNode($value);
153
            }
154
155 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
                $nodeExpr = $this->appendChildrenToObjectNode($value);
157
            } elseif (is_array($value)) {
158
                $nodeExpr = $this->appendChildrenToArrayNode($value);
159
            }
160
161
            $expr = new MethodCall($expr, 'add', [new Arg($nodeExpr)]);
162
        }
163
164
        return $expr;
165
    }
166
167
    /**
168
     * @param \stdClass $data
169
     * @return Expr
170
     */
171
    private function appendChildrenToObjectNode(\stdClass $data)
172
    {
173
        $expr = $this->createObjectNode();
174
175
        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 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
                $nodeExpr = $this->createObjectNode();
178
            } elseif (is_array($value)) {
179
                $nodeExpr = $this->createArrayNode();
180
            } else {
181
                $nodeExpr = $this->createScalarNode($value);
182
            }
183
184 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
                $nodeExpr = $this->appendChildrenToObjectNode($value);
186
            } elseif (is_array($value)) {
187
                $nodeExpr = $this->appendChildrenToArrayNode($value);
188
            }
189
190
            $expr = new MethodCall($expr, 'add', [new Arg(new String_($key)), new Arg($nodeExpr)]);
191
        }
192
193
        return $expr;
194
    }
195
}
196