Files
query_builder/src/Alias/Database/Query/Update.php
2022-09-08 17:42:20 -04:00

92 lines
2.3 KiB
PHP

<?php
namespace ProVM\Alias\Database\Query;
use ProVM\Alias\Database\Query;
use ProVM\Concept\Database\Query\Update as UpdateInterface;
abstract class Update extends Query implements UpdateInterface
{
public function table(string $table): UpdateInterface
{
return $this->setTable($table);
}
public function set(array $value_pairs): UpdateInterface
{
return $this->setValues($value_pairs);
}
public function where(array $conditions): UpdateInterface
{
return $this->setConditions($conditions);
}
protected string $table;
public function setTable(string $table): UpdateInterface
{
$this->table = $table;
return $this;
}
public function getTable(): string
{
return $this->table;
}
protected array $values;
public function setValues(array $values): UpdateInterface
{
foreach ($values as $value) {
$column = $value['column'] ?? $value[0];
$val = $value['value'] ?? $value[1];
$this->addValue($column, $val);
}
return $this;
}
public function addValue(string $column, int|string $value): UpdateInterface
{
if (!is_numeric($value)) {
$value = "'{$value}'";
}
$this->values []= "`{$column}` = {$value}";
return $this;
}
public function getValues(): array
{
return $this->values;
}
public function getValueString(): string
{
return implode(', ', $this->getValues());
}
protected array $conditions;
public function setConditions(array $conditions): UpdateInterface
{
foreach ($conditions as $condition) {
$this->addCondition($condition);
}
return $this;
}
public function addCondition(string $expression): UpdateInterface
{
$this->conditions []= $expression;
return $this;
}
public function getConditions(): array
{
return $this->conditions;
}
public function getConditionString(): string
{
return implode(' ', $this->getConditions());
}
public function build(): string
{
return implode(' ', [
'UPDATE',
$this->getTable(),
'SET',
$this->getValueString(),
'WHERE',
$this->getConditionString()
]);
}
}