packages/sql-formatter/src/Core/Syntax/Brackets.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlFormatter\Core\Syntax;
6
7/**
8 * Pairs parentheses and identifies nested query blocks.
9 *
10 * @visibility SqlFormatter
11 */
12final class Brackets
13{
14 /**
15 * Pairs delimiters and marks parentheses containing a query.
16 */
17 public static function mark(Document $document): void
18 {
19 $stack = [];
20 foreach ($document->tokens as $index => $token) {
21 if ($token->text === '(') {
22 $stack[] = $index;
23 } elseif ($token->text === ')' && $stack !== []) {
24 $open = array_pop($stack);
25 $document->pairs[$open] = $index;
26 }
27 }
28 foreach ($document->pairs as $open => $close) {
29 if (isset($document->clauses[$open + 1])) {
30 $document->blocks[$open] = true;
31 }
32 }
33 }
34}
35