WP-Database-Helper/Insertion.php

62 lines
1.6 KiB
PHP
Raw Normal View History

2025-02-12 14:03:39 +00:00
<?php
namespace DatabaseHelper;
2025-02-21 18:06:16 +00:00
use DatabaseHelper\beans\Schema;
2025-02-12 14:03:39 +00:00
use InvalidArgumentException;
class Insertion
{
2025-02-24 09:54:51 +00:00
private Schema $schema;
private array $currInsert = [];
private array $batchInserts = [];
2025-02-12 14:03:39 +00:00
public function __construct(Schema $table) {
2025-02-24 09:54:51 +00:00
$this->schema = $table;
2025-02-12 14:03:39 +00:00
}
public function data(string $col, mixed $val): Insertion {
2025-02-24 09:54:51 +00:00
$this->schema->reqCol($col);
$info = $this->schema->getCol($col);
$type = $info->type;
$this->currInsert[$col] = $type->dbCast($val);
2025-02-12 14:03:39 +00:00
return $this;
}
public function batchData(array $data): Insertion {
foreach ($data as $key => $value)
$this->data($key, $value);
return $this;
}
public function stack(): Insertion {
2025-02-24 09:54:51 +00:00
if (!empty($this->currInsert))
2025-02-12 14:03:39 +00:00
$this->stackForInsertion();
return $this;
}
private function stackForInsertion(): void {
2025-02-24 09:54:51 +00:00
$this->batchInserts[] = $this->currInsert;
$this->currInsert = [];
2025-02-12 14:03:39 +00:00
}
public function insert(): bool {
global $wpdb;
// Convert single to batch queries.
2025-02-24 09:54:51 +00:00
if (!empty($this->currInsert))
2025-02-12 14:03:39 +00:00
$this->stackForInsertion();
2025-02-24 09:54:51 +00:00
if (empty($this->batchInserts))
2025-02-12 14:03:39 +00:00
throw new InvalidArgumentException("No data set for insertion.");
2025-02-24 09:54:51 +00:00
foreach ($this->batchInserts as $row) {
2025-02-12 14:03:39 +00:00
if (!empty($row)) {
2025-02-24 09:54:51 +00:00
$result = $wpdb->insert($this->schema->name, $row);
2025-02-12 14:03:39 +00:00
if ($result === false)
return false;
}
}
return true;
}
}