2025-02-03 17:44:52 +01:00
|
|
|
<?php
|
|
|
|
namespace DatabaseHelper;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
|
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 = [];
|
|
|
|
|
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 15:40:52 +01:00
|
|
|
/**
|
|
|
|
* Adds a single column-value pair to the row.
|
|
|
|
* @param string $col Column name.
|
|
|
|
* @param mixed $val Value to insert.
|
|
|
|
* @return Insertion Current instance for method chaining.
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
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'];
|
2025-02-05 15:40:52 +01:00
|
|
|
$this->currentRow[$col] = $columnType->dbCast($val);
|
2025-02-03 17:44:52 +01:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2025-02-05 15:40:52 +01:00
|
|
|
/**
|
|
|
|
* Adds multiple column-value pairs to the row.
|
|
|
|
* @param array $data Associative array of column-value pairs.
|
|
|
|
* @return Insertion Current instance for method chaining.
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
|
|
|
public function batchData(array $data): Insertion {
|
|
|
|
foreach ($data as $key => $value)
|
|
|
|
$this->data($key, $value);
|
2025-02-03 17:44:52 +01:00
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2025-02-05 15:40:52 +01:00
|
|
|
/**
|
|
|
|
* Finalizes the current row and stacks it for insertion.
|
|
|
|
* @return Insertion Current instance for method chaining.
|
|
|
|
*/
|
|
|
|
public function stack(): Insertion {
|
|
|
|
if (!empty($this->currentRow))
|
|
|
|
$this->stackForInsertion();
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
private function stackForInsertion(): void {
|
|
|
|
$this->batchRows[] = $this->currentRow;
|
|
|
|
$this->currentRow = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Executes the insertion of all batched rows into the database.
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
2025-02-03 17:44:52 +01:00
|
|
|
public function insert(): void {
|
|
|
|
global $wpdb;
|
|
|
|
|
|
|
|
// Convert single to batch queries.
|
2025-02-05 15:40:52 +01:00
|
|
|
if (!empty($this->currentRow))
|
|
|
|
$this->stackForInsertion();
|
2025-02-03 17:44:52 +01:00
|
|
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|