-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refac(user): move roles into RoleableTrait
- Loading branch information
Showing
2 changed files
with
58 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters