1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cerbero\LaravelEnum\Services; |
6
|
|
|
|
7
|
|
|
use ArrayIterator; |
8
|
|
|
use IteratorAggregate; |
9
|
|
|
use Traversable; |
10
|
|
|
|
11
|
|
|
use function Cerbero\LaravelEnum\yieldLines; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The use statements collector. |
15
|
|
|
* |
16
|
|
|
* @implements IteratorAggregate<string, class-string> |
17
|
|
|
*/ |
18
|
|
|
final class UseStatements implements IteratorAggregate |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* The regular expression to extract the use statements already present on the enum. |
22
|
|
|
*/ |
23
|
|
|
public const RE_STATEMENT = '~^use\s+([^\s;]+)(?:\s+as\s+([^;]+))?~i'; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Instantiate the class. |
27
|
|
|
* |
28
|
|
|
* @param Inspector<\UnitEnum> $inspector |
29
|
|
|
*/ |
30
|
1 |
|
public function __construct(private readonly Inspector $inspector) {} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Retrieve the use statements. |
34
|
|
|
* |
35
|
|
|
* @return ArrayIterator<string, class-string> |
36
|
|
|
*/ |
37
|
1 |
|
public function getIterator(): Traversable |
38
|
|
|
{ |
39
|
1 |
|
$useStatements = [ |
40
|
1 |
|
...$this->fromMethodAnnotations(), |
41
|
1 |
|
...$this->existing(), |
42
|
1 |
|
]; |
43
|
|
|
|
44
|
1 |
|
asort($useStatements); |
45
|
|
|
|
46
|
1 |
|
return new ArrayIterator($useStatements); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Retrieve the use statements from the method annotations. |
51
|
|
|
* |
52
|
|
|
* @return array<string, class-string> |
|
|
|
|
53
|
|
|
*/ |
54
|
1 |
|
public function fromMethodAnnotations(): array |
55
|
|
|
{ |
56
|
1 |
|
$useStatements = []; |
57
|
|
|
|
58
|
1 |
|
foreach ($this->inspector->methodAnnotations() as $annotation) { |
59
|
1 |
|
foreach ($annotation->namespaces as $namespace) { |
60
|
1 |
|
if (! $this->inspector->hasSameNamespace($namespace)) { |
61
|
1 |
|
$useStatements[class_basename($namespace)] = $namespace; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
1 |
|
return $useStatements; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Retrieve the use statements already present on the enum. |
71
|
|
|
* |
72
|
|
|
* @return array<string, class-string> |
|
|
|
|
73
|
|
|
*/ |
74
|
1 |
|
public function existing(): array |
75
|
|
|
{ |
76
|
1 |
|
$useStatements = []; |
77
|
|
|
|
78
|
1 |
|
foreach (yieldLines($this->inspector->filename()) as $line) { |
79
|
1 |
|
if (strpos($line, 'enum') === 0) { |
80
|
1 |
|
break; |
81
|
|
|
} |
82
|
|
|
|
83
|
1 |
|
if (preg_match(self::RE_STATEMENT, $line, $matches)) { |
84
|
1 |
|
$useStatements[$matches[2] ?? class_basename($matches[1])] = $matches[1]; |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
/** @var array<string, class-string> */ |
89
|
1 |
|
return $useStatements; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|