Passed
Push — refactor/improve-static-analys... ( 9f92f2...5cc94f )
by Bas
13:59
created

HandlesAqlGrammar::generateAqlObjectString()   A

Complexity

Conditions 6
Paths 14

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0702

Importance

Changes 0
Metric Value
cc 6
eloc 15
c 0
b 0
f 0
nc 14
nop 1
dl 0
loc 28
ccs 14
cts 16
cp 0.875
crap 6.0702
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LaravelFreelancerNL\Aranguent\Query\Concerns;
6
7
use Illuminate\Support\Arr;
8
use Illuminate\Database\Query\Expression;
9
10
trait HandlesAqlGrammar
11
{
12
    /**
13
     * Available predicate operators.
14
     *
15
     * @var array<string, int>
16
     */
17
    protected array $comparisonOperators = [
18
        '=='      => 1,
19
        '!='      => 1,
20
        '<'       => 1,
21
        '>'       => 1,
22
        '<='      => 1,
23
        '>='      => 1,
24
        'IN'      => 1,
25
        'NOT IN'  => 1,
26
        'LIKE'    => 1,
27
        '~'       => 1,
28
        '!~'      => 1,
29
        'ALL =='  => 1,
30
        'ALL !='  => 1,
31
        'ALL <'   => 1,
32
        'ALL >'   => 1,
33
        'ALL <='  => 1,
34
        'ALL >='  => 1,
35
        'ALL IN'  => 1,
36
        'ANY =='  => 1,
37
        'ANY !='  => 1,
38
        'ANY <'   => 1,
39
        'ANY >'   => 1,
40
        'ANY <='  => 1,
41
        'ANY >='  => 1,
42
        'ANY IN'  => 1,
43
        'NONE ==' => 1,
44
        'NONE !=' => 1,
45
        'NONE <'  => 1,
46
        'NONE >'  => 1,
47
        'NONE <=' => 1,
48
        'NONE >=' => 1,
49
        'NONE IN' => 1,
50
    ];
51
52
    /**
53
     * @var array<string, int>
54
     */
55
    protected array $arithmeticOperators = [
56
        '+' => 1,
57
        '-' => 1,
58
        '*' => 1,
59
        '/' => 1,
60
        '%' => 1,
61
    ];
62
63
    /**
64
     * @var array|int[]
65
     */
66
    protected array $logicalOperators = [
67
        'AND' => 1,
68
        '&&'  => 1,
69
        'OR'  => 1,
70
        '||'  => 1,
71
        'NOT' => 1,
72
        '!'   => 1,
73
    ];
74
75
    protected string $rangeOperator = '..';
76
77
    /**
78
     * Get the format for database stored dates.
79
     *
80
     * @return string
81
     */
82
    public function getDateFormat(): string
83
    {
84
        return 'Y-m-d\TH:i:s.vp';
85
    }
86
87 159
    public function isBind(mixed $value): bool
88
    {
89 159
        if (is_string($value) && preg_match('/^@?[0-9]{4}_' . json_encode($value) . '_[0-9_]+$/', $value)) {
90
            return true;
91
        }
92
93 159
        return false;
94
    }
95
96
    /**
97
     * Get the appropriate query parameter place-holder for a value.
98
     *
99
     * @param  mixed  $value
100
     */
101
    public function parameter($value): string
102
    {
103
        return $this->isExpression($value) ? $this->getValue($value) : (string) $value;
0 ignored issues
show
Bug introduced by
It seems like isExpression() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

103
        return $this->/** @scrutinizer ignore-call */ isExpression($value) ? $this->getValue($value) : (string) $value;
Loading history...
Bug introduced by
It seems like getValue() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

103
        return $this->isExpression($value) ? $this->/** @scrutinizer ignore-call */ getValue($value) : (string) $value;
Loading history...
104
    }
105
106
107
    /**
108
     * Quote the given string literal.
109
     *
110
     * @param  string|array<string>  $value
111
     * @return string
112
     */
113
    public function quoteString($value)
114
    {
115
        if (is_array($value)) {
116
            return implode(', ', array_map([$this, __FUNCTION__], $value));
117
        }
118
119
        return "`$value`";
120
    }
121
122
123
    /**
124
     * Wrap a value in keyword identifiers.
125
     *
126
     * @param  Array<mixed>|Expression|string  $value
127
     * @param  bool  $prefixAlias
128
     * @return array<mixed>|float|int|string
129
     *
130
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
131
     */
132 224
    public function wrap($value, $prefixAlias = false)
133
    {
134 224
        if ($value instanceof Expression) {
135
            return $value->getValue($this);
0 ignored issues
show
Bug introduced by
$this of type LaravelFreelancerNL\Aran...cerns\HandlesAqlGrammar is incompatible with the type Illuminate\Database\Grammar expected by parameter $grammar of Illuminate\Database\Query\Expression::getValue(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
            return $value->getValue(/** @scrutinizer ignore-type */ $this);
Loading history...
136
        }
137
138 224
        if (is_array($value)) {
139
            foreach($value as $key => $subvalue) {
140
                $value[$key] = $this->wrap($subvalue, $prefixAlias);
141
            }
142
            return $value;
143
        }
144
145
        // If the value being wrapped has a column alias we will need to separate out
146
        // the pieces so we can wrap each of the segments of the expression on its
147
        // own, and then join these both back together using the "as" connector.
148 224
        if (is_string($value) && stripos($value, ' as ') !== false) {
149
            return $this->wrapAliasedValue($value, $prefixAlias);
0 ignored issues
show
Bug introduced by
It seems like wrapAliasedValue() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

149
            return $this->/** @scrutinizer ignore-call */ wrapAliasedValue($value, $prefixAlias);
Loading history...
150
        }
151
152 224
        return $this->wrapSegments(explode('.', $value));
0 ignored issues
show
Bug introduced by
It seems like wrapSegments() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

152
        return $this->/** @scrutinizer ignore-call */ wrapSegments(explode('.', $value));
Loading history...
153
    }
154
155
156
    /**
157
     * Wrap a table in keyword identifiers.
158
     *
159
     * @param Expression|string  $table
160
     * @return float|int|string
161
     */
162 222
    public function wrapTable($table)
163
    {
164 222
        if (!$table instanceof Expression) {
165 222
            $wrappedTable = $this->wrap($this->tablePrefix . $table, true);
166
167
            assert(!is_array($wrappedTable));
168
169 222
            return $wrappedTable;
170
        }
171
172
        return $table->getValue($this);
0 ignored issues
show
Bug introduced by
$this of type LaravelFreelancerNL\Aran...cerns\HandlesAqlGrammar is incompatible with the type Illuminate\Database\Grammar expected by parameter $grammar of Illuminate\Database\Query\Expression::getValue(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

172
        return $table->getValue(/** @scrutinizer ignore-type */ $this);
Loading history...
173
    }
174
175
    /**
176
     * Wrap a single string in keyword identifiers.
177
     *
178
     * @param  string  $value
179
     * @return string
180
     */
181 224
    protected function wrapValue($value)
182
    {
183 224
        $postfix = '';
184 224
        if ($value === 'groupsVariable') {
185 1
            $postfix = '[*]';
186
        }
187
188 224
        if ($value === '*') {
189 2
            return $value;
190
        }
191
192 224
        return '`' . str_replace('`', '``', $value) . '`' . $postfix;
193
    }
194
195
    /**
196
     * Wrap a subquery single string in braces.
197
     */
198 23
    public function wrapSubquery(string $subquery): string
199
    {
200 23
        return '(' . $subquery . ')';
201
    }
202
203
    /**
204
     * @param array<mixed> $data
205
     * @return string
206
     */
207 124
    public function generateAqlObject(array $data): string
208
    {
209 124
        $data = Arr::undot($data);
210
211 124
        return $this->generateAqlObjectString($data);
212
    }
213
214
    /**
215
     * @param array<mixed> $data
216
     * @return string
217
     */
218 124
    protected function generateAqlObjectString(array $data): string
219
    {
220 124
        foreach($data as $key => $value) {
221 124
            $prefix = $key . ': ';
222 124
            if (is_numeric($key)) {
223 1
                $prefix = '';
224
            }
225
226 124
            if (is_array($value)) {
227 9
                $data[$key] = $prefix . $this->generateAqlObjectString($value);
228 9
                continue;
229
            }
230
231 124
            if ($value instanceof Expression) {
232
                $data[$key] = $prefix . $value->getValue($this);
0 ignored issues
show
Bug introduced by
$this of type LaravelFreelancerNL\Aran...cerns\HandlesAqlGrammar is incompatible with the type Illuminate\Database\Grammar expected by parameter $grammar of Illuminate\Database\Query\Expression::getValue(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

232
                $data[$key] = $prefix . $value->getValue(/** @scrutinizer ignore-type */ $this);
Loading history...
233
                continue;
234
            }
235
236 124
            $data[$key] = $prefix . $value;
237
        }
238
239 124
        $returnString = implode(', ', $data);
240
241 124
        if (array_is_list($data)) {
242 1
            return '[' . $returnString . ']';
243
        }
244
245 124
        return '{' . $returnString . '}';
246
    }
247
248
    /**
249
     * Substitute the given bindings into the given raw AQL query.
250
     *
251
     * @param  string  $aql
252
     * @param  array<mixed>  $bindings
253
     * @return string
254
     */
255 4
    public function substituteBindingsIntoRawSql($aql, $bindings)
256
    {
257 4
        $bindings = array_map(fn($value) => $this->escape($value), $bindings);
0 ignored issues
show
Bug introduced by
It seems like escape() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

257
        $bindings = array_map(fn($value) => $this->/** @scrutinizer ignore-call */ escape($value), $bindings);
Loading history...
258
259 4
        $bindings = array_reverse($bindings);
260
261 4
        foreach($bindings as $key => $value) {
262 4
            $pattern = '/(@' . $key . ')(?![^a-zA-Z_ ,\}\]])/';
263 4
            $aql = (string) preg_replace(
264 4
                $pattern,
265 4
                $value,
266 4
                $aql
267 4
            );
268
        }
269
270 4
        return $aql;
271
    }
272
273
    /**
274
     * Determine if the given string is a JSON selector.
275
     *
276
     * @param  string  $value
277
     * @return bool
278
     */
279 253
    public function isJsonSelector($value)
280
    {
281 253
        if(!is_string($value)) {
0 ignored issues
show
introduced by
The condition is_string($value) is always true.
Loading history...
282 5
            return false;
283
        }
284
285 253
        return str_contains($value, '->');
286
    }
287
288 253
    public function convertJsonFields(mixed $data): mixed
289
    {
290 253
        if (!is_array($data) && !is_string($data)) {
291
            return $data;
292
        }
293
294 253
        if (is_string($data)) {
295 200
            return str_replace('->', '.', $data);
296
        }
297
298 253
        if (array_is_list($data)) {
299 251
            return $this->convertJsonValuesToDotNotation($data);
300
        }
301
302 38
        return $this->convertJsonKeysToDotNotation($data);
303
    }
304
305
    /**
306
     * @param array<string> $fields
307
     * @return array<string>
308
     */
309 251
    public function convertJsonValuesToDotNotation(array $fields): array
310
    {
311 251
        foreach($fields as $key => $value) {
312 251
            if ($this->isJsonSelector($value)) {
313 1
                $fields[$key] = str_replace('->', '.', $value);
314
            }
315
        }
316 251
        return $fields;
317
    }
318
319
    /**
320
     * @param array<string> $fields
321
     * @return array<string>
322
     */
323 38
    public function convertJsonKeysToDotNotation(array $fields): array
324
    {
325 38
        foreach($fields as $key => $value) {
326 38
            if ($this->isJsonSelector($key)) {
327 2
                $fields[str_replace('->', '.', $key)] = $value;
328 2
                unset($fields[$key]);
329
            }
330
        }
331 38
        return $fields;
332
    }
333
334
    /**
335
     * Translate sql operators to their AQL equivalent where possible.
336
     *
337
     * @param string $operator
338
     *
339
     * @return mixed|string
340
     */
341
    protected function translateOperator(string $operator)
342
    {
343
        if (isset($this->operatorTranslations[strtolower($operator)])) {
344
            $operator = $this->operatorTranslations[$operator];
345
        }
346
347
        return $operator;
348
    }
349
350
}
351