WP-Database-Helper/Deletion.php
2025-02-21 19:06:16 +01:00

64 lines
1.5 KiB
PHP

<?php
namespace DatabaseHelper;
use DatabaseHelper\beans\Schema;
use Exception;
use InvalidArgumentException;
class Deletion
{
use Conditionable;
protected Schema $table;
public function __construct(Schema $table) {
$this->table = $table;
}
/**
* Generates the SQL statement.
* @return string SQL query.
* @throws InvalidArgumentException
*/
public function toSql(): string {
$table = $this->table->name;
$whereClause = $this->combineConditions();
if (!$this->isConditioned())
throw new InvalidArgumentException("Deletions need to be conditioned.");
return "DELETE FROM $table WHERE $whereClause";
}
/**
* Executes the DELETE query.
* @return int Number of affected rows.
* @throws Exception
*/
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);
}
/**
* Clears all entries from the table.
* @return int Number of affected rows.
* @throws Exception
*/
public function truncate(): int {
global $wpdb;
$table = $this->table->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);
}
}