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