54 lines
1.4 KiB
PHP
54 lines
1.4 KiB
PHP
<?php
|
|
namespace DatabaseHelper;
|
|
|
|
use DatabaseHelper\beans\Schema;
|
|
use DatabaseHelper\enums\Type;
|
|
use DatabaseHelper\enums\Operator;
|
|
use InvalidArgumentException;
|
|
|
|
class Update
|
|
{
|
|
use Conditionable;
|
|
|
|
protected Schema $schema;
|
|
protected array $values = [];
|
|
|
|
public function __construct(Schema $table) {
|
|
$this->schema = $table;
|
|
}
|
|
|
|
public function set(string $col, mixed $val): self {
|
|
$info = $this->schema->cols[$col];
|
|
$type = $info->type;
|
|
$castedValue = $type->dbCast($val);
|
|
$this->values[$col] = $castedValue;
|
|
return $this;
|
|
}
|
|
|
|
public function toSql(): string {
|
|
if (empty($this->values))
|
|
throw new InvalidArgumentException("No values have been set for the Update.");
|
|
|
|
$table = $this->schema->name;
|
|
$setParts = [];
|
|
foreach ($this->values as $col => $value)
|
|
$setParts[] = "$col = $value";
|
|
$setClause = implode(", ", $setParts);
|
|
|
|
// FINAL SQL STATEMENT
|
|
$update = "UPDATE $table SET $setClause";
|
|
if($this->isConditioned()) {
|
|
$whereClause = $this->combineConditions();
|
|
$update .= " WHERE $whereClause";
|
|
}
|
|
return $update;
|
|
}
|
|
|
|
public function update(): bool {
|
|
global $wpdb;
|
|
$query = $this->toSql();
|
|
$result = $wpdb->query($query);
|
|
return boolval($result);
|
|
}
|
|
}
|