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 DatabaseHelper\enums\Operator;
|
|
|
|
|
|
|
|
trait Conditionable
|
|
|
|
{
|
|
|
|
protected array $conditions = [];
|
|
|
|
protected Schema $schema;
|
|
|
|
|
|
|
|
public function where(string $col, string|Operator $operator, mixed $val): self {
|
|
|
|
return $this->addCondition($col, $operator, $val, "AND");
|
|
|
|
}
|
|
|
|
|
|
|
|
public function andWhere(string $col, string|Operator $operator, mixed $val): self {
|
|
|
|
return $this->addCondition($col, $operator, $val, "AND");
|
|
|
|
}
|
|
|
|
|
|
|
|
public function orWhere(string $col, string|Operator $operator, mixed $val): self {
|
|
|
|
return $this->addCondition($col, $operator, $val, "OR");
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function addCondition(string $col, string|Operator $operator, mixed $val, string $prefix): self {
|
2025-02-24 09:54:51 +00:00
|
|
|
$this->schema->reqCol($col);
|
|
|
|
$info = $this->schema->getCol($col);
|
2025-02-12 14:03:39 +00:00
|
|
|
|
|
|
|
// Convert the operator string to a ConditionOperator enum if needed.
|
|
|
|
if (is_string($operator))
|
|
|
|
$operator = Operator::fromString($operator);
|
|
|
|
|
2025-02-24 09:54:51 +00:00
|
|
|
$type = $info->type;
|
|
|
|
$castedVal = $type->dbCast($val);
|
2025-02-12 14:03:39 +00:00
|
|
|
|
|
|
|
if (!empty($this->conditions))
|
|
|
|
$this->conditions[] = $prefix;
|
2025-02-24 09:54:51 +00:00
|
|
|
$this->conditions[] = "$col " . $operator->toString() . " $castedVal";
|
2025-02-12 14:03:39 +00:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function isConditioned(): bool {
|
|
|
|
return !empty($this->conditions);
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function combineConditions(): string {
|
|
|
|
if ($this->isConditioned())
|
|
|
|
return implode(" ", $this->conditions);
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
}
|