1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Bluz Framework Component |
5
|
|
|
* |
6
|
|
|
* @copyright Bluz PHP Team |
7
|
|
|
* @link https://github.com/bluzphp/framework |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Bluz\Db\Query\Traits; |
13
|
|
|
|
14
|
|
|
use Bluz\Proxy\Db; |
15
|
|
|
use PDO; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Set Trait |
19
|
|
|
* |
20
|
|
|
* Required for: |
21
|
|
|
* - Insert Builder |
22
|
|
|
* - Update Builder |
23
|
|
|
* |
24
|
|
|
* @package Bluz\Db\Query\Traits |
25
|
|
|
* @author Anton Shevchuk |
26
|
|
|
*/ |
27
|
|
|
trait Set |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* <code> |
31
|
|
|
* [ |
32
|
|
|
* '`firstName` = ?', |
33
|
|
|
* '`lastName` = ?' |
34
|
|
|
* ] |
35
|
|
|
* </code> |
36
|
|
|
* |
37
|
|
|
* @var array |
38
|
|
|
*/ |
39
|
|
|
protected $set = []; |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Set key-value pair |
43
|
|
|
* |
44
|
|
|
* Sets a new value for a column in a insert/update query |
45
|
|
|
* <code> |
46
|
|
|
* $ub = new UpdateBuilder(); |
47
|
|
|
* $ub |
48
|
|
|
* ->update('users') |
49
|
|
|
* ->set('password', md5('password')) |
50
|
|
|
* ->where('id = ?'); |
51
|
|
|
* </code> |
52
|
|
|
* |
53
|
|
|
* @param string $key The column to set |
54
|
|
|
* @param string|integer $value The value, expression, placeholder, etc |
55
|
|
|
* @param int $type The type of value on of PDO::PARAM_* params |
56
|
|
|
* |
57
|
|
|
* @return $this |
58
|
|
|
*/ |
59
|
2 |
|
public function set(string $key, $value, $type = PDO::PARAM_STR): self |
60
|
|
|
{ |
61
|
2 |
|
$this->setParam(null, $value, $type); |
|
|
|
|
62
|
2 |
|
$this->set[] = Db::quoteIdentifier($key) . ' = ?'; |
63
|
2 |
|
return $this; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Set data from array |
68
|
|
|
* |
69
|
|
|
* <code> |
70
|
|
|
* $ub = new UpdateBuilder(); |
71
|
|
|
* $ub |
72
|
|
|
* ->update('users') |
73
|
|
|
* ->setArray([ |
74
|
|
|
* 'password' => md5('password') |
75
|
|
|
* 'updated' => date('Y-m-d H:i:s') |
76
|
|
|
* ]) |
77
|
|
|
* ->where('u.id = ?'); |
78
|
|
|
* </code> |
79
|
|
|
* |
80
|
|
|
* @param array $data |
81
|
|
|
* |
82
|
|
|
* @return $this |
83
|
|
|
*/ |
84
|
1 |
|
public function setArray(array $data): self |
85
|
|
|
{ |
86
|
1 |
|
foreach ($data as $key => $value) { |
87
|
1 |
|
$this->set($key, $value); |
88
|
|
|
} |
89
|
1 |
|
return $this; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* Prepare string to apply it inside SQL query |
94
|
|
|
* |
95
|
|
|
* @return string |
96
|
|
|
*/ |
97
|
2 |
|
protected function prepareSet(): string |
98
|
|
|
{ |
99
|
2 |
|
return ' SET ' . implode(', ', $this->set); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|