Passed
Push — main ( b4da1f...10c988 )
by Jesús
01:01 queued 16s
created

UseBlockParser   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 92.59%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 51
ccs 25
cts 27
cp 0.9259
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getUseStatement() 0 14 3
A searchInUsesStatements() 0 17 3
A lookInCurrentNamespace() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\ClassResolver\DocBlockService;
6
7
final class UseBlockParser
8
{
9 28
    public function getUseStatement(string $className, string $phpCode): string
10
    {
11 28
        if ($phpCode === '') {
12 1
            return '';
13
        }
14
15 27
        $fullyQualifiedClassName = $this->searchInUsesStatements($className, $phpCode);
16 27
        if ($fullyQualifiedClassName !== '') {
17 15
            return '\\' . ltrim($fullyQualifiedClassName, '\\');
18
        }
19
20 13
        $namespace = $this->lookInCurrentNamespace($phpCode);
21
22 13
        return sprintf('\\%s\\%s', $namespace, $className);
23
    }
24
25 27
    private function searchInUsesStatements(string $className, string $phpCode): string
26
    {
27 27
        $needle = "{$className};";
28
29 27
        if (strcasecmp(substr(PHP_OS, 0, 3), 'WIN') == 0) {
30
            $phpCode = str_replace("\n", PHP_EOL, $phpCode);
31
        }
32
33 27
        $lines = array_filter(
34 27
            explode(PHP_EOL, $phpCode),
35 27
            static fn (string $l) => strncmp($l, 'use ', 4) === 0 && str_contains($l, $needle),
36 27
        );
37
38
        /** @psalm-suppress RedundantCast */
39 27
        $lineSplit = (array)explode(' ', (string)reset($lines));
40
41 27
        return rtrim($lineSplit[1] ?? '', ';');
42
    }
43
44 13
    private function lookInCurrentNamespace(string $phpCode): string
45
    {
46 13
        if (strcasecmp(substr(PHP_OS, 0, 3), 'WIN') == 0) {
47
            $phpCode = str_replace("\n", PHP_EOL, $phpCode);
48
        }
49
50 13
        $lines = array_filter(
51 13
            explode(PHP_EOL, $phpCode),
52 13
            static fn (string $l) => strncmp($l, 'namespace ', 10) === 0,
53 13
        );
54
        /** @psalm-suppress RedundantCast */
55 13
        $lineSplit = (array)explode(' ', (string)reset($lines));
56
57 13
        return rtrim($lineSplit[1] ?? '', ';');
58
    }
59
}
60