packages/sql-semantics-mysql/src/Statement/Name/AccountName.php

1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Name;
6
7use SqlSemantics\Platform\MySql\Model\Contract\NameUse;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name;
10use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
11
12/**
13 * A user or role account name: the user part and the optional host part.
14 *
15 * An account written without a host part denotes the host `%`; the host is
16 * kept absent, as written. Role names have the same two parts.
17 * Source: https://dev.mysql.com/doc/refman/8.4/en/account-names.html,
18 * https://dev.mysql.com/doc/refman/8.4/en/role-names.html.
19 *
20 * @visibility public
21 * @example Reading the parts of an account name
22 *     $account = new \SqlSemantics\Platform\MySql\Statement\Name\AccountName(new \SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name('app'), new \SqlSemantics\Platform\MySql\Model\Statement\Identifier\Name('10.0.%'));
23 *     [$account->user->value, $account->host?->value] // => ['app', '10.0.%']
24 */
25final class AccountName implements Account
26{
27    use Snapshot;
28
29    /**
30     * @param Name $user The user part
31     * @param Name|null $host The host part, when written
32     */
33    public function __construct(public readonly Name $user, public readonly ?Name $host = null)
34    {
35    }
36
37    /**
38     * Writes the user part and, joined by `@` without spaces, the host part.
39     */
40    public function render(Output $out): void
41    {
42        $out->name($this->user, NameUse::Label);
43        if ($this->host !== null) {
44            $out->glue()->symbol('@')->glue()->name($this->host, NameUse::Label);
45        }
46    }
47}
48