Completed
Pull Request — master (#27)
by Dmitry
04:13 queued 13s
created

PermissionDescriptionGenerator::parse()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 11
ccs 0
cts 6
cp 0
crap 12
rs 10
1
<?php
2
3
namespace hipanel\rbac\console;
4
5
final class PermissionDescriptionGenerator
6
{
7
    /**
8
     * @var string
9
     */
10
    private $module;
11
    /**
12
     * @var string
13
     */
14
    private $operation;
15
    /**
16
     * @var string
17
     */
18
    private $rawName;
19
    /**
20
     * @var bool
21
     */
22
    private $allows;
23
24
    public function __invoke(string $name): string
25
    {
26
        $this->parse($name);
27
28
        return strtr('{allowance}{operation}', [
29
            '{allowance}' => $this->formatAllowance(),
30
            '{operation}' => $this->formatOperation(),
31
        ]);
32
    }
33
34
    private function parse(string $name): void
35
    {
36
        $this->module = null;
37
        $this->rawName = $name;
38
        $this->allows = strpos($name, 'deny:') === false;
39
        if (!$this->allows) {
40
            [, $name] = explode(':', $name, 2);
41
        }
42
        $this->operation = $name;
43
        if (strpos($name, '.') !== false) {
44
            [$this->module, $this->operation] = explode('.', $name, 2);
45
        }
46
    }
47
48
    private function formatAllowance(): string
49
    {
50
        if (!$this->allows) {
51
            return 'Prohibits ';
52
        }
53
54
        return 'Allows ';
55
    }
56
57
    private function formatOperation(): string
58
    {
59
        if (preg_match('/^[a-z]+$/', $this->operation)) {
60
            $exceptions = [
61
                'createing' => 'creating',
62
                'updateing' => 'updating',
63
                'deleteing' => 'deleting',
64
            ];
65
66
            $result = strtr($this->operation . 'ing', $exceptions);
67
68
            if ($this->module) {
69
                return $result . ' of the ' . $this->module;
70
            }
71
72
            return $result;
73
        }
74
75
        if ($this->module) {
76
            return $this->operation . ' operation on the ' . $this->module;
77
        }
78
79
        return $this->operation . ' operation';
80
    }
81
}
82