WP-Database-Helper/Update.php

54 lines
1.4 KiB
PHP
Raw Normal View History

2025-02-12 14:03:39 +00:00
<?php
namespace DatabaseHelper;
2025-02-21 18:06:16 +00:00
use DatabaseHelper\beans\Schema;
2025-02-12 14:03:39 +00:00
use DatabaseHelper\enums\Type;
use DatabaseHelper\enums\Operator;
use InvalidArgumentException;
class Update
{
use Conditionable;
2025-02-24 09:54:51 +00:00
protected Schema $schema;
2025-02-12 14:03:39 +00:00
protected array $values = [];
public function __construct(Schema $table) {
2025-02-24 09:54:51 +00:00
$this->schema = $table;
2025-02-12 14:03:39 +00:00
}
public function set(string $col, mixed $val): self {
2025-02-24 09:54:51 +00:00
$info = $this->schema->cols[$col];
$type = $info->type;
$castedValue = $type->dbCast($val);
2025-02-12 14:03:39 +00:00
$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.");
2025-02-24 09:54:51 +00:00
$table = $this->schema->name;
2025-02-12 14:03:39 +00:00
$setParts = [];
foreach ($this->values as $col => $value)
$setParts[] = "$col = $value";
$setClause = implode(", ", $setParts);
// FINAL SQL STATEMENT
2025-02-12 15:55:03 +00:00
$update = "UPDATE $table SET $setClause";
2025-02-12 14:03:39 +00:00
if($this->isConditioned()) {
$whereClause = $this->combineConditions();
2025-02-12 15:55:03 +00:00
$update .= " WHERE $whereClause";
2025-02-12 14:03:39 +00:00
}
2025-02-12 15:55:03 +00:00
return $update;
2025-02-12 14:03:39 +00:00
}
public function update(): bool {
global $wpdb;
$query = $this->toSql();
$result = $wpdb->query($query);
return boolval($result);
}
}