Files
kiri-databases/Traits/When.php
T

79 lines
1.5 KiB
PHP
Raw Normal View History

2022-01-09 03:49:51 +08:00
<?php
2023-04-16 01:45:33 +08:00
declare(strict_types=1);
2022-01-09 03:49:51 +08:00
namespace Database\Traits;
use Database\ActiveQuery;
use Database\ISqlBuilder;
use Exception;
use JetBrains\PhpStorm\Pure;
/**
* Class CaseWhen
* @package Database\Traits
*/
class When
{
2023-12-12 15:35:35 +08:00
public ActiveQuery|ISqlBuilder $query;
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
private array $_condition = [];
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
private string $else = '';
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
/**
* CaseWhen constructor.
* @param string $column
* @param ActiveQuery|ISqlBuilder $activeQuery
*/
public function __construct(public string $column, public ActiveQuery|ISqlBuilder $activeQuery)
{
$this->_condition[] = 'CASE ' . $column;
}
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
/**
* @param string|int $condition
* @param string $then
* @return $this
* @throws
*/
public function when(string|int $condition, string $then): static
{
$this->_condition[] = sprintf('WHEN %s THEN %s', $condition, $then);
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
return $this;
}
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
/**
* @param string $alias
*/
public function else(string $alias): void
{
$this->else = $alias;
}
2022-01-09 03:49:51 +08:00
2023-12-12 15:35:35 +08:00
/**
* @return string
*/
#[Pure] public function end(): string
2023-07-31 23:08:59 +08:00
{
2023-12-12 15:35:35 +08:00
if (empty($this->_condition)) {
return '';
}
$prefix = implode(' ', $this->_condition);
if (!empty($this->else)) {
$prefix .= ' ELSE ' . $this->else;
}
return '(' . $prefix . ' END)';
}
2022-01-09 03:49:51 +08:00
}