Database/src/Query/Join/JoinBuilder.php

76 lines
1.9 KiB
PHP
Raw Normal View History

2024-11-08 16:33:44 +01:00
<?php
namespace Nest\Database\Query\Join;
use Nest\Database\Query\Where\ConditionBuilder;
class JoinBuilder
{
const string INNER = "INNER";
const string OUTER = "OUTER";
const string LEFT = "LEFT";
const string RIGHT = "RIGHT";
/**
* @param mixed $query The calling query.
* @param string $type Join type (INNER, OUTER, LEFT, RIGHT, ...).
* @param string $table The table to join.
*/
public function __construct(protected mixed $query, public readonly string $type, public readonly string $table)
{}
/**
* ON conditions of the JOIN clause.
* @var ConditionBuilder[]
*/
protected array $on = [];
/**
* Reset ON conditions.
* @return $this
*/
public function resetOn(): static
{
$this->on = [];
return $this;
}
/**
* Add a ON condition.
* @param string|callable $column The column of the condition, or a condition builder callable.
* @param string $operator The operator of the condition (or the value column if no value is passed).
* @param string|null $valueColumn The value column of the condition.
* @return mixed The query.
*/
public function on(string|callable $column, string $operator, string $valueColumn = null): mixed
{
if (is_callable($column))
{ // Callable condition builder.
$this->on[] = $column(new ConditionBuilder());
}
else
{ // Simple condition, registering it.
if (!empty($operator) && empty($valueColumn))
{ // If there are 2 parameters, considering the second one as the value, with default operator.
$valueColumn = $operator;
// Default operator: "=".
$operator = "=";
}
// Create the simple condition.
$this->on[] = (new ConditionBuilder())->column($column)->operator($operator)->column($valueColumn);
}
return $this->query;
}
/**
* Get join conditions.
* @return ConditionBuilder[] ON conditions of the JOIN clause.
*/
public function getConditions(): array
{
return $this->on;
}
}