1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace LaravelFreelancerNL\Aranguent\Query\Concerns; |
6
|
|
|
|
7
|
|
|
use Illuminate\Database\Query\Expression; |
8
|
|
|
use Illuminate\Database\Query\Builder as IlluminateQueryBuilder; |
9
|
|
|
use InvalidArgumentException; |
10
|
|
|
|
11
|
|
|
trait HandlesBindings |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Add a binding to the query. |
15
|
|
|
* |
16
|
|
|
* @param mixed $value |
17
|
|
|
* @param string $type |
18
|
|
|
* @return IlluminateQueryBuilder |
19
|
|
|
* |
20
|
|
|
* @throws \InvalidArgumentException |
21
|
|
|
*/ |
22
|
|
|
public function addBinding($value, $type = 'where') |
23
|
|
|
{ |
24
|
|
|
if (!array_key_exists($type, $this->bindings)) { |
25
|
|
|
throw new InvalidArgumentException("Invalid binding type: {$type}."); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$bindVariable = $this->generateBindVariable($type); |
29
|
|
|
$this->bindings[$type][$bindVariable] = $this->castBinding($value); |
|
|
|
|
30
|
|
|
|
31
|
|
|
return $this; |
|
|
|
|
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
protected function bindValue($value, string $type = 'where') |
35
|
|
|
{ |
36
|
|
|
if ($this->grammar->isBind($value, $type)) { |
37
|
|
|
return $value; |
38
|
|
|
} |
39
|
|
|
if (!$value instanceof Expression) { |
40
|
|
|
$this->addBinding($value, $type); |
41
|
|
|
$value = $this->replaceValueWithBindVariable($type); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $value; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Remove all of the expressions from a list of bindings. |
49
|
|
|
* |
50
|
|
|
* @param array $bindings |
51
|
|
|
* @return array |
52
|
|
|
*/ |
53
|
|
|
public function cleanBindings(array $bindings) |
54
|
|
|
{ |
55
|
|
|
return collect($bindings) |
|
|
|
|
56
|
|
|
->reject(function ($binding) { |
57
|
|
|
return $binding instanceof Expression; |
58
|
|
|
}) |
59
|
|
|
->map([$this, 'castBinding']) |
60
|
|
|
->all(); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function generateBindVariable(string $type = 'where'): string |
64
|
|
|
{ |
65
|
|
|
return $this->queryId . '_' . $type . '_' . (count($this->bindings[$type]) + 1); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
protected function getLastBindVariable(string $type = 'where') |
69
|
|
|
{ |
70
|
|
|
return array_key_last($this->bindings[$type]); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function importBindings(IlluminateQueryBuilder $query, string $type = null): void |
74
|
|
|
{ |
75
|
|
|
if ($type) { |
76
|
|
|
$this->bindings[$type] = array_merge($this->bindings[$type], $query->bindings[$type]); |
|
|
|
|
77
|
|
|
return; |
78
|
|
|
} |
79
|
|
|
$this->bindings = array_merge_recursive($this->bindings, $query->bindings); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
|
83
|
|
|
protected function replaceValueWithBindVariable(string $type = 'where') |
84
|
|
|
{ |
85
|
|
|
return '@' . $this->getLastBindVariable($type); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|