|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Halalsoft\LaravelDynamicColumn; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Query\Builder; |
|
6
|
|
|
use Illuminate\Database\Query\Grammars\MySqlGrammar; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Class DynamicGrammar |
|
10
|
|
|
* |
|
11
|
|
|
*/ |
|
12
|
|
|
class DynamicGrammar extends MySqlGrammar |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Compile a "JSON contains" statement into SQL. |
|
16
|
|
|
* |
|
17
|
|
|
* @param string $column |
|
18
|
|
|
* @param string $value |
|
19
|
|
|
* |
|
20
|
|
|
* @return string |
|
21
|
|
|
*/ |
|
22
|
|
|
public function compileDynamicColumn($column, $value, $operator = '=') |
|
23
|
|
|
{ |
|
24
|
|
|
[$field, $key] = $this->wrapDynamicField($column); |
|
25
|
|
|
|
|
26
|
|
|
return 'COLUMN_GET('.$field.', "'.$key.'" as char) '.$operator.' '.$value.''; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function compileDynamicExists($column, $value) |
|
30
|
|
|
{ |
|
31
|
|
|
[$field, $key] = $this->wrapDynamicField($column); |
|
32
|
|
|
|
|
33
|
|
|
if ($key) { |
|
34
|
|
|
return 'COLUMN_EXISTS('.$field.', "'.$key.'")'; |
|
35
|
|
|
} else { |
|
36
|
|
|
return 'COLUMN_EXISTS('.$column.', '.$this->parameter($value).')'; |
|
37
|
|
|
} |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Compile a "where JSON contains" clause. |
|
43
|
|
|
* |
|
44
|
|
|
* @param Builder $query |
|
45
|
|
|
* @param array $where |
|
46
|
|
|
* |
|
47
|
|
|
* @return string |
|
48
|
|
|
*/ |
|
49
|
|
|
protected function whereDynamicColumnExists(Builder $query, $where) |
|
|
|
|
|
|
50
|
|
|
{ |
|
51
|
|
|
return $this->compileDynamicExists( |
|
52
|
|
|
$where['column'], |
|
53
|
|
|
$this->parameter($where['value']) |
|
54
|
|
|
); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Split the given JSON selector into the field and the optional path and wrap them separately. |
|
60
|
|
|
* |
|
61
|
|
|
* @param string $column |
|
62
|
|
|
* |
|
63
|
|
|
* @return array |
|
64
|
|
|
*/ |
|
65
|
|
|
protected function wrapDynamicField($column) |
|
66
|
|
|
{ |
|
67
|
|
|
$parts = explode('->', $column, 2); |
|
68
|
|
|
|
|
69
|
|
|
$field = $this->wrap($parts[0]); |
|
70
|
|
|
|
|
71
|
|
|
// $path = count($parts) > 1 ? ', '.$this->wrapJsonPath($parts[1], '->') : ''; |
|
72
|
|
|
|
|
73
|
|
|
return [$field, $parts[1] ?? null]; |
|
74
|
|
|
} |
|
75
|
|
|
} |
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.