2020-04-02 00:02:51 +02:00
|
|
|
<?php
|
|
|
|
|
2022-11-18 18:06:46 +01:00
|
|
|
namespace Core\Driver\SQL\Query;
|
2020-04-02 00:02:51 +02:00
|
|
|
|
2022-11-18 18:06:46 +01:00
|
|
|
use Core\Driver\SQL\Condition\CondOr;
|
|
|
|
use Core\Driver\SQL\SQL;
|
2020-04-04 01:15:59 +02:00
|
|
|
|
2020-04-02 00:02:51 +02:00
|
|
|
class Update extends Query {
|
|
|
|
|
2020-04-03 17:39:58 +02:00
|
|
|
private array $values;
|
|
|
|
private string $table;
|
|
|
|
private array $conditions;
|
2020-04-02 00:02:51 +02:00
|
|
|
|
2021-04-02 21:58:06 +02:00
|
|
|
public function __construct(SQL $sql, string $table) {
|
2020-04-02 00:02:51 +02:00
|
|
|
parent::__construct($sql);
|
|
|
|
$this->values = array();
|
|
|
|
$this->table = $table;
|
|
|
|
$this->conditions = array();
|
|
|
|
}
|
|
|
|
|
2021-04-02 21:58:06 +02:00
|
|
|
public function where(...$conditions): Update {
|
2020-04-04 01:15:59 +02:00
|
|
|
$this->conditions[] = (count($conditions) === 1 ? $conditions : new CondOr($conditions));
|
2020-04-02 00:02:51 +02:00
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2021-04-02 21:58:06 +02:00
|
|
|
public function set(string $key, $val): Update {
|
2020-04-02 00:02:51 +02:00
|
|
|
$this->values[$key] = $val;
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2021-04-02 21:58:06 +02:00
|
|
|
public function getTable(): string { return $this->table; }
|
|
|
|
public function getConditions(): array { return $this->conditions; }
|
|
|
|
public function getValues(): array { return $this->values; }
|
2021-04-08 18:29:47 +02:00
|
|
|
|
2021-04-09 16:05:36 +02:00
|
|
|
public function build(array &$params): ?string {
|
2021-04-08 18:29:47 +02:00
|
|
|
$table = $this->sql->tableName($this->getTable());
|
|
|
|
|
|
|
|
$valueStr = array();
|
|
|
|
foreach($this->getValues() as $key => $val) {
|
|
|
|
$valueStr[] = $this->sql->columnName($key) . "=" . $this->sql->addValue($val, $params);
|
|
|
|
}
|
|
|
|
$valueStr = implode(",", $valueStr);
|
|
|
|
|
|
|
|
$where = $this->sql->getWhereClause($this->getConditions(), $params);
|
|
|
|
return "UPDATE $table SET $valueStr$where";
|
|
|
|
}
|
2020-04-03 17:39:58 +02:00
|
|
|
}
|