Passed
Push — refactor/improve-static-analys... ( efcf20...37f12c )
by Bas
03:04
created

HandlesAqlGrammar::isBind()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
cc 3
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 7
ccs 3
cts 4
cp 0.75
crap 3.1406
rs 10
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 string|array<mixed>
129
     *
130
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
131
     */
132 224
    public function wrap($value, $prefixAlias = false)
133
    {
134 224
        if ($this->isExpression($value)) {
135
            return $this->getValue($value);
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...
Bug introduced by
It seems like $value can also be of type Illuminate\Database\Query\Expression; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

152
        return $this->wrapSegments(explode('.', /** @scrutinizer ignore-type */ $value));
Loading history...
153
    }
154
155
156
    /**
157
     * Wrap a table in keyword identifiers.
158
     *
159
     * @param  \Illuminate\Database\Query\Expression|string  $table
160
     * @return string
161
     */
162 222
    public function wrapTable($table)
163
    {
164 222
        if (!$this->isExpression($table)) {
165 222
            return $this->wrap($this->tablePrefix . $table, true);
0 ignored issues
show
Bug introduced by
Are you sure $table of type Illuminate\Database\Query\Expression|string can be used in concatenation? ( Ignorable by Annotation )

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

165
            return $this->wrap($this->tablePrefix . /** @scrutinizer ignore-type */ $table, true);
Loading history...
Bug Best Practice introduced by
The expression return $this->wrap($this...ePrefix . $table, true) also could return the type array<mixed,mixed> which is incompatible with the documented return type string.
Loading history...
166
        }
167
168
        return $this->getValue($table);
169
    }
170
171
    /**
172
     * Wrap a single string in keyword identifiers.
173
     *
174
     * @param  string  $value
175
     * @return string
176
     */
177 224
    protected function wrapValue($value)
178
    {
179 224
        $postfix = '';
180 224
        if ($value === 'groupsVariable') {
181 1
            $postfix = '[*]';
182
        }
183
184 224
        if ($value === '*') {
185 2
            return $value;
186
        }
187
188 224
        return '`' . str_replace('`', '``', $value) . '`' . $postfix;
189
    }
190
191
    /**
192
     * Wrap a subquery single string in braces.
193
     */
194 23
    public function wrapSubquery(string $subquery): string
195
    {
196 23
        return '(' . $subquery . ')';
197
    }
198
199
    /**
200
     * @param array<mixed> $data
201
     * @return string
202
     */
203 124
    public function generateAqlObject(array $data): string
204
    {
205 124
        $data = Arr::undot($data);
206
207 124
        return $this->generateAqlObjectString($data);
208
    }
209
210
    /**
211
     * @param array<mixed> $data
212
     * @return string
213
     */
214 124
    protected function generateAqlObjectString(array $data): string
215
    {
216 124
        foreach($data as $key => $value) {
217 124
            $prefix = $key . ': ';
218 124
            if (is_numeric($key)) {
219 1
                $prefix = '';
220
            }
221
222 124
            if (is_array($value)) {
223 9
                $data[$key] = $prefix . $this->generateAqlObjectString($value);
224 9
                continue;
225
            }
226
227 124
            if ($value instanceof Expression) {
228
                $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

228
                $data[$key] = $prefix . $value->getValue(/** @scrutinizer ignore-type */ $this);
Loading history...
229
                continue;
230
            }
231
232 124
            $data[$key] = $prefix . $value;
233
        }
234
235 124
        $returnString = implode(', ', $data);
236
237 124
        if (array_is_list($data)) {
238 1
            return '[' . $returnString . ']';
239
        }
240
241 124
        return '{' . $returnString . '}';
242
    }
243
244
    /**
245
     * Substitute the given bindings into the given raw AQL query.
246
     *
247
     * @param  string  $sql
248
     * @param  array<mixed>  $bindings
249
     * @return string
250
     */
251 4
    public function substituteBindingsIntoRawSql($sql, $bindings)
252
    {
253 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

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