2025-02-03 17:44:52 +01:00
|
|
|
<?php
|
|
|
|
namespace DatabaseHelper;
|
|
|
|
|
2025-02-05 12:29:49 +01:00
|
|
|
namespace DatabaseHelper;
|
2025-02-03 17:44:52 +01:00
|
|
|
use DatabaseHelper\enums\ColumnTypes;
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use wpdb;
|
|
|
|
|
|
|
|
global $wpdb;
|
|
|
|
|
2025-02-05 12:29:49 +01:00
|
|
|
class Insertion
|
2025-02-03 17:44:52 +01:00
|
|
|
{
|
2025-02-05 12:29:49 +01:00
|
|
|
private Table $table;
|
2025-02-03 17:44:52 +01:00
|
|
|
private array $currentRow = [];
|
|
|
|
private array $batchRows = [];
|
|
|
|
private bool $isReady = false;
|
|
|
|
|
2025-02-05 12:29:49 +01:00
|
|
|
public function __construct(Table $table) {
|
2025-02-03 17:44:52 +01:00
|
|
|
$this->table = $table;
|
|
|
|
}
|
|
|
|
|
2025-02-05 12:29:49 +01:00
|
|
|
public function data(string $col, mixed $val): Insertion {
|
2025-02-03 17:44:52 +01:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2025-02-05 12:29:49 +01:00
|
|
|
public function done(): Insertion {
|
2025-02-03 17:44:52 +01:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|