Passed
Push — master ( 206034...319324 )
by Théo
02:08
created

UseStmtName::__construct()   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
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Humbug\PhpScoper\PhpParser;
6
7
use Humbug\PhpScoper\PhpParser\NodeVisitor\ParentNodeAppender;
8
use PhpParser\Node\Name;
9
use PhpParser\Node\Stmt\Use_;
10
use PhpParser\Node\Stmt\UseUse;
11
use UnexpectedValueException;
12
use function count;
13
use function get_class;
14
use function Safe\sprintf;
15
16
final class UseStmtName
17
{
18
    private Name $name;
19
20
    public function __construct(Name $name)
21
    {
22
        $this->name = $name;
23
    }
24
25
    public function contains(Name $resolvedName): bool
26
    {
27
        return self::arrayStartsWith(
28
            $resolvedName->parts,
29
            $this->name->parts,
30
        );
31
    }
32
33
    /**
34
     * @param string[] $array
35
     * @param string[] $start
36
     */
37
    private static function arrayStartsWith(array $array, array $start): bool
38
    {
39
        $prefixLength = count($start);
40
41
        for ($index = 0; $index < $prefixLength; ++$index) {
42
            if (!isset($array[$index]) || $array[$index] !== $start[$index]) {
43
                return false;
44
            }
45
        }
46
47
        return true;
48
    }
49
50
    /**
51
     * @return array{string|null, Use_::TYPE_*}
0 ignored issues
show
Documentation Bug introduced by
The doc comment array{string|null, Use_::TYPE_*} at position 2 could not be parsed: Expected ':' at position 2, but found 'string'.
Loading history...
52
     */
53
    public function getUseStmtAliasAndType(): array
54
    {
55
        $use = ParentNodeAppender::getParent($this->name);
56
57
        if (!($use instanceof UseUse)) {
58
            throw new UnexpectedValueException(
59
                sprintf(
60
                    'Unexpected use statement name parent "%s"',
61
                    get_class($use),
62
                ),
63
            );
64
        }
65
66
        $useParent = ParentNodeAppender::getParent($use);
67
68
        if (!($useParent instanceof Use_)) {
69
            throw new UnexpectedValueException(
70
                sprintf(
71
                    'Unexpected UseUse parent "%s"',
72
                    get_class($useParent),
73
                ),
74
            );
75
        }
76
77
        $alias = $use->alias;
78
79
        if (null !== $alias) {
80
            $alias = (string) $alias;
81
        }
82
83
        return [
84
            $alias,
85
            $useParent->type,
86
        ];
87
    }
88
}
89