-
Notifications
You must be signed in to change notification settings - Fork 16
/
FunctionFinder.php
253 lines (207 loc) 路 8.77 KB
/
FunctionFinder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
<?php
namespace Castor;
use Castor\Attribute\AsContext;
use Castor\Attribute\AsContextGenerator;
use Castor\Attribute\AsListener;
use Castor\Attribute\AsSymfonyTask;
use Castor\Attribute\AsTask;
use Castor\Exception\FunctionConfigurationException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Process\Process;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
/** @internal */
class FunctionFinder
{
/** @var array<string> */
public static array $files = [];
public function __construct(
private readonly CacheInterface $cache,
private readonly string $rootDir,
) {
}
/** @return iterable<TaskDescriptor|ContextDescriptor|ContextGeneratorDescriptor|ListenerDescriptor|SymfonyTaskDescriptor> */
public function findFunctions(string $path): iterable
{
yield from self::doFindFunctions([new \SplFileInfo($path . '/castor.php')]);
$castorDirectory = $path . '/castor';
if (is_dir($castorDirectory)) {
$files = Finder::create()
->files()
->name('*.php')
->in($castorDirectory)
;
yield from self::doFindFunctions($files);
}
}
/**
* @param iterable<\SplFileInfo> $files
*
* @return iterable<TaskDescriptor|ContextDescriptor|ContextGeneratorDescriptor|ListenerDescriptor|SymfonyTaskDescriptor>
*/
private function doFindFunctions(iterable $files): iterable
{
$initialFunctions = get_defined_functions()['user'];
$initialClasses = get_declared_classes();
foreach ($files as $file) {
castor_require($file->getPathname());
}
$newFunctions = array_diff(get_defined_functions()['user'], $initialFunctions);
foreach ($newFunctions as $functionName) {
$reflectionFunction = new \ReflectionFunction($functionName);
yield from $this->resolveTasks($reflectionFunction);
yield from $this->resolveContexts($reflectionFunction);
yield from $this->resolveContextGenerators($reflectionFunction);
yield from $this->resolveListeners($reflectionFunction);
}
// Symfony task in repacked application are not supported
if (class_exists(\RepackedApplication::class)) {
return;
}
$newClasses = array_diff(get_declared_classes(), $initialClasses);
foreach ($newClasses as $className) {
$reflectionClass = new \ReflectionClass($className);
yield from $this->resolveSymfonyTask($reflectionClass);
}
}
/**
* @return iterable<TaskDescriptor>
*/
private function resolveTasks(\ReflectionFunction $reflectionFunction): iterable
{
$attributes = $reflectionFunction->getAttributes(AsTask::class, \ReflectionAttribute::IS_INSTANCEOF);
if (!\count($attributes)) {
return;
}
try {
$taskAttribute = $attributes[0]->newInstance();
} catch (\Throwable $e) {
throw new FunctionConfigurationException(sprintf('Could not instantiate the attribute "%s".', AsTask::class), $reflectionFunction, $e);
}
if ('' === $taskAttribute->name) {
$taskAttribute->name = SluggerHelper::slug($reflectionFunction->getShortName());
}
if (null === $taskAttribute->namespace) {
$ns = str_replace('/', ':', \dirname(str_replace('\\', '/', $reflectionFunction->getName())));
$ns = implode(':', array_map(SluggerHelper::slug(...), explode(':', $ns)));
$taskAttribute->namespace = $ns;
}
foreach ($taskAttribute->onSignals as $signal => $callable) {
if (!\is_callable($callable)) {
throw new FunctionConfigurationException(sprintf('The callable for signal "%s" is not callable.', $signal), $reflectionFunction);
}
}
yield new TaskDescriptor($taskAttribute, $reflectionFunction);
}
/**
* @return iterable<SymfonyTaskDescriptor>
*/
private function resolveSymfonyTask(\ReflectionClass $reflectionClass): iterable
{
$attributes = $reflectionClass->getAttributes(AsSymfonyTask::class, \ReflectionAttribute::IS_INSTANCEOF);
if (!\count($attributes)) {
return;
}
$taskAttribute = $attributes[0]->newInstance();
$console = $taskAttribute->console;
$key = hash('sha256', implode('-', ['symfony-console-definitions-', ...$console, $this->rootDir]));
$definitions = $this->cache->get($key, function (ItemInterface $item) use ($console) {
$item->expiresAfter(60 * 60 * 24);
$p = new Process([...$console, '--format=json']);
$p->mustRun();
return json_decode($p->getOutput(), true);
});
$sfAttribute = $reflectionClass->getAttributes(AsCommand::class);
if (\count($sfAttribute)) {
$sfAttribute = $sfAttribute[0]->newInstance();
if (!$taskAttribute->originalName) {
$taskAttribute->originalName = $sfAttribute->name;
}
if (!$taskAttribute->name) {
$taskAttribute->name = $sfAttribute->name;
}
}
if (!$taskAttribute->name) {
throw new FunctionConfigurationException('The task command must have a name.', $reflectionClass);
}
$definition = null;
foreach ($definitions['commands'] as $definition) {
if ($definition['name'] !== $taskAttribute->originalName) {
continue;
}
break;
}
if ($definition['name'] !== $taskAttribute->originalName) {
throw new FunctionConfigurationException(sprintf('Could not find a command named "%s" in the Symfony application', $taskAttribute->name), $reflectionClass);
}
yield new SymfonyTaskDescriptor($taskAttribute, $reflectionClass, $definition);
}
/**
* @return iterable<ContextDescriptor>
*/
private function resolveContexts(\ReflectionFunction $reflectionFunction): iterable
{
$attributes = $reflectionFunction->getAttributes(AsContext::class, \ReflectionAttribute::IS_INSTANCEOF);
if (!\count($attributes)) {
return;
}
$contextAttribute = $attributes[0]->newInstance();
if ('' === $contextAttribute->name) {
if ($contextAttribute->default) {
$contextAttribute->name = 'default';
} else {
$contextAttribute->name = SluggerHelper::slug($reflectionFunction->getShortName());
}
}
yield new ContextDescriptor($contextAttribute, $reflectionFunction);
}
/**
* @return iterable<ContextGeneratorDescriptor>
*/
private function resolveContextGenerators(\ReflectionFunction $reflectionFunction): iterable
{
$attributes = $reflectionFunction->getAttributes(AsContextGenerator::class, \ReflectionAttribute::IS_INSTANCEOF);
if (!\count($attributes)) {
return;
}
$contextAttribute = $attributes[0]->newInstance();
if ($reflectionFunction->getParameters()) {
throw new FunctionConfigurationException('The contexts generator must not have arguments.', $reflectionFunction);
}
$generators = [];
foreach ($reflectionFunction->invoke() as $name => $generator) {
if (!$generator instanceof \Closure) {
throw new FunctionConfigurationException(sprintf('The context generator "%s" is not callable.', $name), $reflectionFunction);
}
$r = new \ReflectionFunction($generator);
if ($r->getParameters()) {
throw new FunctionConfigurationException(sprintf('The context generator "%s" must not have arguments.', $name), $reflectionFunction);
}
$generators[$name] = $generator;
}
yield new ContextGeneratorDescriptor($contextAttribute, $reflectionFunction, $generators);
}
/**
* @return iterable<ListenerDescriptor>
*/
private function resolveListeners(\ReflectionFunction $reflectionFunction): iterable
{
$attributes = $reflectionFunction->getAttributes(AsListener::class);
foreach ($attributes as $attribute) {
/** @var AsListener $listenerAttribute */
$listenerAttribute = $attribute->newInstance();
yield new ListenerDescriptor($listenerAttribute, $reflectionFunction);
}
}
}
// Don't leak internal variables
/** @internal */
function castor_require(string $file): void
{
if (!is_file($file)) {
throw new \RuntimeException(sprintf('Could not find file "%s".', $file));
}
FunctionFinder::$files[] = $file;
require_once $file;
}