Passed
Push — master ( 03a6f5...40da0b )
by Luca
11:01 queued 15s
created

HasCode   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 78.56%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 7
eloc 13
c 2
b 0
f 0
dl 0
loc 46
ccs 11
cts 14
cp 0.7856
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A canUpdateCode() 0 10 2
A setCode() 0 11 4
A getCode() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Traits;
6
7
use Application\Api\Exception;
8
use Application\Model\User;
9
use Doctrine\ORM\Mapping as ORM;
10
11
trait HasCode
12
{
13
    /**
14
     * @var null|string
15
     *
16
     * @ORM\Column(type="string", length=30, nullable=true)
17
     */
18
    private $code;
19
20
    /**
21
     * Set code
22
     */
23 2
    public function setCode(?string $code): void
24
    {
25 2
        if ($code === '') {
26
            $code = null;
27
        }
28
29 2
        if ($code !== $this->code && !$this->canUpdateCode()) {
30
            throw new Exception('Only majors and administrators are allowed to update card.code');
31
        }
32
33 2
        $this->code = $code;
34 2
    }
35
36
    /**
37
     * Get code
38
     */
39 7
    public function getCode(): ?string
40
    {
41 7
        return $this->code;
42
    }
43
44
    /**
45
     * Simple ACL check
46
     */
47 5
    private function canUpdateCode(): bool
48
    {
49
        $whitelist = [
50 5
            User::ROLE_MAJOR,
51
            User::ROLE_ADMINISTRATOR,
52
        ];
53
54 5
        $currentRole = User::getCurrent() ? User::getCurrent()->getRole() : User::ROLE_ANONYMOUS;
55
56 5
        return in_array($currentRole, $whitelist, true);
57
    }
58
}
59