WP-Database-Helper/Insertion.php

84 lines
2.3 KiB
PHP
Raw Normal View History

2025-02-12 14:03:39 +00:00
<?php
namespace DatabaseHelper;
use InvalidArgumentException;
class Insertion
{
private Schema $table;
private array $currentRow = [];
private array $batchRows = [];
public function __construct(Schema $table) {
$this->table = $table;
}
/**
* 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
*/
public function data(string $col, mixed $val): Insertion {
if (!isset($this->table->columns[$col]))
throw new InvalidArgumentException("Column '$col' does not exist.");
$columnType = $this->table->columns[$col]['colType'];
$this->currentRow[$col] = $columnType->dbCast($val);
return $this;
}
/**
* 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);
return $this;
}
/**
* 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
*/
public function insert(): bool {
global $wpdb;
// Convert single to batch queries.
if (!empty($this->currentRow))
$this->stackForInsertion();
if (empty($this->batchRows))
throw new InvalidArgumentException("No data set for insertion.");
foreach ($this->batchRows as $row) {
if (!empty($row)) {
$result = $wpdb->insert($this->table->name, $row);
if ($result === false)
return false;
}
}
return true;
}
}