packages/sql-semantics-mysql/src/Statement/Expression/Branching/CaseBranch.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Expression\Branching;
6
7use SqlSemantics\Platform\MySql\Model\Rendering\Output;
8use SqlSemantics\Platform\MySql\Model\Statement\Node;
9use SqlSemantics\Platform\MySql\Model\Statement\Scalar;
10use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
11
12/**
13 * One `WHEN condition THEN result` branch of a CASE expression.
14 *
15 * In a simple CASE the condition is a value compared with the operand; in
16 * a searched CASE it is a truth value. The CASE expression derives both parts.
17 * Source: https://dev.mysql.com/doc/refman/8.4/en/flow-control-functions.html#operator_case.
18 *
19 * @visibility public
20 * @example Reading a branch
21 * $query = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('SELECT a FROM t WHERE CASE WHEN a THEN 1 END');
22 * $query->statement->where->branches[0]->result->text // => '1'
23 */
24final class CaseBranch implements Node
25{
26 use Snapshot;
27
28 /**
29 * @param Scalar $condition The value or condition after WHEN
30 * @param Scalar $result The result after THEN
31 */
32 public function __construct(public readonly Scalar $condition, public readonly Scalar $result)
33 {
34 }
35
36 /**
37 * Writes WHEN, the condition, THEN and the result.
38 */
39 public function render(Output $out): void
40 {
41 $out->keyword('WHEN')->node($this->condition)->keyword('THEN')->node($this->result);
42 }
43}
44