Completed
Pull Request — master (#28)
by Valentyn
02:24
created

UserRoles::getRoles()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 6
cts 7
cp 0.8571
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 0
crap 3.0261
1
<?php
2
declare(strict_types=1);
3
4
namespace App\Users\Entity;
5
6
use Doctrine\ORM\Mapping as ORM;
7
8
/**
9
 * @ORM\Embeddable
10
 */
11
class UserRoles
12
{
13
    public const ROLE_USER = 'ROLE_USER';
14
    public const ROLE_MODERATOR = 'ROLE_MODER';
15
    public const ROLE_ADMIN = 'ROLE_ADMIN';
16
17
    /**
18
     * @ORM\Column(type="string", length=255, nullable=true)
19
     */
20
    private $roles;
21
22 30
    public function __construct()
23
    {
24 30
        $this->addRole(self::ROLE_USER);
25 30
    }
26
27 30
    public function addRole(string $role): self
28
    {
29 30
        if (in_array($role, $this->getValidRoles()) === false) {
30 1
            throw new \InvalidArgumentException(sprintf('Invalid role: %s', $role));
31
        }
32
33 30
        if (array_search($role, $this->getRoles()) === false) {
34 2
            return $this->setRoles(
35 2
                array_merge($this->getRoles(), [$role])
36
            );
37
        }
38
39 30
        return $this;
40
    }
41
42 1
    public function removeRole(string $role): self
43
    {
44 1
        $roles = $this->getRoles();
45 1
        $foundedRoleKey = array_search($role, $roles);
46
47 1
        if ($foundedRoleKey !== false) {
48 1
            unset($roles[$foundedRoleKey]);
49 1
            return $this->setRoles($roles);
50
        }
51
52
        return $this;
53
    }
54
55 2
    private function setRoles(array $roles): self
56
    {
57 2
        if (!count($roles)) {
58 1
            $this->roles = null;
59 1
            return $this;
60
        }
61
62 2
        $roles = json_encode($roles);
63
64 2
        if (strlen($roles) > 255) {
65
            throw new \InvalidArgumentException(sprintf('UserRoles $roles is too long. Max 255 characters.'));
66
        }
67
68 2
        $this->roles = $roles;
69 2
        return $this;
70
    }
71
72 34
    public function getRoles(): array
73
    {
74 34
        if (!$this->roles) {
75 32
            return $this->getDefaultRoles();
76
        }
77
78 4
        $roles = (array)json_decode($this->roles);
79
80 4
        if (!count($roles)) {
81
            return $this->getDefaultRoles();
82
        }
83
84 4
        return array_values($roles);
85
    }
86
87 32
    public function getDefaultRoles(): array
88
    {
89 32
        return [self::ROLE_USER];
90
    }
91
92 30
    public function getValidRoles(): array
93
    {
94 30
        return [self::ROLE_ADMIN, self::ROLE_MODERATOR, self::ROLE_USER];
95
    }
96
}