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