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
|
|
|
|