Completed
Push — master ( 01ac29...866a9a )
by Théo
03:27 queued 01:17
created

UseStmtCollection::findStatementForNode()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 6
nop 2
dl 0
loc 21
ccs 11
cts 11
cp 1
crap 6
rs 8.7624
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Humbug\PhpScoper\NodeVisitor\Collection;
16
17
use ArrayIterator;
18
use IteratorAggregate;
19
use PhpParser\Node\Name;
20
use PhpParser\Node\Stmt\Use_;
21
use PhpParser\Node\Stmt\UseUse;
22
use function Humbug\PhpScoper\clone_node;
23
24
/**
25
 * Utility class collecting all the use statements for the scoped files allowing to easily find the use which a node
26
 * may use.
27
 */
28
final class UseStmtCollection implements IteratorAggregate
29
{
30
    /**
31
     * @var Use_[][]
32
     */
33
    private $nodes = [
34
        null => [],
35
    ];
36
37 191
    public function add(?Name $namespaceName, Use_ $node): void
38
    {
39 191
        $this->nodes[(string) $namespaceName][] = clone_node($node);
40
    }
41
42
    /**
43
     * Finds the statements matching the given name.
44
     *
45
     * $name = 'Foo';
46
     *
47
     * use X;
48
     * use Bar\Foo;
49
     * use Y;
50
     *
51
     * will return the use statement for `Bar\Foo`.
52
     *
53
     * @param Name|null $namespaceName
54
     * @param Name      $node
55
     *
56
     * @return null|Name
57
     */
58 156
    public function findStatementForNode(?Name $namespaceName, Name $node): ?Name
59
    {
60 156
        $name = strtolower($node->getFirst());
61
62 156
        $useStatements = $this->nodes[(string) $namespaceName] ?? [];
63
64 156
        foreach ($useStatements as $use_) {
65 84
            foreach ($use_->uses as $useStatement) {
66 84
                if ($useStatement instanceof UseUse) {
67 84
                    if ($name === strtolower($useStatement->alias)) {
68
                        // Match the alias
69 84
                        return $useStatement->name;
70 7
                    } elseif (null !== $useStatement->alias) {
71 7
                        continue;
72
                    }
73
                }
74
            }
75
        }
76
77 79
        return null;
78
    }
79
80
    /**
81
     * @inheritdoc
82
     */
83
    public function getIterator(): iterable
84
    {
85
        return new ArrayIterator($this->nodes);
86
    }
87
}
88