Passed
Push — feature/custom-services-v2 ( 35de26...30061f )
by Chema
03:34
created

UseBlockParser   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
dl 0
loc 41
rs 10
c 1
b 0
f 0
ccs 21
cts 21
cp 1
wmc 5

3 Methods

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