WP-Database-Helper/Update.php
2025-02-12 15:03:39 +01:00

70 lines
1.8 KiB
PHP

<?php
namespace DatabaseHelper;
use DatabaseHelper\enums\Type;
use DatabaseHelper\enums\Operator;
use InvalidArgumentException;
class Update
{
use Conditionable;
protected Schema $table;
protected array $values = [];
public function __construct(Schema $table) {
$this->table = $table;
}
/**
* Sets a new value for a column.
* @param string $col Column name.
* @param mixed $val Value to set.
* @return self Current instance for method chaining.
* @throws InvalidArgumentException
*/
public function set(string $col, mixed $val): self {
$this->table->requireColumn($col);
$columnType = $this->table->columnType($col);
$castedValue = $columnType->dbCast($val);
$this->values[$col] = $castedValue;
return $this;
}
/**
* Generates the SQL statement.
* @return string SQL query.
* @throws InvalidArgumentException
*/
public function toSql(): string {
if (empty($this->values))
throw new InvalidArgumentException("No values have been set for the Update.");
$table = $this->table->name;
$setParts = [];
foreach ($this->values as $col => $value)
$setParts[] = "$col = $value";
$setClause = implode(", ", $setParts);
// FINAL SQL STATEMENT
$sqlStatement = "UPDATE $table SET $setClause";
if($this->isConditioned()) {
$whereClause = $this->combineConditions();
$sqlStatement .= " WHERE $whereClause";
}
return esc_sql($sqlStatement);
}
/**
* Executes the SQL UPDATE query.
* @return bool Returns true on success.
*/
public function update(): bool {
global $wpdb;
$query = $this->toSql();
$result = $wpdb->query($query);
return boolval($result);
}
}