packages/sql-semantics-mysql/src/Statement/Query/OrderItem.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Query;
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 ordering or grouping expression with the direction written after it.
14 *
15 * It is the item of ORDER BY, of the GROUP BY of releases that accept a
16 * direction there, of GROUP_CONCAT ... ORDER BY, and of the PARTITION BY and
17 * ORDER BY of a window. No direction means ascending order; the absence is
18 * kept as written. The statement that holds the item derives its expression.
19 * Source: https://dev.mysql.com/doc/refman/8.4/en/sorting-rows.html.
20 *
21 * @visibility public
22 * @example Holding an ordering expression and its direction
23 * $item = new \SqlSemantics\Platform\MySql\Statement\Query\OrderItem(new \SqlSemantics\Platform\MySql\Statement\Name\ColumnUse(new \SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name('a')), \SqlSemantics\Platform\MySql\Statement\Query\Direction::Descending);
24 * [$item->expression->name->value, $item->direction] // => ['a', \SqlSemantics\Platform\MySql\Statement\Query\Direction::Descending]
25 */
26final class OrderItem implements Node
27{
28 use Snapshot;
29
30 /**
31 * @param Scalar $expression The ordering expression
32 * @param Direction|null $direction The direction, when written
33 */
34 public function __construct(public readonly Scalar $expression, public readonly ?Direction $direction = null)
35 {
36 }
37
38 /**
39 * Writes the expression and the direction.
40 */
41 public function render(Output $out): void
42 {
43 $out->node($this->expression);
44 if ($this->direction !== null) {
45 $out->keyword($this->direction->value);
46 }
47 }
48}
49