forked from tpetry/laravel-query-expressions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaseGroup.php
38 lines (31 loc) · 1.05 KB
/
CaseGroup.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
declare(strict_types=1);
namespace Tpetry\QueryExpressions\Language;
use Illuminate\Contracts\Database\Query\ConditionExpression;
use Illuminate\Database\Grammar;
use Tpetry\QueryExpressions\Concerns\IdentifiesDriver;
use Tpetry\QueryExpressions\Concerns\StringizeExpression;
class CaseGroup implements ConditionExpression
{
use IdentifiesDriver;
use StringizeExpression;
/**
* @param non-empty-array<int, CaseRule> $when
*/
public function __construct(
private readonly array $when,
private readonly string|Expression|null $else = null,
) {}
public function getValue(Grammar $grammar): string
{
$conditions = array_map(
callback: fn ($expression) => $this->stringize($grammar, $expression),
array: $this->when,
);
$conditions = implode(' ', $conditions);
return match ($this->else) {
null => "(case {$conditions} end)",
default => "(case {$conditions} else {$this->stringize($grammar, $this->else)} end)",
};
}
}