Passed
Push — 1.x ( a9995e...5c2b79 )
by Aleksei
12:31
created

RoleAliasCollection::__construct()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 16
rs 9.6111
cc 5
nc 9
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cycle\Schema\Renderer\MermaidRenderer;
6
7
use Cycle\ORM\SchemaInterface;
8
9
final class RoleAliasCollection
10
{
11
    private array $aliases = [];
12
13
    /**
14
     * @param array<string, array<int, mixed>> $schema
15
     */
16
    public function __construct(array $schema)
17
    {
18
        foreach ($schema as $key => $value) {
19
            $role = $key;
20
21
            if (\class_exists($role)) {
22
                $role = $value[SchemaInterface::ROLE] ?? 'undefinedRole';
23
            }
24
25
            $this->aliases[$key] = $role;
26
        }
27
28
        foreach ($this->aliases as $key => $role) {
29
            if (\preg_match('/[^_a-zA-Z0-9]/u', $role)) {
30
                $role = $this->makeAlias($role);
31
                $this->aliases[$key] = $role;
32
            }
33
        }
34
    }
35
36
    public function getAlias(string $role): string
37
    {
38
        return $this->aliases[$role] ?? 'undefined';
39
    }
40
41
    /**
42
     * @param non-empty-string $role
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string.
Loading history...
43
     *
44
     * @return string
45
     */
46
    private function makeAlias(string $role): string
47
    {
48
        $role = \preg_replace('/[^a-z0-9_]/u', '_', $role);
49
        $oldRole = $role;
50
51
        $counter = 0;
52
        while (isset($this->aliases[$role])) {
53
            $counter++;
54
            $role = $oldRole . '_' . $counter;
55
        }
56
57
        return $role;
58
    }
59
}
60