-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathsfCommandApplication.class.php
662 lines (558 loc) · 19 KB
/
sfCommandApplication.class.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfCommandApplication manages the lifecycle of a CLI application.
*
* @author Fabien Potencier <[email protected]>
*/
abstract class sfCommandApplication
{
/** @var sfCommandManager */
protected $commandManager;
/** @var bool */
protected $trace = false;
/** @var bool */
protected $verbose = true;
/** @var bool */
protected $debug = true;
/** @var bool */
protected $nowrite = false;
/** @var string */
protected $name = 'UNKNOWN';
/** @var string */
protected $version = 'UNKNOWN';
/** @var array */
protected $tasks = [];
/** @var sfTask */
protected $currentTask;
/** @var sfEventDispatcher */
protected $dispatcher;
/** @var array */
protected $options = [];
/** @var sfFormatter */
protected $formatter;
protected $commandOptions;
/**
* Constructor.
*
* @param sfEventDispatcher $dispatcher A sfEventDispatcher instance
* @param sfFormatter $formatter A sfFormatter instance
* @param array $options An array of options
*/
public function __construct(sfEventDispatcher $dispatcher, ?sfFormatter $formatter = null, $options = [])
{
$this->dispatcher = $dispatcher;
$this->formatter = $formatter ?? $this->guessBestFormatter(STDOUT);
$this->options = $options;
$this->fixCgi();
$argumentSet = new sfCommandArgumentSet([
new sfCommandArgument('task', sfCommandArgument::REQUIRED, 'The task to execute'),
]);
$optionSet = new sfCommandOptionSet([
new sfCommandOption('--help', '-H', sfCommandOption::PARAMETER_NONE, 'Display this help message.'),
new sfCommandOption('--quiet', '-q', sfCommandOption::PARAMETER_NONE, 'Do not log messages to standard output.'),
new sfCommandOption('--trace', '-t', sfCommandOption::PARAMETER_NONE, 'Turn on invoke/execute tracing, enable full backtrace.'),
new sfCommandOption('--version', '-V', sfCommandOption::PARAMETER_NONE, 'Display the program version.'),
new sfCommandOption('--color', '', sfCommandOption::PARAMETER_NONE, 'Forces ANSI color output.'),
new sfCommandOption('--no-debug', '', sfCommandOption::PARAMETER_NONE, 'Disable debug'),
]);
$this->commandManager = new sfCommandManager($argumentSet, $optionSet);
$this->configure();
$this->registerTasks();
}
/**
* Configures the current command application.
*/
abstract public function configure();
/**
* Returns the value of a given option.
*
* @param string $name The option name
*
* @return mixed The option value
*/
public function getOption($name)
{
return $this->options[$name] ?? null;
}
/**
* Returns the formatter instance.
*
* @return sfFormatter The formatter instance
*/
public function getFormatter()
{
return $this->formatter;
}
/**
* Sets the formatter instance.
*
* @param sfFormatter $formatter The formatter instance
*/
public function setFormatter(sfFormatter $formatter)
{
$this->formatter = $formatter;
foreach ($this->getTasks() as $task) {
$task->setFormatter($formatter);
}
}
public function clearTasks()
{
$this->tasks = [];
}
/**
* Registers an array of task objects.
*
* If you pass null, this method will register all available tasks.
*
* @param array $tasks An array of tasks
*/
public function registerTasks($tasks = null)
{
if (null === $tasks) {
$tasks = $this->autodiscoverTasks();
}
foreach ($tasks as $task) {
$this->registerTask($task);
}
}
/**
* Registers a task object.
*
* @param sfTask $task An sfTask object
*
* @throws sfCommandException
*/
public function registerTask(sfTask $task)
{
if (isset($this->tasks[$task->getFullName()])) {
throw new sfCommandException(sprintf('The task named "%s" in "%s" task is already registered by the "%s" task.', $task->getFullName(), get_class($task), get_class($this->tasks[$task->getFullName()])));
}
$this->tasks[$task->getFullName()] = $task;
foreach ($task->getAliases() as $alias) {
if (isset($this->tasks[$alias])) {
throw new sfCommandException(sprintf('A task named "%s" is already registered.', $alias));
}
$this->tasks[$alias] = $task;
}
}
/**
* Autodiscovers task classes.
*
* @return array An array of tasks instances
*/
public function autodiscoverTasks()
{
$tasks = [];
foreach (get_declared_classes() as $class) {
$r = new ReflectionClass($class);
if ($r->isSubclassOf('sfTask') && !$r->isAbstract()) {
$tasks[] = new $class($this->dispatcher, $this->formatter);
}
}
return $tasks;
}
/**
* Returns all registered tasks.
*
* @return array An array of sfTask objects
*/
public function getTasks()
{
return $this->tasks;
}
/**
* Returns a registered task by name or alias.
*
* @param string $name The task name or alias
*
* @return sfTask An sfTask object
*
* @throws sfCommandException
*/
public function getTask($name)
{
if (!isset($this->tasks[$name])) {
throw new sfCommandException(sprintf('The task "%s" does not exist.', $name));
}
return $this->tasks[$name];
}
/**
* Runs the current application.
*
* @param mixed $options The command line options
*
* @return int 0 if everything went fine, or an error code
*/
public function run($options = null)
{
$this->handleOptions($options);
$arguments = $this->commandManager->getArgumentValues();
$this->currentTask = $this->getTaskToExecute($arguments['task']);
$ret = $this->currentTask->runFromCLI($this->commandManager, $this->commandOptions);
$this->currentTask = null;
return $ret;
}
/**
* Gets the name of the application.
*
* @return string The application name
*/
public function getName()
{
return $this->name;
}
/**
* Sets the application name.
*
* @param string $name The application name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Gets the application version.
*
* @return string The application version
*/
public function getVersion()
{
return $this->version;
}
/**
* Sets the application version.
*
* @param string $version The application version
*/
public function setVersion($version)
{
$this->version = $version;
}
/**
* Returns the long version of the application.
*
* @return string The long application version
*/
public function getLongVersion()
{
return sprintf('%s version %s', $this->getName(), $this->formatter->format($this->getVersion(), 'INFO'))."\n";
}
/**
* Returns whether the application must be verbose.
*
* @return bool true if the application must be verbose, false otherwise
*/
public function isVerbose()
{
return $this->verbose;
}
/**
* Returns whether the application must activate the trace.
*
* @return bool true if the application must activate the trace, false otherwise
*/
public function withTrace()
{
return $this->trace;
}
/**
* Returns whether the application must be verbose.
*
* @return bool true if the application is in debug mode, false otherwise
*/
public function isDebug()
{
return $this->debug;
}
/**
* Outputs a help message for the current application.
*/
public function help()
{
$messages = [
$this->formatter->format('Usage:', 'COMMENT'),
sprintf(" %s [options] task_name [arguments]\n", $this->getName()),
$this->formatter->format('Options:', 'COMMENT'),
];
foreach ($this->commandManager->getOptionSet()->getOptions() as $option) {
$messages[] = sprintf(
' %-24s %s %s',
$this->formatter->format('--'.$option->getName(), 'INFO'),
$option->getShortcut() ? $this->formatter->format('-'.$option->getShortcut(), 'INFO') : ' ',
$option->getHelp()
);
}
$this->dispatcher->notify(new sfEvent($this, 'command.log', $messages));
}
/**
* Renders an exception.
*
* @param Exception $e An exception object
*/
public function renderException($e)
{
$title = sprintf(' [%s] ', get_class($e));
$len = $this->strlen($title);
$lines = [];
foreach (explode("\n", $e->getMessage()) as $line) {
$lines[] = sprintf(' %s ', $line);
$len = max($this->strlen($line) + 4, $len);
}
$messages = [str_repeat(' ', $len)];
if ($this->trace) {
$messages[] = $title.str_repeat(' ', $len - $this->strlen($title));
}
foreach ($lines as $line) {
$messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
}
$messages[] = str_repeat(' ', $len);
fwrite(STDERR, "\n");
foreach ($messages as $message) {
fwrite(STDERR, $this->formatter->format($message, 'ERROR', STDERR)."\n");
}
fwrite(STDERR, "\n");
if (null !== $this->currentTask && $e instanceof sfCommandArgumentsException) {
fwrite(STDERR, $this->formatter->format(sprintf($this->currentTask->getSynopsis(), $this->getName()), 'INFO', STDERR)."\n");
fwrite(STDERR, "\n");
}
if ($this->trace) {
fwrite(STDERR, $this->formatter->format("Exception trace:\n", 'COMMENT'));
// exception related properties
$trace = $e->getTrace();
array_unshift($trace, [
'function' => '',
'file' => null != $e->getFile() ? $e->getFile() : 'n/a',
'line' => null != $e->getLine() ? $e->getLine() : 'n/a',
'args' => [],
]);
for ($i = 0, $count = count($trace); $i < $count; ++$i) {
$class = $trace[$i]['class'] ?? '';
$type = $trace[$i]['type'] ?? '';
$function = $trace[$i]['function'];
$file = $trace[$i]['file'] ?? 'n/a';
$line = $trace[$i]['line'] ?? 'n/a';
fwrite(STDERR, sprintf(" %s%s%s at %s:%s\n", $class, $type, $function, $this->formatter->format($file, 'INFO', STDERR), $this->formatter->format($line, 'INFO', STDERR)));
}
fwrite(STDERR, "\n");
}
$this->dispatcher->notify(new sfEvent($e, 'application.throw_exception'));
}
/**
* Gets a task from a task name or a shortcut.
*
* @param string $name The task name or a task shortcut
*
* @return sfTask A sfTask object
*
* @throws sfCommandException
*/
public function getTaskToExecute($name)
{
// namespace
if (false !== $pos = strpos($name, ':')) {
$namespace = substr($name, 0, $pos);
$name = substr($name, $pos + 1);
$namespaces = [];
foreach ($this->tasks as $task) {
if ($task->getNamespace() && !in_array($task->getNamespace(), $namespaces)) {
$namespaces[] = $task->getNamespace();
}
}
$abbrev = $this->getAbbreviations($namespaces);
if (!isset($abbrev[$namespace])) {
throw new sfCommandException(sprintf('There are no tasks defined in the "%s" namespace.', $namespace));
}
if (count($abbrev[$namespace]) > 1) {
throw new sfCommandException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, implode(', ', $abbrev[$namespace])));
}
$namespace = $abbrev[$namespace][0];
} else {
$namespace = '';
}
// name
$tasks = [];
foreach ($this->tasks as $taskName => $task) {
if ($taskName == $task->getFullName() && $task->getNamespace() == $namespace) {
$tasks[] = $task->getName();
}
}
$abbrev = $this->getAbbreviations($tasks);
if (isset($abbrev[$name]) && 1 == count($abbrev[$name])) {
return $this->getTask($namespace ? $namespace.':'.$abbrev[$name][0] : $abbrev[$name][0]);
}
// aliases
$aliases = [];
foreach ($this->tasks as $taskName => $task) {
if ($taskName == $task->getFullName()) {
foreach ($task->getAliases() as $alias) {
$aliases[] = $alias;
}
}
}
$abbrev = $this->getAbbreviations($aliases);
$fullName = $namespace ? $namespace.':'.$name : $name;
if (!isset($abbrev[$fullName])) {
throw new sfCommandException(sprintf('Task "%s" is not defined.', $fullName));
}
if (count($abbrev[$fullName]) > 1) {
throw new sfCommandException(sprintf('Task "%s" is ambiguous (%s).', $fullName, implode(', ', $abbrev[$fullName])));
}
return $this->getTask($abbrev[$fullName][0]);
}
/**
* Parses and handles command line options.
*
* @param mixed $options The command line options
*/
protected function handleOptions($options = null)
{
$this->commandManager->process($options);
$this->commandOptions = $options;
// the order of option processing matters
if ($this->commandManager->getOptionSet()->hasOption('color') && false !== $this->commandManager->getOptionValue('color')) {
$this->setFormatter(new sfAnsiColorFormatter());
}
if ($this->commandManager->getOptionSet()->hasOption('quiet') && false !== $this->commandManager->getOptionValue('quiet')) {
$this->verbose = false;
}
if ($this->commandManager->getOptionSet()->hasOption('no-debug') && false !== $this->commandManager->getOptionValue('no-debug')) {
$this->debug = false;
}
if ($this->commandManager->getOptionSet()->hasOption('trace') && false !== $this->commandManager->getOptionValue('trace')) {
$this->verbose = true;
$this->trace = true;
}
if ($this->commandManager->getOptionSet()->hasOption('help') && false !== $this->commandManager->getOptionValue('help')) {
$this->help();
exit(0);
}
if ($this->commandManager->getOptionSet()->hasOption('version') && false !== $this->commandManager->getOptionValue('version')) {
echo $this->getLongVersion();
exit(0);
}
}
protected function strlen($string)
{
if (!function_exists('mb_strlen')) {
return strlen($string);
}
if (false === $encoding = mb_detect_encoding($string)) {
return strlen($string);
}
return mb_strlen($string, $encoding);
}
/**
* Fixes php behavior if using cgi php.
*
* @see http://www.sitepoint.com/article/php-command-line-1/3
*/
protected function fixCgi()
{
// handle output buffering
if (ob_get_level() > 0) {
@ob_end_flush();
}
ob_implicit_flush(true);
// PHP ini settings
set_time_limit(0);
ini_set('track_errors', true);
ini_set('html_errors', false);
ini_set('magic_quotes_runtime', false);
if (false === strpos(PHP_SAPI, 'cgi')) {
return;
}
// define stream constants
define('STDIN', fopen('php://stdin', 'r'));
define('STDOUT', fopen('php://stdout', 'w'));
define('STDERR', fopen('php://stderr', 'w'));
// change directory
if (isset($_SERVER['PWD'])) {
chdir($_SERVER['PWD']);
}
// close the streams on script termination
register_shutdown_function(function () {
fclose(STDIN);
fclose(STDOUT);
fclose(STDERR);
return true;
});
}
/**
* Returns an array of possible abbreviations given a set of names.
*
* @see Text::Abbrev perl module for the algorithm
*
* @param string[] $names
*
* @return string[]
*/
protected function getAbbreviations($names)
{
$abbrevs = [];
$table = [];
foreach ($names as $name) {
for ($len = strlen($name) - 1; $len > 0; --$len) {
$abbrev = substr($name, 0, $len);
if (!array_key_exists($abbrev, $table)) {
$table[$abbrev] = 1;
} else {
++$table[$abbrev];
}
$seen = $table[$abbrev];
if (1 == $seen) {
// We're the first word so far to have this abbreviation.
$abbrevs[$abbrev] = [$name];
} elseif (2 == $seen) {
// We're the second word to have this abbreviation, so we can't use it.
// unset($abbrevs[$abbrev]);
$abbrevs[$abbrev][] = $name;
} else {
// We're the third word to have this abbreviation, so skip to the next word.
continue;
}
}
}
// Non-abbreviations always get entered, even if they aren't unique
foreach ($names as $name) {
$abbrevs[$name] = [$name];
}
return $abbrevs;
}
/**
* Returns true if the stream supports colorization.
*
* Colorization is disabled if not supported by the stream:
*
* - windows without ansicon
* - non tty consoles
*
* @param mixed $stream A stream
*
* @return bool true if the stream supports colorization, false otherwise
*/
protected function isStreamSupportsColors($stream)
{
if (DIRECTORY_SEPARATOR == '\\') {
return false !== getenv('ANSICON');
}
return function_exists('posix_isatty') && @posix_isatty($stream);
}
/**
* Guesses the best formatter for the stream.
*
* @param mixed $stream A stream
*
* @return sfFormatter A formatter instance
*/
protected function guessBestFormatter($stream)
{
return $this->isStreamSupportsColors($stream) ? new sfAnsiColorFormatter() : new sfFormatter();
}
}