WP-Query-Builder/Insertion.php

58 lines
1.5 KiB
PHP
Raw Permalink Normal View History

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