50 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
			
		
		
	
	
			50 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			PHP
		
	
	
	
	
	
<?php
 | 
						|
namespace DatabaseHelper;
 | 
						|
 | 
						|
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 {
 | 
						|
        $this->schema->requireColumn($col);
 | 
						|
 | 
						|
        // Convert the operator string to a ConditionOperator enum if needed.
 | 
						|
        if (is_string($operator))
 | 
						|
            $operator = Operator::fromString($operator);
 | 
						|
 | 
						|
        $columnType = $this->schema->columnType($col);
 | 
						|
        $castedValue = $columnType->dbCast($val);
 | 
						|
 | 
						|
        if (!empty($this->conditions))
 | 
						|
            $this->conditions[] = $prefix;
 | 
						|
        $this->conditions[] = "$col " . $operator->toString() . " $castedValue";
 | 
						|
 | 
						|
        return $this;
 | 
						|
    }
 | 
						|
 | 
						|
    public function isConditioned(): bool {
 | 
						|
        return !empty($this->conditions);
 | 
						|
    }
 | 
						|
 | 
						|
    protected function combineConditions(): string {
 | 
						|
        if ($this->isConditioned())
 | 
						|
            return implode(" ", $this->conditions);
 | 
						|
        return "";
 | 
						|
    }
 | 
						|
}
 |