QueryBuilderGenerator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 1
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
/**
21
 * @deprecated use Saxulum\ElasticSearchQueryBuilder\Generator\NodeGenerator
22
 */
23
final class QueryBuilderGenerator
24
{
25
    /**
26
     * @var PhpGenerator
27
     */
28
    private $phpGenerator;
29
30
    /**
31
     * @var bool
32
     */
33
    private $useMethodName;
34
35
    /**
36
     * @param bool         $useMethodName
37
     * @param PhpGenerator $phpGenerator
38
     */
39 14
    public function __construct(PhpGenerator $phpGenerator, bool $useMethodName = false)
40
    {
41 14
        @trigger_error(sprintf('Use "%s" instead of the "%s"', NodeGenerator::class, self::class), E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
42
43 14
        $this->phpGenerator = $phpGenerator;
44 14
        $this->useMethodName = $useMethodName;
45 14
    }
46
47
    /**
48
     * @param $query
49
     *
50
     * @return string
51
     */
52 14
    public function generateByJson($query): string
53
    {
54 14
        $data = json_decode($query, false);
55 14
        if (JSON_ERROR_NONE !== json_last_error()) {
56 1
            throw new \InvalidArgumentException(sprintf('Message: %s, query: %s', json_last_error_msg(), $query));
57
        }
58
59 13
        $queryBuilder = new Variable('qb');
60
61 13
        $stmts = [];
62
63 13
        $stmts[] = $this->createQueryBuilderNode();
64 13
        $stmts[] = $this->appendChildrenToObjectNode($queryBuilder, $queryBuilder, $data);
65
66 13
        return $this->structureCode($this->phpGenerator->prettyPrint($stmts));
67
    }
68
69
    /**
70
     * @return Expr
71
     */
72 13
    private function createQueryBuilderNode(): Expr
73
    {
74 13
        return new Assign(new Variable('qb'), new New_(new Name('QueryBuilder')));
75
    }
76
77
    /**
78
     * @param Expr $expr
79
     *
80
     * @return Expr
81
     */
82 13
    private function createObjectNode(Expr $expr): Expr
83
    {
84 13
        return new MethodCall($expr, 'objectNode');
85
    }
86
87
    /**
88
     * @param Expr $expr
89
     *
90
     * @return Expr
91
     */
92 3
    private function createArrayNode(Expr $expr): Expr
93
    {
94 3
        return new MethodCall($expr, 'arrayNode');
95
    }
96
97
    /**
98
     * @param Expr                       $expr
99
     * @param string|float|int|bool|null $value
100
     *
101
     * @return Expr
102
     */
103 12
    private function createScalarNode(Expr $expr, $value): Expr
104
    {
105 12
        if (is_int($value)) {
106 5
            return new MethodCall($expr, 'intNode', [new Arg(new LNumber($value))]);
107 11
        } elseif (is_float($value)) {
108 2
            return new MethodCall($expr, 'floatNode', [new Arg(new DNumber($value))]);
109 11
        } elseif (is_bool($value)) {
110 2
            return new MethodCall($expr, 'boolNode', [new Arg(new ConstFetch(new Name($value ? 'true' : 'false')))]);
111 11
        } elseif (null === $value) {
112 2
            return new MethodCall($expr, 'nullNode');
113
        }
114
115 11
        return new MethodCall($expr, 'stringNode', [new Arg(new String_($value))]);
116
    }
117
118
    /**
119
     * @param Expr  $queryBuilder
120
     * @param Expr  $expr
121
     * @param array $data
122
     *
123
     * @return Expr
124
     */
125 3
    private function appendChildrenToArrayNode(Expr $queryBuilder, Expr $expr, array $data)
126
    {
127 3
        foreach ($data as $value) {
128 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...
129 2
                $argument = $this->createObjectNode($queryBuilder);
130 3
            } elseif (is_array($value)) {
131 2
                $argument = $this->createArrayNode($queryBuilder);
132
            } else {
133 1
                $argument = $this->createScalarNode($queryBuilder, $value);
134
            }
135
136 3
            $methodName = $this->useMethodName ? 'addToArrayNode' : 'add';
137
138 3
            $expr = new MethodCall($expr, $methodName, [new Arg($argument)]);
139
140 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...
141 2
                $expr = new MethodCall($this->appendChildrenToObjectNode($queryBuilder, $expr, $value), 'end');
142 3
            } elseif (is_array($value)) {
143 3
                $expr = new MethodCall($this->appendChildrenToArrayNode($queryBuilder, $expr, $value), 'end');
144
            }
145
        }
146
147 3
        return $expr;
148
    }
149
150
    /**
151
     * @param Expr      $queryBuilder
152
     * @param Expr      $expr
153
     * @param \stdClass $data
154
     *
155
     * @return Expr
156
     */
157 13
    private function appendChildrenToObjectNode(Expr $queryBuilder, Expr $expr, \stdClass $data)
158
    {
159 13
        foreach ($data as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $data of type object<stdClass> is not traversable.
Loading history...
160 13 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...
161 13
                $argument = $this->createObjectNode($queryBuilder);
162 12
            } elseif (is_array($value)) {
163 3
                $argument = $this->createArrayNode($queryBuilder);
164
            } else {
165 12
                $argument = $this->createScalarNode($queryBuilder, $value);
166
            }
167
168 13
            $methodName = $this->useMethodName ? 'addToObjectNode' : 'add';
169
170 13
            $expr = new MethodCall($expr, $methodName, [new Arg(new String_($key)), new Arg($argument)]);
171
172 13 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...
173 13
                $expr = new MethodCall($this->appendChildrenToObjectNode($queryBuilder, $expr, $value), 'end');
174 12
            } elseif (is_array($value)) {
175 13
                $expr = new MethodCall($this->appendChildrenToArrayNode($queryBuilder, $expr, $value), 'end');
176
            }
177
        }
178
179 13
        return $expr;
180
    }
181
182
    /**
183
     * @param string $code
184
     *
185
     * @return string
186
     */
187 13
    private function structureCode(string $code): string
188
    {
189 13
        $lines = $this->getLinesByCode($code);
190
191 13
        $position = 0;
192
193 13
        $structuredLines = [];
194
195 13 View Code Duplication
        foreach ($lines as $i => $line) {
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...
196 13
            $lastLine = $lines[$i - 1] ?? '';
197 13
            $this->structuredLine($line, $lastLine, $position, $structuredLines);
198
        }
199
200 13
        return implode("\n", $structuredLines);
201
    }
202
203
    /**
204
     * @param string $code
205
     *
206
     * @return array
207
     */
208 13
    private function getLinesByCode(string $code): array
209
    {
210 13
        $codeWithLinebreaks = str_replace('->add', "\n->add", $code);
211 13
        $codeWithLinebreaks = str_replace('->end', "\n->end", $codeWithLinebreaks);
212
213 13
        return explode("\n", $codeWithLinebreaks);
214
    }
215
216
    /**
217
     * @param string $line
218
     * @param string $lastLine
219
     * @param int    $position
220
     * @param array  $structuredLines
221
     */
222 13
    private function structuredLine(string $line, string $lastLine, int &$position, array &$structuredLines)
223
    {
224 13
        if (0 === strpos($line, '->add')) {
225 13
            if (false === strpos($lastLine, '->end') &&
226 13
                false === strpos($lastLine, '->boolNode') &&
227 13
                false === strpos($lastLine, '->floatNode') &&
228 13
                false === strpos($lastLine, '->intNode') &&
229 13
                false === strpos($lastLine, '->nullNode') &&
230 13
                false === strpos($lastLine, '->stringNode')
231
            ) {
232 13
                ++$position;
233
            }
234
235 13
            $structuredLines[] = str_pad('', $position * 4).$line;
236
237 13
            return;
238
        }
239
240 13
        if (0 === strpos($line, '->end')) {
241 13
            if (strpos($lastLine, '->objectNode') || strpos($lastLine, '->arrayNode')) {
242 1
                $structuredLines[count($structuredLines) - 1] .= '->end()';
243
244 1
                return;
245
            }
246
247 13
            --$position;
248
249 13
            $structuredLines[] = str_pad('', $position * 4).$line;
250
251 13
            return;
252
        }
253
254 13
        $structuredLines[] = $line;
255 13
    }
256
}
257