Skip to content

Commit

Permalink
refac(user): move roles into RoleableTrait
Browse files Browse the repository at this point in the history
  • Loading branch information
n3wborn committed Nov 1, 2023
1 parent a0bbc6d commit 98cd01e
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 18 deletions.
56 changes: 56 additions & 0 deletions src/Entity/RoleableTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

trait RoleableTrait
{
public const ROLE_ADMIN = 'ROLE_ADMIN';
public const ROLE_USER = 'ROLE_USER';
public const ROLE_GUEST = 'ROLE_GUEST';

#[ORM\Column(type: 'json')]
private array $roles = [];

final public function getMainRole(): string
{
return current($this->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;
}
}
20 changes: 2 additions & 18 deletions src/Entity/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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
{
Expand Down

0 comments on commit 98cd01e

Please sign in to comment.