Failed Conditions
Pull Request — master (#162)
by
unknown
09:45
created

GuessFromComposerInstalledJson::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 15
ccs 8
cts 8
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php declare(strict_types=1);
2
3
4
namespace ComposerRequireChecker\DependencyGuesser;
5
6
use Roave\BetterReflection\BetterReflection;
7
use Roave\BetterReflection\Identifier\Identifier;
8
use Roave\BetterReflection\Identifier\IdentifierType;
9
use Roave\BetterReflection\Reflection\ReflectionClass;
10
use Roave\BetterReflection\Reflector\ClassReflector;
11
use Roave\BetterReflection\SourceLocator\Type\Composer\Factory\MakeLocatorForInstalledJson;
12
use Roave\BetterReflection\SourceLocator\Type\MemoizingSourceLocator;
13
use Roave\BetterReflection\SourceLocator\Type\SourceLocator;
14
15
final class GuessFromComposerInstalledJson implements GuesserInterface
16
{
17
    /**
18
     * @var SourceLocator
19
     */
20
    private $sourceLocator;
21
22
    /**
23
     * @var ClassReflector
24
     */
25
    private $reflector;
26
27
    /**
28
     * @var string
29
     */
30
    private $pathRegex;
31
32 3
    public function __construct(string $projectPath)
33
    {
34 3
        $this->sourceLocator = new MemoizingSourceLocator(
35 3
            (new MakeLocatorForInstalledJson())(
36 3
                $projectPath,
37 3
                (new BetterReflection())->astLocator()
38
            )
39
        );
40
41 3
        $this->reflector = new ClassReflector($this->sourceLocator);
42
43
        // @todo: support https://getcomposer.org/doc/06-config.md#vendor-dir; useless as BetterReflection does not, at this moment.
44 3
        $cleanPath = preg_quote(str_replace(DIRECTORY_SEPARATOR, '/', $projectPath) . '/' . 'vendor', '@');
45
46 3
        $this->pathRegex = '@^' . $cleanPath . '/(?:composer/\.\./)?([^/]+/[^/]+)/@';
47 3
    }
48
49 3
    public function __invoke(string $symbolName): \Generator
50
    {
51 3
        $reflection = $this->sourceLocator->locateIdentifier($this->reflector, new Identifier($symbolName, new IdentifierType(IdentifierType::IDENTIFIER_CLASS)));
52
53 3
        if (!($reflection instanceof ReflectionClass)) {
54 2
            return;
55
        }
56
57 1
        $path = $reflection->getFileName();
58
59 1
        if (preg_match($this->pathRegex, $path, $captures)) {
60 1
            yield $captures[1];
61
        }
62
    }
63
}
64