| 1 |
<?php |
| 2 |
|
| 3 |
namespace CodesVault\Howdyqb\Statement; |
| 4 |
|
| 5 |
use CodesVault\Howdyqb\Api\UpdateInterface; |
| 6 |
use CodesVault\Howdyqb\Clause\WhereClause; |
| 7 |
use CodesVault\Howdyqb\QueryFactory; |
| 8 |
use CodesVault\Howdyqb\SqlGenerator; |
| 9 |
use CodesVault\Howdyqb\Utilities; |
| 10 |
|
| 11 |
class Update implements UpdateInterface |
| 12 |
{ |
| 13 |
// Bring all SQL where clause |
| 14 |
use WhereClause; |
| 15 |
|
| 16 |
protected $db; |
| 17 |
protected $data = []; |
| 18 |
public $sql = []; |
| 19 |
protected $params = []; |
| 20 |
protected $table_name; |
| 21 |
|
| 22 |
public function __construct($db, string $table_name, array $data) |
| 23 |
{ |
| 24 |
$this->db = $db; |
| 25 |
|
| 26 |
$this->data = $data; |
| 27 |
$this->table_name = $this->get_table_prefix()->prefix . $table_name; |
| 28 |
$this->sql['set_columns'] = $this->set_columns(); |
| 29 |
} |
| 30 |
|
| 31 |
private function driver_execute($sql) |
| 32 |
{ |
| 33 |
$driver = $this->db; |
| 34 |
if (class_exists('wpdb') && $driver instanceof \wpdb) { |
| 35 |
return $driver->query($driver->prepare($sql, $this->params)); |
| 36 |
} |
| 37 |
|
| 38 |
$data = $driver->prepare($sql); |
| 39 |
try { |
| 40 |
return $data->execute($this->params); |
| 41 |
} catch (\Exception $exception) { |
| 42 |
Utilities::throughException($exception); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
private function update_data() |
| 47 |
{ |
| 48 |
$query = SqlGenerator::update($this->sql); |
| 49 |
|
| 50 |
$this->driver_execute($query); |
| 51 |
} |
| 52 |
|
| 53 |
public function execute() |
| 54 |
{ |
| 55 |
$this->start(); |
| 56 |
$this->update_data(); |
| 57 |
} |
| 58 |
|
| 59 |
// get only sql query string |
| 60 |
public function getSql() |
| 61 |
{ |
| 62 |
$this->start(); |
| 63 |
$query = [ |
| 64 |
'query' => SqlGenerator::update($this->sql), |
| 65 |
'params' => $this->params, |
| 66 |
]; |
| 67 |
return $query; |
| 68 |
} |
| 69 |
|
| 70 |
private function get_table_prefix() |
| 71 |
{ |
| 72 |
if (empty(QueryFactory::getConfig())) { |
| 73 |
global $wpdb; |
| 74 |
return $wpdb; |
| 75 |
} |
| 76 |
return QueryFactory::getConfig(); |
| 77 |
} |
| 78 |
|
| 79 |
protected function start() |
| 80 |
{ |
| 81 |
$this->sql['start'] = 'UPDATE ' . $this->table_name; |
| 82 |
} |
| 83 |
|
| 84 |
protected function set_columns() |
| 85 |
{ |
| 86 |
if (empty($this->data)) return; |
| 87 |
|
| 88 |
$columns = []; |
| 89 |
foreach ($this->data as $column => $value) { |
| 90 |
$columns[] = $column . '=' . Utilities::get_placeholder($this->db, $value); |
| 91 |
$this->params[] = $value; |
| 92 |
} |
| 93 |
return 'SET ' . implode(', ', $columns); |
| 94 |
} |
| 95 |
} |
| 96 |
|