WP-Query-Builder/Insertion.php

78 lines
2.2 KiB
PHP
Raw Normal View History

<?php
namespace DatabaseHelper;
use InvalidArgumentException;
2025-02-05 12:29:49 +01:00
class Insertion
{
2025-02-05 16:10:30 +01:00
private Schema $table;
private array $currentRow = [];
private array $batchRows = [];
2025-02-05 16:10:30 +01:00
public function __construct(Schema $table) {
$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 {
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);
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);
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
*/
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();
if (empty($this->batchRows))
throw new InvalidArgumentException("No data set for insertion.");
foreach ($this->batchRows as $row)
if (!empty($row))
2025-02-05 16:10:30 +01:00
$wpdb->insert($this->table->name, $row);
}
}