StaticClassMapSourceLocator   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 37
rs 10
c 2
b 0
f 0
wmc 4

2 Methods

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