Passed
Pull Request — master (#48)
by Marco
02:59
created

StaticClassMapSourceLocator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
dl 0
loc 36
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 1
A createLocatedSource() 0 13 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\ApiCompare\SourceLocator;
6
7
use Assert\Assert;
8
use Roave\BetterReflection\Identifier\Identifier;
9
use Roave\BetterReflection\SourceLocator\Ast\Locator;
10
use Roave\BetterReflection\SourceLocator\Located\LocatedSource;
11
use Roave\BetterReflection\SourceLocator\Type\AbstractSourceLocator;
12
use function array_keys;
13
use function array_map;
14
use function file_get_contents;
15
16
final class StaticClassMapSourceLocator extends AbstractSourceLocator
17
{
18
    /** @var string[] */
19
    private $classMap;
20
21
    /** @param string[] $classMap of class to file path. Every file must exist, every key must be non-empty */
22
    public function __construct(
23
        array $classMap,
24
        Locator $astLocator
25
    ) {
26
        parent::__construct($astLocator);
27
28
        $realPaths = array_map('realpath', $classMap);
29
30
        Assert::that($classMap)->all()->file();
31
        Assert::that(array_keys($classMap))->all()->string()->notEmpty();
32
33
        $this->classMap = $realPaths;
34
    }
35
36
    /**
37
     * {@inheritDoc}
38
     */
39
    protected function createLocatedSource(Identifier $identifier) : ?LocatedSource
40
    {
41
        if (! $identifier->isClass()) {
42
            return null;
43
        }
44
45
        $classFile = $this->classMap[$identifier->getName()] ?? null;
46
47
        if ($classFile === null) {
48
            return null;
49
        }
50
51
        return new LocatedSource(file_get_contents($classFile), $classFile);
52
    }
53
}
54