packages/sql-semantics-postgres/src/Model/Statement/Identifier/Comparison.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier;
6
7/**
8 * How two decoded identifiers are compared in one name space of a language profile.
9 *
10 * @visibility public
11 * @example Comparing names without regard to ASCII letter case
12 *     \SqlSemantics\Platform\PostgreSql\Model\Statement\Identifier\Comparison::AsciiInsensitive->equal('Users', 'USERS') // => true
13 */
14enum Comparison
15{
16    case Sensitive;
17    case AsciiInsensitive;
18
19    /**
20     * Decides whether two decoded identifiers denote the same name.
21     */
22    public function equal(string $left, string $right): bool
23    {
24        return match ($this) {
25            self::Sensitive => $left === $right,
26            self::AsciiInsensitive => $this->fold($left) === $this->fold($right),
27        };
28    }
29
30    /**
31     * Folds ASCII letters only; every other byte is kept, independent of the host locale.
32     */
33    public function fold(string $name): string
34    {
35        return strtr($name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
36    }
37}
38