52 lines
1.4 KiB
PHP
52 lines
1.4 KiB
PHP
<?php
|
|
namespace DatabaseHelper;
|
|
|
|
use DatabaseHelper\enums\ColumnTypes;
|
|
use InvalidArgumentException;
|
|
|
|
class Query
|
|
{
|
|
use Conditionable;
|
|
|
|
protected Schema $table;
|
|
protected array $columns = ['*'];
|
|
|
|
public function __construct(Schema $table) {
|
|
$this->table = $table;
|
|
}
|
|
|
|
public function select(string ...$cols): Query {
|
|
if (!empty($cols))
|
|
$this->columns = $cols;
|
|
|
|
// Validate colum existence
|
|
foreach ($cols as $col)
|
|
if (!$this->table->existsColumn($col))
|
|
throw new InvalidArgumentException("Unknown column: $col");
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function toSql(): string {
|
|
$columns = implode(", ", $this->columns);
|
|
$table = $this->table->name;
|
|
$whereClause = $this->combineConditions();
|
|
return esc_sql("SELECT $columns FROM $table WHERE $whereClause");
|
|
}
|
|
|
|
public function query(): array {
|
|
global $wpdb;
|
|
$query = $this->toSql();
|
|
$results = $wpdb->get_results($wpdb->prepare($query), ARRAY_A);
|
|
return $this->castResults($results);
|
|
}
|
|
|
|
protected function castResults(array $results): array {
|
|
foreach ($results as &$row)
|
|
foreach ($row as $column => &$value)
|
|
if (isset($this->columnTypes[$column]))
|
|
$value = $this->columnTypes[$column]->valCast($value);
|
|
return $results;
|
|
}
|
|
}
|