Passed
Push — union-types ( cd7236...b93e9c )
by Luis
10:52
created

resolveExternalAssociationsFromTypeNames()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 1
nop 2
dl 0
loc 8
rs 10
c 0
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;
9
10
use PhUml\Code\Attributes\Attribute;
11
use PhUml\Code\ClassDefinition;
12
use PhUml\Code\Codebase;
13
use PhUml\Code\Name;
14
use PhUml\Code\Parameters\Parameter;
15
16
/**
17
 * It checks the attributes and the constructor parameters of a class looking for external definitions
18
 *
19
 * An external definition is either a class or interface from a third party library, or a built-in class or interface
20
 *
21
 * In the case of a third-party library or built-in type a `ClassDefinition` is added by default.
22
 * Although we don't really know if it's an interface or trait since we don't have access to the source code
23
 */
24
final class ExternalAssociationsResolver implements RelationshipsResolver
25
{
26
    public function resolve(Codebase $codebase): void
27
    {
28
        foreach ($codebase->definitions() as $definition) {
29
            if ($definition instanceof ClassDefinition) {
30
                $this->resolveForClass($definition, $codebase);
31
            }
32
        }
33
    }
34
35
    private function resolveForClass(ClassDefinition $definition, Codebase $codebase): void
36
    {
37
        $this->resolveExternalAttributes($definition, $codebase);
38
        $this->resolveExternalConstructorParameters($definition, $codebase);
39
    }
40
41
    private function resolveExternalAttributes(ClassDefinition $definition, Codebase $codebase): void
42
    {
43
        array_map(function (Attribute $attribute) use ($codebase): void {
44
            $this->resolveExternalAssociationsFromTypeNames($attribute->references(), $codebase);
45
        }, $definition->attributes());
46
    }
47
48
    private function resolveExternalConstructorParameters(ClassDefinition $definition, Codebase $codebase): void
49
    {
50
        array_map(function (Parameter $parameter) use ($codebase): void {
51
            $this->resolveExternalAssociationsFromTypeNames($parameter->references(), $codebase);
52
        }, $definition->constructorParameters());
53
    }
54
55
    /** @param Name[] $references */
56
    private function resolveExternalAssociationsFromTypeNames(array $references, Codebase $codebase): void
57
    {
58
        array_map(static function (Name $reference) use ($codebase): void {
59
            if ($codebase->has($reference)) {
60
                return;
61
            }
62
            $codebase->add(new ClassDefinition($reference));
63
        }, $references);
64
    }
65
}
66