forked from inhere/php-console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractApplication.php
More file actions
646 lines (556 loc) · 17.6 KB
/
Copy pathAbstractApplication.php
File metadata and controls
646 lines (556 loc) · 17.6 KB
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
<?php
/**
* Created by PhpStorm.
* User: inhere
* Date: 2017-03-09
* Time: 18:37
*/
namespace Inhere\Console\Base;
use Inhere\Console\IO\Input;
use Inhere\Console\IO\Output;
use Inhere\Console\Traits\InputOutputTrait;
use Inhere\Console\Traits\SimpleEventTrait;
use Inhere\Console\Style\Style;
use Inhere\Console\Utils\Helper;
/**
* Class AbstractApplication
* @package Inhere\Console
*/
abstract class AbstractApplication implements ApplicationInterface
{
use InputOutputTrait, SimpleEventTrait;
/**
* @var array
*/
protected static $internalCommands = [
'version' => 'Show application version information',
'help' => 'Show application help information',
'list' => 'List all group and independent commands',
];
/**
* @var array
*/
protected static $internalOptions = [
'--debug' => 'Setting the application runtime debug level',
'--profile' => 'Display timing and memory usage information',
'--no-color' => 'Disable color/ANSI for message output',
'-h, --help' => 'Display this help message',
'-V, --version' => 'Show application version information',
];
/**
* app meta config
* @var array
*/
private $meta = [
'name' => 'My Console',
'debug' => false,
'profile' => false,
'version' => '0.5.1',
'publishAt' => '2017.03.24',
'updateAt' => '2017.03.24',
'rootPath' => '',
'hideRootPath' => true,
// 'timeZone' => 'Asia/Shanghai',
// 'env' => 'pdt', // dev test pdt
// 'charset' => 'UTF-8',
// runtime stats
'_stats' => [],
];
/** @var string Command delimiter. e.g dev:serve */
public $delimiter = ':'; // '/' ':'
/** @var array The group commands */
protected $controllers = [];
/** @var array The independent commands */
protected $commands = [];
/** @var array */
private $commandMessages = [];
/** @var string */
private $commandName;
/**
* App constructor.
* @param array $meta
* @param Input $input
* @param Output $output
*/
public function __construct(array $meta = [], Input $input = null, Output $output = null)
{
$this->runtimeCheck();
$this->setMeta($meta);
$this->input = $input ?: new Input();
$this->output = $output ?: new Output();
$this->init();
}
protected function init()
{
$this->meta['_stats'] = [
'startTime' => microtime(1),
'startMemory' => memory_get_usage(true),
];
$this->commandName = $this->input->getCommand();
set_exception_handler([$this, 'handleException']);
}
/**********************************************************
* app run
**********************************************************/
protected function prepareRun()
{
// date_default_timezone_set($this->config('timeZone', 'UTC'));
//new AutoCompletion(array_merge($this->getCommandNames(), $this->getControllerNames()));
}
protected function beforeRun()
{}
/**
* run app
* @param bool $exit
*/
public function run($exit = true)
{
$command = trim($this->input->getCommand(), $this->delimiter);
$this->prepareRun();
$this->filterSpecialCommand($command);
// call 'onBeforeRun' service, if it is registered.
self::fire(self::ON_BEFORE_RUN, [$this]);
$this->beforeRun();
// do run ...
try {
$returnCode = $this->dispatch($command);
} catch (\Throwable $e) {
self::fire(self::ON_RUN_ERROR, [$e, $this]);
$returnCode = $e->getCode() === 0 ? $e->getLine() : $e->getCode();
$this->handleException($e);
}
$this->meta['_stats']['endTime'] = microtime(1);
// call 'onAfterRun' service, if it is registered.
self::fire(self::ON_AFTER_RUN, [$this]);
$this->afterRun();
if ($exit) {
$this->stop((int)$returnCode);
}
}
/**
* dispatch command
* @param string $command A command name
* @return int|mixed
*/
abstract protected function dispatch($command);
/**
* run a independent command
* {@inheritdoc}
*/
abstract public function runCommand($name, $believable = false);
/**
* run a controller's action
* {@inheritdoc}
*/
abstract public function runAction($name, $action, $believable = false, $standAlone = false);
protected function afterRun()
{
// display runtime info
if ($this->isProfile()) {
$title = '---------- Runtime Stats(profile=true) ----------';
$stats = $this->meta['_stats'];
$this->meta['_stats'] = Helper::runtime($stats['startTime'], $stats['startMemory'], $stats);
$this->output->write('');
$this->output->aList($this->meta['_stats'], $title);
}
}
/**
* @param int $code
*/
public function stop($code = 0)
{
// call 'onAppStop' service, if it is registered.
self::fire(self::ON_STOP_RUN, [$this]);
exit((int)$code);
}
/**********************************************************
* helper method for the application
**********************************************************/
/**
* runtime env check
*/
protected function runtimeCheck()
{
// check env
if (!\in_array(PHP_SAPI, ['cli', 'cli-server'], true)) {
header('HTTP/1.1 403 Forbidden');
exit(" 403 Forbidden \n\n"
. " current environment is CLI. \n"
. " :( Sorry! Run this script is only allowed in the terminal environment!\n,You are not allowed to access this file.\n");
}
}
/**
* 运行异常处理
* @param \Exception|\Throwable $e
*/
public function handleException($e)
{
$type = $e instanceof \Error ? 'Error' : 'Exception';
$title = ":( OO ... An $type Occurred!";
$this->logError($e);
// open debug, throw exception
if ($this->isDebug()) {
$tpl = <<<ERR
<danger>$title</danger>
Message <magenta>%s</magenta>
At File <cyan>%s</cyan> line <cyan>%d</cyan>
Catch by %s()\n
Code Trace:\n%s\n
ERR;
$message = sprintf(
$tpl,
// $e->getCode(),
$e->getMessage(),
$e->getFile(),
$e->getLine(),
__METHOD__,
$e->getTraceAsString()
);
if ($this->meta['hideRootPath'] && ($rootPath = $this->meta['rootPath'])) {
$message = str_replace($rootPath, '{ROOT}', $message);
}
$this->output->write($message, false);
} else {
// simple output
$this->output->error('An error occurred! MESSAGE: ' . $e->getMessage() . '. you can use --debug to see error details.');
}
}
/**
* @param \Throwable $e
*/
protected function logError($e)
{
// you can log error on sub class ...
}
/**
* @param $command
*/
protected function filterSpecialCommand($command)
{
if (!$command) {
if ($this->input->getSameOpt(['V', 'version'])) {
$this->showVersionInfo();
}
if ($this->input->getSameOpt(['h', 'help'])) {
$this->showHelpInfo();
}
}
if ($this->input->getSameOpt(['no-color'])) {
Style::setNoColor();
}
$command = $command ?: 'list';
switch ($command) {
case 'help':
$this->showHelpInfo(true, $this->input->getFirstArg());
break;
case 'list':
$this->showCommandList();
break;
case 'version':
$this->showVersionInfo();
break;
}
}
/**
* @param $name
* @param bool $isGroup
* @throws \InvalidArgumentException
*/
protected function validateName(string $name, $isGroup = false)
{
$pattern = $isGroup ? '/^[a-z][\w-]+$/' : '/^[a-z][\w-]*:?([a-z][\w-]+)?$/';
if (1 !== preg_match($pattern, $name)) {
throw new \InvalidArgumentException('The command name is must match: ' . $pattern);
}
if ($this->isInternalCommand($name)) {
throw new \InvalidArgumentException("The command name [$name] is not allowed. It is a built in command.");
}
}
/***************************************************************************
* some information for the application
***************************************************************************/
/**
* show the application help information
* @param bool $quit
* @param string $command
*/
public function showHelpInfo($quit = true, string $command = null)
{
// display help for a special command
if ($command) {
$this->input->setCommand($command);
$this->input->setSOpt('h', true);
$this->input->clearArgs();
$this->dispatch($command);
$this->stop();
}
$script = $this->input->getScript();
$sep = $this->delimiter;
$this->output->helpPanel([
'usage' => "$script {command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
'example' => [
"$script test (run a independent command)",
"$script home{$sep}index (run a command of the group)",
"$script help {command} (see a command help information)",
"$script home{$sep}index -h (see a command help of the group)",
]
], $quit);
}
/**
* show the application version information
* @param bool $quit
*/
public function showVersionInfo($quit = true)
{
$date = date('Y.m.d');
$name = $this->getMeta('name', 'Console Application');
$version = $this->getMeta('version', 'Unknown');
$publishAt = $this->getMeta('publishAt', 'Unknown');
$updateAt = $this->getMeta('updateAt', 'Unknown');
$phpVersion = PHP_VERSION;
$os = PHP_OS;
$this->output->aList([
"\n <info>{$name}</info>, Version <comment>$version</comment>\n",
'System Info' => "PHP version <info>$phpVersion</info>, on <info>$os</info> system",
'Application Info' => "Update at <info>$updateAt</info>, publish at <info>$publishAt</info>(current $date)",
], null, [
'leftChar' => '',
'sepChar' => ' : '
]);
$quit && $this->stop();
}
/**
* show the application command list information
* @param bool $quit
*/
public function showCommandList($quit = true)
{
$script = $this->getScriptName();
$hasGroup = $hasCommand = false;
$controllerArr = $commandArr = [];
$desPlaceholder = 'No description of the command';
// all console controllers
$controllerArr[] = PHP_EOL . '- <cyan>Group Commands</cyan>';
$controllers = $this->controllers;
ksort($controllers);
foreach ($controllers as $name => $controller) {
$hasGroup = true;
/** @var AbstractCommand $controller */
$controllerArr[$name] = $controller::getDescription() ?: $desPlaceholder;
}
if (!$hasGroup) {
$controllerArr[] = '... No register any group command(controller)';
}
// all independent commands
$commands = $this->commands;
$commandArr[] = PHP_EOL . '- <cyan>Independent Commands</cyan>';
ksort($commands);
foreach ($commands as $name => $command) {
$desc = $desPlaceholder;
$hasCommand = true;
/** @var AbstractCommand $command */
if (is_subclass_of($command, CommandInterface::class)) {
$desc = $command::getDescription() ?: $desPlaceholder;
} else if ($msg = $this->getCommandMessage($name)) {
$desc = $msg;
} else if (\is_string($command)) {
$desc = 'A handler : ' . $command;
} else if (\is_object($command)) {
$desc = 'A handler by ' . \get_class($command);
}
$commandArr[$name] = $desc;
}
if (!$hasCommand) {
$commandArr[] = '... No register any group command(controller)';
}
// built in commands
$internalCommands = static::$internalCommands;
ksort($internalCommands);
array_unshift($internalCommands, "\n- <cyan>Internal Commands</cyan>");
$this->output->mList([
//'There are all console controllers and independent commands.',
'Usage:' => "$script {command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
'Options:' => self::$internalOptions,
'Available Commands:' => array_merge($controllerArr, $commandArr, $internalCommands),
//'Independent Commands:' => $commandArr ?: '... No register any independent command',
// 'Internal Commands:' => $internalCommands,
]);
// $this->output->mList([
// //'There are all console controllers and independent commands.',
// 'Usage:' => "$script {command} [arg0 arg1=value1 arg2=value2 ...] [--opt -v -h ...]",
// 'Options:' => self::$internalOptions,
// 'Group Commands:' => $controllerArr ?: '... No register any group command(controller)',
// 'Independent Commands:' => $commandArr ?: '... No register any independent command',
// 'Internal Commands:' => $internalCommands,
// ]);
unset($controllerArr, $commandArr, $internalCommands);
$this->output->write("More command information, please use: <cyan>$script {command} -h</cyan>");
$quit && $this->stop();
}
/**
* @param string $name
* @param string $default
* @return string
*/
public function getCommandMessage($name, $default = null)
{
return $this->commandMessages[$name] ?? $default;
}
/**
* @param string $name The command name
* @param string $message
* @return string
*/
public function addCommandMessage($name, $message)
{
return $this->commandMessages[$name] = $message;
}
/**********************************************************
* getter/setter methods
**********************************************************/
/**
* @return array
*/
public function getControllerNames()
{
return array_keys($this->controllers);
}
/**
* @return array
*/
public function getCommandNames()
{
return array_keys($this->commands);
}
/**
* @param array $controllers
*/
public function setControllers(array $controllers)
{
foreach ($controllers as $name => $controller) {
if (\is_int($name)) {
$this->controller($controller);
} else {
$this->controller($name, $controller);
}
}
}
/**
* @return array
*/
public function getControllers(): array
{
return $this->controllers;
}
/**
* @param $name
* @return bool
*/
public function isController($name)
{
return isset($this->controllers[$name]);
}
/**
* @param array $commands
*/
public function setCommands(array $commands)
{
foreach ($commands as $name => $handler) {
if (\is_int($name)) {
$this->command($handler);
} else {
$this->command($name, $handler);
}
}
}
/**
* @return array
*/
public function getCommands(): array
{
return $this->commands;
}
/**
* @param $name
* @return bool
*/
public function isCommand($name)
{
return isset($this->commands[$name]);
}
/**
* @return array
*/
public static function getInternalCommands(): array
{
return static::$internalCommands;
}
/**
* @param $name
* @return bool
*/
public function isInternalCommand(string $name): bool
{
return isset(static::$internalCommands[$name]);
}
/**
* @return string
*/
public function getName()
{
return $this->meta['name'];
}
/**
* set meta info
* @param array $meta
*/
public function setMeta(array $meta)
{
if ($meta) {
$this->meta = array_merge($this->meta, $meta);
}
}
/**
* get meta info
* @param null|string $name
* @param null|string $default
* @return array|string
*/
public function getMeta($name = null, $default = null)
{
if (!$name) {
return $this->meta;
}
return $this->meta[$name] ?? $default;
}
/**
* is Debug
* @return boolean|int
*/
public function isDebug()
{
return $this->input->getOpt('debug', $this->meta['debug']);
}
/**
* is profile
* @return boolean
*/
public function isProfile()
{
return (bool)$this->input->getOpt('profile', $this->getMeta('profile'));
}
/**
* @return array
*/
public function getCommandMessages(): array
{
return $this->commandMessages;
}
/**
* @param array $commandMessages
*/
public function setCommandMessages(array $commandMessages)
{
$this->commandMessages = $commandMessages;
}
}