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

UseBlockParser::getUseStatement()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 3
nop 2
dl 0
loc 14
rs 10
c 1
b 0
f 0
ccs 8
cts 8
cp 1
crap 3
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