62 lines
1.6 KiB
PHP
62 lines
1.6 KiB
PHP
<?php
|
|
namespace DatabaseHelper;
|
|
|
|
use DatabaseHelper\beans\Schema;
|
|
use InvalidArgumentException;
|
|
|
|
class Insertion
|
|
{
|
|
private Schema $schema;
|
|
private array $currInsert = [];
|
|
private array $batchInserts = [];
|
|
|
|
public function __construct(Schema $table) {
|
|
$this->schema = $table;
|
|
}
|
|
|
|
public function data(string $col, mixed $val): Insertion {
|
|
$this->schema->reqCol($col);
|
|
$info = $this->schema->getCol($col);
|
|
$type = $info->type;
|
|
$this->currInsert[$col] = $type->dbCast($val);
|
|
return $this;
|
|
}
|
|
|
|
public function batchData(array $data): Insertion {
|
|
foreach ($data as $key => $value)
|
|
$this->data($key, $value);
|
|
return $this;
|
|
}
|
|
|
|
public function stack(): Insertion {
|
|
if (!empty($this->currInsert))
|
|
$this->stackForInsertion();
|
|
return $this;
|
|
}
|
|
|
|
private function stackForInsertion(): void {
|
|
$this->batchInserts[] = $this->currInsert;
|
|
$this->currInsert = [];
|
|
}
|
|
|
|
public function insert(): bool {
|
|
global $wpdb;
|
|
|
|
// Convert single to batch queries.
|
|
if (!empty($this->currInsert))
|
|
$this->stackForInsertion();
|
|
|
|
if (empty($this->batchInserts))
|
|
throw new InvalidArgumentException("No data set for insertion.");
|
|
|
|
foreach ($this->batchInserts as $row) {
|
|
if (!empty($row)) {
|
|
$result = $wpdb->insert($this->schema->name, $row);
|
|
if ($result === false)
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
} |