-
Notifications
You must be signed in to change notification settings - Fork 16
/
Application.php
275 lines (236 loc) 路 10.1 KB
/
Application.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
<?php
namespace Castor\Console;
use Castor\Console\Command\SymfonyTaskCommand;
use Castor\Console\Command\TaskCommand;
use Castor\Console\Input\Input;
use Castor\Context;
use Castor\ContextDescriptor;
use Castor\ContextGeneratorDescriptor;
use Castor\ContextRegistry;
use Castor\Event\AfterApplicationInitializationEvent;
use Castor\Event\BeforeApplicationInitializationEvent;
use Castor\EventDispatcher;
use Castor\ExpressionLanguage;
use Castor\Fingerprint\FingerprintHelper;
use Castor\FunctionFinder;
use Castor\GlobalHelper;
use Castor\ListenerDescriptor;
use Castor\PlatformUtil;
use Castor\Remote\Importer;
use Castor\SectionOutput;
use Castor\SymfonyTaskDescriptor;
use Castor\TaskDescriptor;
use Castor\TaskDescriptorCollection;
use Castor\VerbosityLevel;
use Castor\WaitForHelper;
use Monolog\Logger;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Log\LogLevel;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\ExceptionInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\ErrorHandler\ErrorHandler;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\VarDumper\Cloner\AbstractCloner;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/** @internal */
class Application extends SymfonyApplication
{
public const NAME = 'castor';
public const VERSION = 'v0.14.0';
// "Current" objects availables at some point of the lifecycle
private Input $input;
private SectionOutput $sectionOutput;
private SymfonyStyle $symfonyStyle;
private Command $command;
public function __construct(
private readonly string $rootDir,
public readonly FunctionFinder $functionFinder,
public readonly ContextRegistry $contextRegistry,
public readonly EventDispatcher $eventDispatcher,
public readonly ExpressionLanguage $expressionLanguage,
public readonly Logger $logger,
public readonly Filesystem $fs,
public readonly WaitForHelper $waitForHelper,
public readonly FingerprintHelper $fingerprintHelper,
public readonly Importer $importer,
public HttpClientInterface $httpClient,
public CacheItemPoolInterface&CacheInterface $cache,
) {
$handler = ErrorHandler::register();
$handler->setDefaultLogger($logger, [
\E_COMPILE_WARNING => LogLevel::WARNING,
\E_CORE_WARNING => LogLevel::WARNING,
\E_USER_WARNING => LogLevel::WARNING,
\E_WARNING => LogLevel::WARNING,
\E_USER_DEPRECATED => LogLevel::WARNING,
\E_DEPRECATED => LogLevel::WARNING,
\E_USER_NOTICE => LogLevel::WARNING,
\E_NOTICE => LogLevel::WARNING,
\E_COMPILE_ERROR => LogLevel::ERROR,
\E_CORE_ERROR => LogLevel::ERROR,
\E_ERROR => LogLevel::ERROR,
\E_PARSE => LogLevel::ERROR,
\E_RECOVERABLE_ERROR => LogLevel::ERROR,
\E_STRICT => LogLevel::ERROR,
\E_USER_ERROR => LogLevel::ERROR,
]);
$this->setCatchErrors(true);
AbstractCloner::$defaultCasters[self::class] = ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'];
AbstractCloner::$defaultCasters[AfterApplicationInitializationEvent::class] = ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'];
parent::__construct(static::NAME, static::VERSION);
GlobalHelper::setApplication($this);
}
public function getInput(): Input
{
return $this->input ?? throw new \LogicException('Input not available yet.');
}
public function getSectionOutput(): SectionOutput
{
return $this->sectionOutput ?? throw new \LogicException('Section output not available yet.');
}
public function getOutput(): OutputInterface
{
return $this->getSectionOutput()->getConsoleOutput();
}
public function getSymfonyStyle(): SymfonyStyle
{
return $this->symfonyStyle ?? throw new \LogicException('SymfonyStyle not available yet.');
}
/**
* @return ($allowNull is true ? ?Command : Command)
*/
public function getCommand(bool $allowNull = false): ?Command
{
return $this->command ?? ($allowNull ? null : throw new \LogicException('Command not available yet.'));
}
// We do all the logic as late as possible to ensure the exception handler
// is registered
public function doRun(InputInterface $input, OutputInterface $output): int
{
if ($input instanceof Input) {
$this->input = $input;
}
$this->sectionOutput = new SectionOutput($output);
$this->symfonyStyle = new SymfonyStyle($input, $output);
$this->logger->pushHandler(new ConsoleHandler($output));
$event = new BeforeApplicationInitializationEvent($this);
$this->eventDispatcher->dispatch($event);
$descriptors = $this->initializeApplication($input);
// Must be done after the initializeApplication() call, to ensure all
// contexts have been created; but before the adding of task, because we
// may want to seek in the context to know if the command is enabled
$this->configureContext($input, $output);
$event = new AfterApplicationInitializationEvent($this, $descriptors);
$this->eventDispatcher->dispatch($event);
$descriptors = $event->taskDescriptorCollection;
foreach ($descriptors->taskDescriptors as $taskDescriptor) {
$this->add(new TaskCommand(
$taskDescriptor->taskAttribute,
$taskDescriptor->function,
$this->eventDispatcher,
$this->expressionLanguage,
));
}
foreach ($descriptors->symfonyTaskDescriptors as $symfonyTaskDescriptor) {
$this->add(new SymfonyTaskCommand(
$symfonyTaskDescriptor->taskAttribute,
$symfonyTaskDescriptor->function,
$symfonyTaskDescriptor->definition,
));
}
return parent::doRun($input, $output);
}
protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int
{
$this->command = $command;
return parent::doRunCommand($command, $input, $output);
}
private function initializeApplication(InputInterface $input): TaskDescriptorCollection
{
$functionsRootDir = $this->rootDir;
if (class_exists(\RepackedApplication::class)) {
$functionsRootDir = \RepackedApplication::ROOT_DIR;
}
$descriptors = $this->functionFinder->findFunctions($functionsRootDir);
$tasks = [];
$symfonyTasks = [];
foreach ($descriptors as $descriptor) {
if ($descriptor instanceof TaskDescriptor) {
$tasks[] = $descriptor;
} elseif ($descriptor instanceof SymfonyTaskDescriptor) {
$symfonyTasks[] = $descriptor;
} elseif ($descriptor instanceof ContextDescriptor) {
$this->contextRegistry->addDescriptor($descriptor);
} elseif ($descriptor instanceof ContextGeneratorDescriptor) {
foreach ($descriptor->generators as $name => $generator) {
$this->contextRegistry->addContext($name, $generator);
}
} elseif ($descriptor instanceof ListenerDescriptor && null !== $descriptor->reflectionFunction->getClosure()) {
$this->eventDispatcher->addListener(
$descriptor->asListener->event,
$descriptor->reflectionFunction->getClosure(),
$descriptor->asListener->priority
);
}
}
$this->contextRegistry->setDefaultIfEmpty();
$contextNames = $this->contextRegistry->getNames();
if ($contextNames) {
$defaultContext = PlatformUtil::getEnv('CASTOR_CONTEXT') ?: $this->contextRegistry->getDefaultName();
$this->getDefinition()->addOption(new InputOption(
'context',
'_complete' === $input->getFirstArgument() || 'list' === $input->getFirstArgument() ? null : 'c',
InputOption::VALUE_REQUIRED,
sprintf('The context to use (%s)', implode('|', $contextNames)),
$defaultContext,
$contextNames,
));
}
$this->getDefinition()->addOption(
new InputOption(
'no-remote',
null,
InputOption::VALUE_NONE,
'Skips the import of all remote remote packages.',
)
);
$this->getDefinition()->addOption(
new InputOption(
'update-remotes',
null,
InputOption::VALUE_NONE,
'Force the update of remote packages.',
)
);
return new TaskDescriptorCollection($tasks, $symfonyTasks);
}
private function configureContext(InputInterface $input, OutputInterface $output): void
{
try {
$input->bind($this->getDefinition());
} catch (ExceptionInterface) {
// not an issue if parsing gone wrong, we'll just use the default
// context and it will fail later anyway
}
// occurs when running `castor -h`, or if no context is defined
if (!$input->hasOption('context')) {
$this->contextRegistry->setCurrentContext(new Context());
return;
}
$context = $this
->contextRegistry
->get($input->getOption('context'))
;
if ($context->verbosityLevel->isNotConfigured()) {
$context = $context->withVerbosityLevel(VerbosityLevel::fromSymfonyOutput($output));
}
$this->contextRegistry->setCurrentContext($context->withName($input->getOption('context')));
}
}