Passed
Push — master ( d46d5f...674e23 )
by Luis
44s queued 12s
created

TagType::named()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php declare(strict_types=1);
2
/**
3
 * PHP version 8.0
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;
9
10
use PhUml\Code\Name;
11
use PhUml\Code\UseStatements;
12
use PhUml\Code\Variables\TypeDeclaration;
13
14
final class TagType
15
{
16
    public static function nullable(string $type): TagType
17
    {
18
        return new TagType([$type], isNullable: true);
19
    }
20
21
    /** @param string[] $types */
22
    public static function compound(array $types): TagType
23
    {
24
        return new TagType($types, isNullable: false);
25
    }
26
27
    public static function named(string $type): TagType
28
    {
29
        return new TagType([$type]);
30
    }
31
32
    /** @param string[] $types */
33
    public function __construct(private array $types, private bool $isNullable = false)
34
    {
35
    }
36
37
    public function resolve(UseStatements $useStatements): TypeDeclaration
38
    {
39
        return match (true) {
40
            $this->isNullable => TypeDeclaration::fromNullable($useStatements->fullyQualifiedNameFor($this->types()[0])),
41
            count($this->types) === 1 => TypeDeclaration::from($useStatements->fullyQualifiedNameFor($this->types()[0])),
42
            default => $this->resolveUnionTypes($useStatements),
43
        };
44
    }
45
46
    private function resolveUnionTypes(UseStatements $useStatements): TypeDeclaration
47
    {
48
        $withFullyQualifiedNames = array_map(
49
            static fn (Name $type) => $useStatements->fullyQualifiedNameFor($type),
50
            $this->types(),
51
        );
52
        return TypeDeclaration::fromUnionType($withFullyQualifiedNames);
53
    }
54
55
    /** @return Name[] */
56
    private function types(): array
57
    {
58
        return array_map(static fn (string $type) => new Name(ltrim($type, characters: '\\')), $this->types);
59
    }
60
}
61