-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathApplication.php
579 lines (482 loc) · 16.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
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
<?php
/*
* This file is part of the {{ }} package.
*
* (c) Yo-An Lin <cornelius.howl@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
*/
namespace CLIFramework;
use GetOptionKit\ContinuousOptionParser;
use GetOptionKit\OptionCollection;
use CLIFramework\CommandLoader;
use CLIFramework\CommandBase;
use CLIFramework\Logger;
use CLIFramework\CommandInterface;
use CLIFramework\Prompter;
use CLIFramework\CommandGroup;
use CLIFramework\Formatter;
use CLIFramework\Corrector;
use CLIFramework\ServiceContainer;
use CLIFramework\Exception\CommandNotFoundException;
use CLIFramework\Exception\CommandArgumentNotEnoughException;
use CLIFramework\Exception\ExecuteMethodNotDefinedException;
use Pimple\Container;
use CLIFramework\ExceptionPrinter\ProductionExceptionPrinter;
use CLIFramework\ExceptionPrinter\DevelopmentExceptionPrinter;
use CLIFramework\Command\HelpCommand;
use CLIFramework\Command\ZshCompletionCommand;
use CLIFramework\Command\BashCompletionCommand;
use CLIFramework\Command\MetaCommand;
use CLIFramework\Command\CompileCommand;
use CLIFramework\Command\ArchiveCommand;
use CLIFramework\Command\BuildGitHubWikiTopicsCommand;
use Exception;
use ReflectionClass;
use InvalidArgumentException;
use BadMethodCallException;
class Application extends CommandBase implements CommandInterface
{
const CORE_VERSION = '3.0.0';
const VERSION = "3.0.0";
const NAME = 'CLIFramework';
/**
* timestamp when started
*/
public $startedAt;
public $supportReadline;
public $showAppSignature = true;
/**
*
*/
public $topics = array();
/**
* @var CLIFramework\Formatter
*/
public $formatter;
/**
* Command message logger.
*
* (This should be deprecated since we use service container from now on).
*
* @var CLIFramework\Logger
*/
public $logger;
public $programName;
/**
* @var CLIFramework\ServiceContainer
*/
protected $serviceContainer;
/**
* @var Unviersal\Event\EventDispatcher
*/
protected $eventService;
/**
* cliframework global config
*/
protected $globalConfig;
/** @var bool */
protected $commandAutoloadEnabled = false;
public function __construct(Container $container = null, CommandBase $parent = null)
{
parent::__construct($parent);
$this->serviceContainer = $container ?: ServiceContainer::getInstance();
if (isset($this->serviceContainer['event'])) {
$this->eventService = $this->serviceContainer['event'];
} else {
$this->eventService = EventDispatcher::getInstance();
}
// initliaze command loader
// TODO: if the service is not defined, we should create them with default settings.
$this->loader = $this->serviceContainer['command_loader'];
$this->logger = $this->serviceContainer['logger'];
$this->formatter = $this->serviceContainer['formatter'];
$this->globalConfig = $this->serviceContainer['config'];
// get current class namespace, add {App}\Command\ to loader
$appRefClass = new ReflectionClass($this);
$appNs = $appRefClass->getNamespaceName();
$this->loader->addNamespace('\\' . $appNs . '\\Command');
$this->loader->addNamespace(array('\\CLIFramework\\Command' ));
$this->supportReadline = extension_loaded('readline');
}
/**
* @return Pimple\Container
*/
public function getService()
{
return $this->serviceContainer;
}
public function getEventService()
{
return $this->eventService;
}
/**
* Enable command autoload feature.
*
* @return void
*/
public function enableCommandAutoload()
{
$this->commandAutoloadEnabled = true;
}
/**
* Disable command autoload feature.
*
* @return void
*/
public function disableCommandAutoload()
{
$this->commandAutoloadEnabled = false;
}
/**
* Use ReflectionClass to get the namespace of the current running app.
* (not CLIFramework\Application itself)
*
* @return string classname
*/
public function getCurrentAppNamespace()
{
$refClass = new ReflectionClass($this);
return $refClass->getNamespaceName();
}
/**
* @return string brief of this application
*/
public function brief()
{
return 'application brief';
}
public function usage()
{
return 'application usage';
}
/**
* Register application option specs to the parser
*/
public function options($opts)
{
$opts->add('v|verbose', 'Print verbose message.');
$opts->add('d|debug', 'Print debug message.');
$opts->add('q|quiet', 'Be quiet.');
$opts->add('h|help', 'Show help.');
$opts->add('version', 'Show version.');
$opts->add('p|profile', 'Display timing and memory usage information.');
$opts->add('log-path?', 'The path of a log file.');
// Un-implemented options
$opts->add('no-interact', 'Do not ask any interactive question.');
// $opts->add('no-ansi', 'Disable ANSI output.');
}
public function topics(array $topics)
{
foreach ($topics as $key => $val) {
if (is_numeric($key)) {
$this->topics[$val] = $this->loadTopic($val);
} else {
$this->topics[$key] = $this->loadTopic($val);
}
}
}
public function topic($topicId, $topicClass = null)
{
$this->topics[$topicId] = $topicClass ? new $topicClass: $this->loadTopic($topicId);
}
public function getTopic($topicId)
{
if (isset($this->topics[$topicId])) {
return $this->topics[$topicId];
}
}
public function loadTopic($topicId)
{
// existing class name or full-qualified class name
if (class_exists($topicId, true)) {
return new $topicId;
}
if (!preg_match('/Topic$/', $topicId)) {
$className = ucfirst($topicId) . 'Topic';
} else {
$className = ucfirst($topicId);
}
$possibleNs = array($this->getCurrentAppNamespace(), 'CLIFramework');
foreach ($possibleNs as $ns) {
$class = $ns . '\\' . 'Topic' . '\\' . $className;
if (class_exists($class, true)) {
return new $class;
}
}
throw new InvalidArgumentException("Topic $topicId not found.");
}
/*
* init application,
*
* users register command mapping here. (command to class name)
*/
public function init()
{
// $this->addCommand('list','CLIFramework\\Command\\ListCommand');
parent::init();
$this->command('help', HelpCommand::class);
$this->commandGroup("Development Commands", array(
'zsh' => ZshCompletionCommand::class,
'bash' => BashCompletionCommand::class,
'meta' => MetaCommand::class,
'compile' => CompileCommand::class,
'archive' => ArchiveCommand::class,
'github:build-topics' => BuildGitHubWikiTopicsCommand::class,
))->setId('dev');
}
/**
* Execute `run` method with a default try & catch block to catch the exception.
*
* @param array $argv
*
* @return bool return true for success, false for failure. the returned
* state will be reflected to the exit code of the process.
*/
public function runWithTry(array $argv)
{
try {
return $this->run($argv);
} catch (CommandArgumentNotEnoughException $e) {
$this->logger->error($e->getMessage());
$this->logger->writeln("Expected argument prototypes:");
foreach ($e->getCommand()->getAllCommandPrototype() as $p) {
$this->logger->writeln("\t" . $p);
}
$this->logger->newline();
} catch (CommandNotFoundException $e) {
$this->logger->error($e->getMessage() . " available commands are: " . join(', ', $e->getCommand()->getVisibleCommandList()));
$this->logger->newline();
$this->logger->writeln("Please try the command below to see the details:");
$this->logger->newline();
$this->logger->writeln("\t" . $this->getProgramName() . ' help ');
$this->logger->newline();
} catch (BadMethodCallException $e) {
$this->logger->error($e->getMessage());
$this->logger->error("Seems like an application logic error, please contact the developer.");
} catch (Exception $e) {
if ($this->options && $this->options->debug) {
$printer = new DevelopmentExceptionPrinter($this->getLogger());
$printer->dump($e);
} else {
$printer = new ProductionExceptionPrinter($this->getLogger());
$printer->dump($e);
}
}
return false;
}
/**
* Run application with
* list argv
*
* @param Array $argv
*
* @return bool return true for success, false for failure. the returned
* state will be reflected to the exit code of the process.
* */
public function run(array $argv)
{
$this->setProgramName($argv[0]);
$currentCommand = $this;
// init application,
// before parsing options, we have to known the registered commands.
$currentCommand->init();
// use getoption kit to parse application options
$parser = new ContinuousOptionParser($currentCommand->getOptionCollection());
// parse the first part options (options after script name)
// option parser should stop before next command name.
//
// $ app.php -v -d next
// |
// |->> parser
//
//
$appOptions = $parser->parse($argv);
$currentCommand->setOptions($appOptions);
if (false === $currentCommand->prepare()) {
return false;
}
$commandStack = array();
$arguments = array();
// build the command list from command line arguments
while (! $parser->isEnd()) {
$a = $parser->getCurrentArgument();
// if current command is in subcommand list.
if ($currentCommand->hasCommands()) {
if (!$currentCommand->hasCommand($a)) {
if (!$appOptions->noInteract && ($guess = $currentCommand->guessCommand($a)) !== null) {
$a = $guess;
} else {
throw new CommandNotFoundException($currentCommand, $a);
}
}
$parser->advance(); // advance position
// get command object of "$a"
$nextCommand = $currentCommand->getCommand($a);
$parser->setSpecs($nextCommand->getOptionCollection());
// parse the option result for command.
$result = $parser->continueParse();
$nextCommand->setOptions($result);
$commandStack[] = $currentCommand = $nextCommand; // save command object into the stack
} else {
$r = $parser->continueParse();
if (count($r)) {
// get the option result and merge the new result
$currentCommand->getOptions()->merge($r);
} else {
$a = $parser->advance();
$arguments[] = $a;
}
}
}
foreach ($commandStack as $cmd) {
if (false === $cmd->prepare()) {
return false;
}
}
// get last command and run
if ($lastCommand = array_pop($commandStack)) {
$return = $lastCommand->executeWrapper($arguments);
$lastCommand->finish();
while ($cmd = array_pop($commandStack)) {
// call finish stage.. of every command.
$cmd->finish();
}
} else {
// no command specified.
return $this->executeWrapper($arguments);
}
$currentCommand->finish();
$this->finish();
return true;
}
/**
* This is a `before` trigger of an app. when the application is getting
* started, we run `prepare` method to prepare the settings.
*/
public function prepare()
{
$this->startedAt = microtime(true);
$options = $this->getOptions();
$config = $this->getGlobalConfig();
if ($options->debug || $options->verbose || $options->quiet) {
if ($options->debug) {
$this->getLogger()->setDebug();
} elseif ($options->verbose) {
$this->getLogger()->setVerbose();
} elseif ($options->quiet) {
$this->getLogger()->setLevel(2);
}
} else {
if ($config->isDebug()) {
$this->getLogger()->setDebug();
} elseif ($config->isVerbose()) {
$this->getLogger()->setVerbose();
}
}
return true;
}
public function finish()
{
if ($this->options->profile) {
$this->logger->info(
sprintf('Memory usage: %.2fMB (peak: %.2fMB), time: %.4fs',
memory_get_usage(true) / (1024 * 1024),
memory_get_peak_usage(true) / (1024 * 1024),
(microtime(true) - $this->startedAt)
)
);
}
}
public function getCoreVersion()
{
if (defined('static::core_version')) {
return static::core_version;
}
if (defined('static::CORE_VERSION')) {
return static::CORE_VERSION;
}
}
public function getVersion()
{
if (defined('static::VERSION')) {
return static::VERSION;
}
if (defined('static::version')) {
return static::version;
}
}
public function setProgramName($programName)
{
$this->programName = $programName;
}
public function getProgramName()
{
return $this->programName;
}
public function getName()
{
if (defined('static::NAME')) {
return static::NAME;
}
if (defined('static::name')) {
return static::name;
}
}
/**
* This method is the top logic of an application. when there is no
* argument provided, we show help content by default.
*
* @return bool return true if success
*/
public function execute()
{
$options = $this->getOptions();
if ($options->version) {
$this->logger->writeln($this->getName() . ' - ' . $this->getVersion());
$this->logger->writeln("cliframework core: " . $this->getCoreVersion());
return true;
}
$arguments = func_get_args();
// show list and help by default
$help = $this->getCommand('help');
$help->setOptions($options);
if ($help || $options->help) {
$help->executeWrapper($arguments);
return true;
}
throw new CommandNotFoundException($this, 'help');
}
public function getFormatter()
{
return $this->formatter;
}
public function getLogger()
{
return $this->logger;
}
public function getGlobalConfig()
{
return $this->globalConfig;
}
/**
* A quick helper for accessing service
*/
public function __get($name)
{
if (isset($this->serviceContainer[$name])) {
return $this->serviceContainer[$name];
}
throw new InvalidArgumentException("Application class doesn't have `$name` service or property.");
}
public static function getInstance()
{
static $app;
if ($app) {
return $app;
}
return $app = new static;
}
}