Failed Conditions
Pull Request — master (#162)
by
unknown
05:20
created

GuessFromComposerAutoloader   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 17
c 1
b 0
f 0
dl 0
loc 42
ccs 15
cts 16
cp 0.9375
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 4
A __invoke() 0 13 4
1
<?php
2
3
namespace ComposerRequireChecker\DependencyGuesser;
4
5
use Composer\Autoload\ClassLoader;
6
use ComposerRequireChecker\Cli\Options;
7
use ComposerRequireChecker\JsonLoader;
8
9
class GuessFromComposerAutoloader implements GuesserInterface
10
{
11
    private const COMPOSER_PATH_PREFIX = 'composer' . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR;
12
13
    /**
14
     * @var ClassLoader|null
15
     */
16
    private $autoloader;
17
18
    /**
19
     * @var string
20
     */
21
    private $pathRegex;
22
23 4
    public function __construct(?Options $options)
24
    {
25 4
        if ($options === null || !$options->getAutoloaderPath()) {
26 1
            return;
27
        }
28
29
        // Note: the loader is automatically registered
30
        // @todo figure out how to unregister the loader to avoid conflicts
31 4
        $this->autoloader = require $options->getAutoloaderPath();
32
33 4
        $vendorRoot = dirname($options->getAutoloaderPath());
34 4
        $SEP = \DIRECTORY_SEPARATOR === '/' ? '/' : '[' . preg_quote(\DIRECTORY_SEPARATOR, '@') . '/]';
35 4
        $this->pathRegex = '@^' . preg_quote($vendorRoot, '@') . "${SEP}(?:composer${SEP}\.\.${SEP})?([^${SEP}]+${SEP}[^${SEP}]+)${SEP}@";
36 4
    }
37
38 2
    public function __invoke(string $symbolName): \Generator
39
    {
40 2
        if (!$this->autoloader) {
41
            return;
42
        }
43
44 2
        $path = $this->autoloader->findFile(\ltrim($symbolName, '\\'));
45 2
        if ($path === false) {
46 1
            return;
47
        }
48
49 1
        if (preg_match($this->pathRegex, $path, $captures)) {
50 1
            yield $captures[1];
51
        }
52
    }
53
}
54