WP-Query-Builder/Insertion.php
2025-02-03 17:44:52 +01:00

59 lines
1.6 KiB
PHP

<?php
namespace DatabaseHelper;
use DatabaseHelper\interfaces\InsertionBuilder;
use DatabaseHelper\interfaces\TableBlueprint;
use DatabaseHelper\enums\ColumnTypes;
use InvalidArgumentException;
use wpdb;
global $wpdb;
class Insertion implements InsertionBuilder
{
private TableBlueprint $table;
private array $currentRow = [];
private array $batchRows = [];
private bool $isReady = false;
public function __construct(TableBlueprint $table) {
$this->table = $table;
}
public function data(string $col, mixed $val): InsertionBuilder {
if (!isset($this->table->columns[$col]))
throw new InvalidArgumentException("Column '$col' does not exist.");
$columnType = $this->table->columns[$col]['colType'];
$this->currentRow[$col] = $columnType->valCast($val);
return $this;
}
public function done(): InsertionBuilder {
if (!empty($this->currentRow)) {
$this->batchRows[] = $this->currentRow;
$this->currentRow = [];
}
$this->isReady = true;
return $this;
}
public function insert(): void {
global $wpdb;
// Convert single to batch queries.
if (!$this->isReady and !empty($this->currentRow)) {
$this->batchRows[] = $this->currentRow;
$this->currentRow = [];
$this->isReady = true;
}
if (empty($this->batchRows))
throw new InvalidArgumentException("No data set for insertion.");
foreach ($this->batchRows as $row)
if (!empty($row))
$wpdb->insert($this->table->tableName, $row);
}
}