From 98cd01eab5e9f2ba5990acb433b568830b96ba9c Mon Sep 17 00:00:00 2001 From: n3wborn Date: Wed, 1 Nov 2023 21:45:12 +0100 Subject: [PATCH] refac(user): move roles into RoleableTrait --- src/Entity/RoleableTrait.php | 56 ++++++++++++++++++++++++++++++++++++ src/Entity/User.php | 20 ++----------- 2 files changed, 58 insertions(+), 18 deletions(-) create mode 100644 src/Entity/RoleableTrait.php diff --git a/src/Entity/RoleableTrait.php b/src/Entity/RoleableTrait.php new file mode 100644 index 0000000..bb5e2c8 --- /dev/null +++ b/src/Entity/RoleableTrait.php @@ -0,0 +1,56 @@ +getRoles()); + } + + /** + * @see UserInterface + */ + final public function getRoles(): array + { + // guarantee every user at least has ROLE_USER + $roles = !empty($this->roles) + ? $this->roles + : [self::ROLE_USER]; + + return array_unique($roles); + } + + final public function setRoles(array $roles): self + { + $this->roles = $roles; + + return $this; + } + + final public function addRole(string $role): self + { + $this->roles[] = $role; + + return $this; + } + + final public function removeRole(string $role): self + { + if (($roleIndex = array_search($role, $this->getRoles(), true)) !== false) { + unset($this->roles[$roleIndex]); + } + + return $this; + } +} diff --git a/src/Entity/User.php b/src/Entity/User.php index 2c339bc..c3b253f 100644 --- a/src/Entity/User.php +++ b/src/Entity/User.php @@ -20,12 +20,12 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface use SluggableTrait; use CreatableUpdateableTrait; use UsernameableTrait; + use RoleableTrait; - public const ROLE_ADMIN = 'ROLE_ADMIN'; - public const ROLE_USER = 'ROLE_USER'; public const ROLES = [ self::ROLE_ADMIN => 'Administrateur', self::ROLE_USER => 'Utilisateur', + self::ROLE_GUEST => 'Invité', ]; #[ORM\Id] @@ -74,22 +74,6 @@ final public function getUserIdentifier(): string return $this->getUsername(); } - /** @see UserInterface */ - final public function getRoles(): array - { - $roles = $this->roles; - $roles[] = 'ROLE_USER'; - - return array_unique($roles); - } - - final public function setRoles(array $roles): self - { - $this->roles = $roles; - - return $this; - } - /** @see PasswordAuthenticatedUserInterface */ final public function getPassword(): string {