Passed
Pull Request — master (#22)
by Luis
24:40 queued 21:48
created

ParsedConstantsBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 35
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0
wmc 5
1
<?php declare(strict_types=1);
2
/**
3
 * PHP version 8.1
4
 *
5
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
6
 */
7
8
namespace PhUml\Parser\Code\Builders\Members;
9
10
use PhpParser\Node\Const_;
11
use PhpParser\Node\Expr\ConstFetch;
12
use PhpParser\Node\Stmt\ClassConst;
13
use PhUml\Code\Properties\Constant;
14
use PhUml\Code\Variables\TypeDeclaration;
15
16
/**
17
 * It builds an array of `Constants` for either a `ClassDefinition` or an `InterfaceDefinition`
18
 */
19
final class ParsedConstantsBuilder implements ConstantsBuilder
20
{
21
    /** @var string[] */
22
    private const TYPES = [
23
        'integer' => 'int',
24
        'double' => 'float',
25
        'string' => 'string',
26
    ];
27
28 44
    public function __construct(private readonly VisibilityBuilder $visibilityBuilder)
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_STRING, expecting T_VARIABLE on line 28 at column 49
Loading history...
29
    {
30
    }
31
32
    /**
33
     * @param ClassConst[] $classConstants
34
     * @return Constant[]
35
     */
36 29
    public function build(array $classConstants): array
37
    {
38 29
        return array_map(fn (ClassConst $constant): Constant => new Constant(
39 16
            (string) $constant->consts[0]->name,
40 16
            TypeDeclaration::from($this->determineType($constant->consts[0])),
41 16
            $this->visibilityBuilder->build($constant)
42
        ), $classConstants);
43
    }
44
45 16
    private function determineType(Const_ $constant): ?string
46
    {
47 16
        if (property_exists($constant->value, 'value')) {
48 15
            return self::TYPES[\gettype($constant->value->value)];
49
        }
50 12
        if (! $constant->value instanceof ConstFetch) {
51 1
            return null;
52
        }
53 11
        return 'bool';
54
    }
55
}
56