packages/sql-semantics-sqlite/src/Model/Rendering/Lexical.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\Sqlite\Model\Rendering;
6
7/**
8 * Joins output pieces into SQL text with a fixed, minimal spacing rule.
9 *
10 * Pieces are separated by one space, except around punctuation that never
11 * merges with a neighbour, where a node asked for glue, and inside a spelled
12 * region, where the layout's trivia is written. The rule performs
13 * no formatting and no normalization of the pieces themselves.
14 *
15 * @visibility SqlSemantics
16 */
17final class Lexical
18{
19 /**
20 * Joins the pieces into text.
21 *
22 * @param list<Piece> $pieces
23 */
24 public function join(array $pieces): string
25 {
26 $sql = '';
27 $previous = null;
28 foreach ($pieces as $piece) {
29 if ($previous !== null && $piece->gap !== null) {
30 $sql .= $piece->gap;
31 } elseif ($previous !== null && !$this->tight($previous, $piece)) {
32 $sql .= ' ';
33 }
34 $sql .= $piece->text;
35 $previous = $piece;
36 }
37
38 return $sql;
39 }
40
41 /**
42 * Decides whether two neighbouring pieces are written without a space.
43 */
44 public function tight(Piece $left, Piece $right): bool
45 {
46 if ($right->glued) {
47 return true;
48 }
49 if ($right->kind === PieceKind::Symbol && in_array($right->text, [',', ')', ']', ';', '.'], true)) {
50 return true;
51 }
52
53 return $left->kind === PieceKind::Symbol && in_array($left->text, ['(', '[', '.'], true);
54 }
55}
56