packages/sql-semantics-mysql/src/Rules/Identifiers.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Rules;
6
7/**
8 * Decodes the spelling of a MySQL identifier token.
9 *
10 * Rule: MYSQL-IDENTIFIER-DECODE-001. Scope: the terminals IDENT and
11 * IDENT_QUOTED of every release. A word in backticks is the text between them
12 * with each doubled backtick read as one; under ANSI_QUOTES a word in double
13 * quotes is the text between them with each doubled double quote read as one;
14 * any other word, including one made of digits and letters or of bytes above
15 * 0x7F, is the name as written. No backslash escape exists in an identifier.
16 * Letter case is kept, because the server keeps it and compares names by the
17 * rules of each name space. Precision: exact for every token the lexer
18 * produces. Terminates: one pass over the token text.
19 * Source: https://dev.mysql.com/doc/refman/8.4/en/identifiers.html.
20 * Status: Implemented.
21 *
22 * @visibility SqlSemantics\Platform\MySql
23 */
24final class Identifiers
25{
26    /**
27     * Decodes an identifier token text to the name it denotes.
28     */
29    public function decode(string $text): string
30    {
31        $quote = $text[0] ?? '';
32        if (($quote === '`' || $quote === '"') && strlen($text) >= 2 && $text[strlen($text) - 1] === $quote) {
33            return str_replace($quote . $quote, $quote, substr($text, 1, -1));
34        }
35
36        return $text;
37    }
38}
39