packages/sql-semantics-mysql/src/Statement/Account/User/RoleSelection.php
1<?php
2
3declare(strict_types=1);
4
5namespace SqlSemantics\Platform\MySql\Statement\Account\User;
6
7use SqlSemantics\Platform\MySql\Model\Diagnostic\Check;
8use SqlSemantics\Platform\MySql\Model\Rendering\Output;
9use SqlSemantics\Platform\MySql\Model\Statement\Node;
10use SqlSemantics\Platform\MySql\Model\Statement\Snapshot;
11use SqlSemantics\Platform\MySql\Statement\Name\AccountName;
12
13/**
14 * The roles SET ROLE, a DEFAULT ROLE clause or GRANT … AS … WITH ROLE select: `role, …`, `NONE`, `DEFAULT` or `ALL [EXCEPT role, …]`.
15 *
16 * The roles are the named ones for Named and the excepted ones for All.
17 * Source: https://dev.mysql.com/doc/refman/8.4/en/set-role.html,
18 * https://dev.mysql.com/doc/refman/8.4/en/set-default-role.html.
19 *
20 * @visibility public
21 * @example Selecting all roles but one
22 * $selection = (new \SqlSemantics\Platform\MySql\Semantics())->analyze('SET ROLE ALL EXCEPT r')->statement->roles;
23 * [$selection->set, $selection->roles[0]->user->value] // => [\SqlSemantics\Platform\MySql\Statement\Account\User\RoleSet::All, 'r']
24 */
25final class RoleSelection implements Node
26{
27 use Snapshot;
28
29 /**
30 * @var list<AccountName> The named roles, or the roles EXCEPT names
31 */
32 public readonly array $roles;
33
34 /**
35 * @param RoleSet $set Which roles are selected
36 * @param list<AccountName> $roles The named roles (at least one), or the roles EXCEPT names; none otherwise
37 */
38 public function __construct(public readonly RoleSet $set, array $roles = [])
39 {
40 $this->roles = Check::listOf($roles, AccountName::class, 'A role selection names roles.');
41 Check::input(match ($set) {
42 RoleSet::Named => $this->roles !== [],
43 RoleSet::All => true,
44 RoleSet::None, RoleSet::Default => $this->roles === [],
45 }, 'Roles are named by a selection of named roles and excepted by a selection of all roles.');
46 }
47
48 /**
49 * Writes the selection.
50 */
51 public function render(Output $out): void
52 {
53 match ($this->set) {
54 RoleSet::Named => $out->list($this->roles),
55 RoleSet::None => $out->keyword('NONE'),
56 RoleSet::Default => $out->keyword('DEFAULT'),
57 RoleSet::All => $out->keyword('ALL'),
58 };
59 if ($this->set === RoleSet::All && $this->roles !== []) {
60 $out->keyword('EXCEPT')->list($this->roles);
61 }
62 }
63}
64