packages/ztd-query-sqlite/src/Sql/Lexing/QuotedSpan.php

1<?php
2
3declare(strict_types=1);
4
5namespace ZtdQuery\Platform\Sqlite\Sql\Lexing;
6
7/**
8 * Measures quoted SQL spans without treating their contents as syntax.
9 *
10 * @visibility ZtdQuery\Platform\Sqlite
11 */
12final class QuotedSpan
13{
14    /**
15     * Measures quoted SQL spans without treating their contents as syntax.
16     */
17    public static function quotedLength(string $sql, string $quote): int
18    {
19        $length = strlen($sql);
20        $i = 1;
21
22        while (true) {
23            $end = strpos($sql, $quote, $i);
24            if ($end === false) {
25                return $length;
26            }
27            $quoteCount = strspn($sql, $quote, $end);
28            $i = $end + $quoteCount;
29            if ($quoteCount % 2 === 0) {
30                continue;
31            }
32
33            return $i;
34        }
35    }
36
37    /**
38     * Measures quoted SQL spans without treating their contents as syntax.
39     */
40    public static function bracketQuotedLength(string $sql): int
41    {
42        $end = strpos($sql, ']');
43        if ($end === false) {
44            return strlen($sql);
45        }
46
47        return $end;
48    }
49}
50