Passed
Push — 1.5 ( c7c5a4...fe8795 )
by Luis
06:06
created

ConstantsBuilder::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * PHP version 7.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\Scalar;
13
use PhpParser\Node\Stmt\ClassConst;
14
use PhUml\Code\Attributes\Constant;
15
use PhUml\Code\Variables\TypeDeclaration;
16
17
/**
18
 * It builds an array of `Constants` for either a `ClassDefinition` or an `InterfaceDefinition`
19
 */
20
class ConstantsBuilder
21
{
22
    private static $types = [
23
        'integer' => 'int',
24
        'double' => 'float',
25
        'string' => 'string',
26
    ];
27
28
    /**
29
     * @param \PhpParser\Node[] $classAttributes
30
     * @return Constant[]
31
     */
32
    public function build(array $classAttributes): array
33
    {
34 96
        $constants = array_filter($classAttributes, function ($attribute) {
35 84
            return $attribute instanceof ClassConst;
36 96
        });
37 96
        return array_map(function (ClassConst $constant) {
38 39
            return new Constant(
39 39
                $constant->consts[0]->name,
40 39
                TypeDeclaration::from($this->determineType($constant->consts[0]))
41
            );
42 96
        }, $constants);
43
    }
44
45 39
    private function determineType(Const_ $constant): ?string
46
    {
47 39
        if ($constant->value instanceof Scalar) {
48 36
            return self::$types[\gettype($constant->value->value)];
49
        }
50 6
        if ($constant->value instanceof ConstFetch
51 6
            && \in_array($constant->value->name->parts[0], ['true', 'false'], true)) {
52 3
            return 'bool';
53
        }
54 3
        return null; // It's an expression
55
    }
56
}
57