Update namespaces
This commit is contained in:
82
src/Ideal/Query/Update.php
Normal file
82
src/Ideal/Query/Update.php
Normal file
@ -0,0 +1,82 @@
|
||||
<?php
|
||||
namespace Database\Ideal\Query;
|
||||
|
||||
use Database\Ideal\Query;
|
||||
use Database\Define;
|
||||
use Database\Reinforce\Query\{hasConditions, hasTable};
|
||||
|
||||
abstract class Update extends Query implements Define\Query\Update
|
||||
{
|
||||
use hasTable, hasConditions;
|
||||
|
||||
public function __construct(?string $table = null)
|
||||
{
|
||||
if ($table !== null) {
|
||||
$this->table($table);
|
||||
}
|
||||
}
|
||||
public function table(string $table): self
|
||||
{
|
||||
return $this->setTable($table);
|
||||
}
|
||||
public function set(array|string $value_pairs): self
|
||||
{
|
||||
return $this->setValues($value_pairs);
|
||||
}
|
||||
public function where(array|string $conditions): self
|
||||
{
|
||||
return $this->setConditions($conditions);
|
||||
}
|
||||
|
||||
protected array|string $values;
|
||||
|
||||
public function getValues(): array
|
||||
{
|
||||
return $this->values;
|
||||
}
|
||||
|
||||
public function addValue(string|array $values): self
|
||||
{
|
||||
if (is_string($values)) {
|
||||
$this->values []= $values;
|
||||
return $this;
|
||||
}
|
||||
$column = $values['column'] ?? $values[0];
|
||||
$value = $values['value'] ?? $values[1];
|
||||
if (!is_numeric($value)) {
|
||||
$value = "'{$value}'";
|
||||
}
|
||||
$this->values []= "`{$column}` = {$value}";
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setValues(array|string $values): self
|
||||
{
|
||||
if (is_string($values)) {
|
||||
$this->addValue($values);
|
||||
return $this;
|
||||
}
|
||||
foreach ($values as $value) {
|
||||
$this->addValue($value);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
protected function getValuesString(): string
|
||||
{
|
||||
if (!isset($this->values)) {
|
||||
return '';
|
||||
}
|
||||
$values = (is_array($this->getValues())) ? implode(', ', $this->getValues()) : $this->getValues();
|
||||
return " SET {$values}";
|
||||
}
|
||||
|
||||
public function build(): string
|
||||
{
|
||||
return implode('', [
|
||||
"UPDATE {$this->getTable()}",
|
||||
$this->getValuesString(),
|
||||
$this->getConditionsString()
|
||||
]);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user