Passed
Push — variadic-params-visibility-con... ( ca0a66 )
by Luis
13:54
created

Variable::__toString()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php declare(strict_types=1);
2
/**
3
 * PHP version 7.2
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\Code\Variables;
9
10
use BadMethodCallException;
11
use PhUml\Code\Name;
12
13
/**
14
 * It represents a variable declaration
15
 */
16
final class Variable implements HasType
17
{
18
    use WithTypeDeclaration;
19
20
    /** @var string */
21
    protected $name;
22
23
    public function __construct(string $name, TypeDeclaration $type)
24
    {
25
        $this->name = $name;
26
        $this->type = $type;
27
    }
28
29
    /**
30
     * References to arrays need to have the `[]` removed from their names in order to create
31
     * external definitions with a proper name
32
     *
33
     * The edges created from these references need to map to the names without the suffix
34
     *
35
     * @see \PhUml\Parser\Code\ExternalAssociationsResolver::resolveExternalAttributes()
36
     * @see \PhUml\Parser\Code\ExternalAssociationsResolver::resolveExternalConstructorParameters()
37
     * @see \PhUml\Graphviz\Builders\EdgesBuilder::addAssociation()
38
     */
39
    public function referenceName(): Name
40
    {
41
        $name = $this->isArray() ? $this->arrayTypeName() : $this->typeName();
42
        if ($name === null) {
43
            throw new BadMethodCallException('This attribute is not a reference to a code definition');
44
        }
45
        return $name;
46
    }
47
48
    public function __toString()
49
    {
50
        return sprintf(
51
            '%s%s',
52
            $this->name,
53
            $this->type->isPresent() ? ": {$this->type}" : ''
54
        );
55
    }
56
57
    private function typeName(): ?Name
58
    {
59
        return $this->type->name();
60
    }
61
62
    private function isArray(): bool
63
    {
64
        return $this->type->isArray();
65
    }
66
67
    private function arrayTypeName(): Name
68
    {
69
        return Name::from($this->type->removeArraySuffix());
70
    }
71
}
72