WP-Database-Helper/Deletion.php
2025-02-24 10:54:51 +01:00

49 lines
1.2 KiB
PHP

<?php
namespace DatabaseHelper;
use DatabaseHelper\beans\Schema;
use Exception;
use InvalidArgumentException;
class Deletion
{
use Conditionable;
protected Schema $schema;
public function __construct(Schema $table) {
$this->schema = $table;
}
public function toSql(): string {
$table = $this->schema->name;
$whereClause = $this->combineConditions();
if (!$this->isConditioned())
throw new InvalidArgumentException("Deletions need to be conditioned.");
return "DELETE FROM $table WHERE $whereClause";
}
public function delete(): int {
global $wpdb;
$query = $this->toSql();
$result = $wpdb->query($query);
if ($result === false)
throw new Exception("Deletion failed: " . $wpdb->last_error . ".");
return intval($result);
}
public function truncate(): int {
global $wpdb;
$table = $this->schema->name;
$query = esc_sql("TRUNCATE TABLE $table");
$result = $wpdb->query($query);
if ($result === false)
throw new Exception("Truncation failed: " . $wpdb->last_error . ".");
return intval($result);
}
}