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

UseStmtCollection   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 86.67%

Importance

Changes 0
Metric Value
dl 0
loc 60
ccs 13
cts 15
cp 0.8667
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 4 1
B findStatementForNode() 0 21 6
A getIterator() 0 4 1
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