WP-Database-Helper/Deletion.php

49 lines
1.2 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 Exception;
use InvalidArgumentException;
class Deletion
{
use Conditionable;
2025-02-24 09:54:51 +00:00
protected Schema $schema;
2025-02-12 14:03:39 +00:00
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 toSql(): string {
2025-02-24 09:54:51 +00:00
$table = $this->schema->name;
2025-02-12 14:03:39 +00:00
$whereClause = $this->combineConditions();
if (!$this->isConditioned())
throw new InvalidArgumentException("Deletions need to be conditioned.");
2025-02-12 15:55:03 +00:00
return "DELETE FROM $table WHERE $whereClause";
2025-02-12 14:03:39 +00:00
}
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;
2025-02-24 09:54:51 +00:00
$table = $this->schema->name;
2025-02-12 14:03:39 +00:00
$query = esc_sql("TRUNCATE TABLE $table");
$result = $wpdb->query($query);
if ($result === false)
throw new Exception("Truncation failed: " . $wpdb->last_error . ".");
return intval($result);
}
}