Passed
Push — chore/add-feature-tests ( 36c2df...e56562 )
by Bas
04:12 queued 19s
created

HandlesAqlGrammar::wrapValue()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
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 223
    public function isBind(mixed $value): bool
78
    {
79 223
        if (is_string($value) && preg_match('/^@?[0-9]{4}_[a-zA-Z0-9_$]_[0-9_]+$/', $value)) {
80
            return true;
81
        }
82
83 223
        return false;
84
    }
85
86
    /**
87
     * Get the appropriate query parameter place-holder for a value.
88
     *
89
     * @param  mixed  $value
90
     */
91
    public function parameter($value): string
92
    {
93
        return $this->isExpression($value) ? $this->getValue($value) : (string) $value;
0 ignored issues
show
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

93
        return $this->isExpression($value) ? $this->/** @scrutinizer ignore-call */ getValue($value) : (string) $value;
Loading history...
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

93
        return $this->/** @scrutinizer ignore-call */ isExpression($value) ? $this->getValue($value) : (string) $value;
Loading history...
94
    }
95
96
97
    /**
98
     * Quote the given string literal.
99
     *
100
     * @param  string|array<string>  $value
101
     * @return string
102
     */
103
    public function quoteString($value)
104
    {
105
        if (is_array($value)) {
106
            return implode(', ', array_map([$this, __FUNCTION__], $value));
107
        }
108
109
        return "`$value`";
110
    }
111
112
113
    /**
114
     * Wrap a value in keyword identifiers.
115
     *
116
     * @param  Array<mixed>|Expression|string  $value
117
     * @return array<mixed>|float|int|string
118
     *
119
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
120
     */
121 290
    public function wrap($value)
122
    {
123 290
        if ($value instanceof Expression) {
124
            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

124
            return $value->getValue(/** @scrutinizer ignore-type */ $this);
Loading history...
125
        }
126
127 290
        if (is_array($value)) {
128
            foreach($value as $key => $subvalue) {
129
                $value[$key] = $this->wrap($subvalue);
130
            }
131
            return $value;
132
        }
133
134
        // If the value being wrapped has a column alias we will need to separate out
135
        // the pieces so we can wrap each of the segments of the expression on its
136
        // own, and then join these both back together using the "as" connector.
137 290
        if (is_string($value) && stripos($value, ' as ') !== false) {
138
            return $this->wrapAliasedValue($value);
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

138
            return $this->/** @scrutinizer ignore-call */ wrapAliasedValue($value);
Loading history...
139
        }
140
141 290
        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

141
        return $this->/** @scrutinizer ignore-call */ wrapSegments(explode('.', $value));
Loading history...
142
    }
143
144
145
    /**
146
     * Wrap a table in keyword identifiers.
147
     *
148
     * @param Expression|string  $table
149
     * @return float|int|string
150
     */
151 288
    public function wrapTable($table)
152
    {
153 288
        if (!$table instanceof Expression) {
154 288
            $wrappedTable = $this->wrap($this->tablePrefix . $table);
155
156
            assert(!is_array($wrappedTable));
157
158 288
            return $wrappedTable;
159
        }
160
161
        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

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

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

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