Skip to content

Commit fa42324

Browse files
committed
update, some bug fixed
1 parent fb51560 commit fa42324

File tree

11 files changed

+176
-49
lines changed

11 files changed

+176
-49
lines changed

examples/HomeController.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,10 @@ public function indexCommand()
4444
protected function colorConfigure()
4545
{
4646
$this->createDefinition()
47-
->setDescription('command description')
48-
->addArgument('name', Input::ARG_REQUIRED)
49-
->addOption('yes', 'y', Input::OPT_BOOLEAN);
47+
->setDescription('the color command description')
48+
->addArgument('name', Input::ARG_REQUIRED, 'description for the argument [name]')
49+
->addOption('yes', 'y', Input::OPT_BOOLEAN, 'description for the option [yes]')
50+
->addOption('opt1', null, Input::OPT_REQUIRED, 'description for the option [opt1]');
5051
}
5152

5253
/**
@@ -60,7 +61,7 @@ public function colorCommand()
6061

6162
return 0;
6263
}
63-
64+
$this->output->dumpVars($this->input->getArgs(), $this->input->getBoolOpt('y'));
6465
$this->write('color text output:');
6566
$styles = $this->output->getStyle()->getStyleNames();
6667

@@ -253,7 +254,7 @@ public function envCommand()
253254

254255
Interact::panel($info);
255256

256-
echo Helper::printR($_SERVER);
257+
echo Helper::printVars($_SERVER);
257258
}
258259

259260
/**

examples/app

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,15 @@
11
#!/usr/bin/env php
22
<?php
3-
// define STDIN, STDOUT and STDERR if the PHP SAPI did not define them (e.g. creating console application in web env)
4-
// http://php.net/manual/en/features.commandline.io-streams.php
5-
defined('STDIN') or define('STDIN', fopen('php://stdin', 'rb'));
6-
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'wb'));
7-
defined('STDERR') or define('STDERR', fopen('php://stderr', 'wb'));
83

94
define('PROJECT_PATH', dirname(__DIR__));
105

116
require __DIR__ . '/s-autoload.php';
127

138
// create app instance
14-
$app = new \inhere\console\App();
9+
$app = new \inhere\console\App([
10+
'debug' => true,
11+
'rootPath' => PROJECT_PATH,
12+
]);
1513

1614
// require dirname(__DIR__) . '/boot/cli-services.php';
1715

examples/baks/color.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,59 @@
66
// $text = sprintf("\033[%sm%s\033[%sm\n", implode(';', $setCodes), $text, implode(';', $unsetCodes));
77
// var_dump(chr(27));
88
// echo $text;
9+
system("echo -e '\033[32;40;1;4mfoo\033[39;49;22;24m'");
10+
system("printf '\033[32;40;1;4mfoo\033[39;49;22;24m'");
911
fwrite(STDOUT, "\033[32;40;1;4mfoo\033[39;49;22;24m");
1012
fflush(STDOUT);
13+
14+
function execInBackground($cmd)
15+
{
16+
if (substr(php_uname(), 0, 7) == "Windows") {
17+
pclose(popen("start /B " . $cmd, "r"));
18+
} else {
19+
exec($cmd . " > /dev/null &");
20+
}
21+
}
22+
function GetProgCpuUsage($program)
23+
{
24+
if (!$program) {
25+
return -1;
26+
}
27+
28+
$c_pid = exec("ps aux | grep " . $program . " | grep -v grep | grep -v su | awk {'print $3'}");
29+
return $c_pid;
30+
}
31+
32+
function GetProgMemUsage($program)
33+
{
34+
if (!$program) {
35+
return -1;
36+
}
37+
38+
$c_pid = exec("ps aux | grep " . $program . " | grep -v grep | grep -v su | awk {'print $4'}");
39+
return $c_pid;
40+
}
41+
42+
// If you want to download files from a linux server with a filesize bigger than 2GB you can use the following
43+
function serveFile($file, $as)
44+
{
45+
header('Expires: Mon, 1 Apr 1974 05:00:00 GMT');
46+
header('Pragma: no-cache');
47+
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
48+
header('Content-Description: File Download');
49+
header('Content-Type: application/octet-stream');
50+
header('Content-Length: ' . trim(`stat -c%s "$file"`));
51+
header('Content-Disposition: attachment; filename="' . $as . '"');
52+
header('Content-Transfer-Encoding: binary');
53+
//@readfile( $file );
54+
55+
flush();
56+
$fp = popen("tail -c " . trim(`stat -c%s "$file"`) . " " . $file . ' 2>&1', "r");
57+
while (!feof($fp)) {
58+
// send the current file part to the browser
59+
print fread($fp, 1024);
60+
// flush the content to the browser
61+
flush();
62+
}
63+
fclose($fp);
64+
}

src/AbstractApp.php

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use inhere\console\io\Output;
1313
use inhere\console\traits\InputOutputTrait;
1414
use inhere\console\traits\SimpleEventStaticTrait;
15+
use inhere\console\utils\Helper;
1516

1617
/**
1718
* Class AbstractApp
@@ -36,12 +37,14 @@ abstract class AbstractApp
3637
* app config
3738
* @var array
3839
*/
39-
protected $config = [
40+
private $config = [
4041
'env' => 'pdt', // dev test pdt
41-
'debug' => true,
42+
'debug' => false,
4243
'name' => 'My Console',
4344
'version' => '0.5.1',
4445
'publishAt' => '2017.03.24',
46+
'rootPath' => '',
47+
'hideRootPath' => true,
4548
'charset' => 'UTF-8',
4649
'timeZone' => 'Asia/Shanghai',
4750
];
@@ -70,6 +73,11 @@ abstract class AbstractApp
7073
*/
7174
private $commandName;
7275

76+
/**
77+
* @var bool
78+
*/
79+
private $hideRootPath = true;
80+
7381
/**
7482
* App constructor.
7583
* @param array $config
@@ -78,13 +86,26 @@ abstract class AbstractApp
7886
*/
7987
public function __construct(array $config = [], Input $input = null, Output $output = null)
8088
{
89+
$this->runtimeCheck();
90+
$this->setConfig($config);
91+
8192
$this->input = $input ?: new Input();
8293
$this->output = $output ?: new Output();
8394

84-
$this->setConfig($config);
8595
$this->init();
8696
}
8797

98+
protected function runtimeCheck()
99+
{
100+
// check env
101+
if (!in_array(PHP_SAPI, ['cli', 'cli-server'], true)) {
102+
header('HTTP/1.1 403 Forbidden');
103+
exit(" 403 Forbidden \n\n"
104+
. " current environment is CLI. \n"
105+
. " :( Sorry! Run this script is only allowed in the terminal environment!\n,You are not allowed to access this file.\n");
106+
}
107+
}
108+
88109
protected function init()
89110
{
90111
$this->commandName = $this->input->getCommand();
@@ -267,15 +288,19 @@ protected function dispatchExHandler($e)
267288
// open debug, throw exception
268289
if ($this->isDebug()) {
269290
$message = sprintf(
270-
"<bold>Exception(%d)</bold>: <red>%s</red>\nCalled At %s, Line: <cyan>%d</cyan>\nCatch the exception by: %s\nCode Trace:\n%s\n",
271-
$e->getCode(),
291+
"<red>Exception</red>: %s\nCalled At %s, Line: <cyan>%d</cyan>\nCatch the exception by: %s\nCode Trace:\n%s\n",
292+
// $e->getCode(),
272293
$e->getMessage(),
273294
$e->getFile(),
274295
$e->getLine(),
275296
get_class($e),
276297
$e->getTraceAsString()
277298
);
278299

300+
if ($this->config('hideRootPath') && $rootPath = $this->config('rootPath')) {
301+
$message = str_replace($rootPath, '{ROOT}', $message);
302+
}
303+
279304
$this->output->write($message, false);
280305
} else {
281306
// simple output
@@ -348,13 +373,14 @@ public function showHelpInfo($quit = true)
348373
public function showVersionInfo($quit = true)
349374
{
350375
$date = date('Y-m-d');
376+
$name = $this->config('name', 'Console Application');
351377
$version = $this->config('version', 'Unknown');
352-
$publishAt = $this->config['publishAt'];
378+
$publishAt = $this->config('publishAt', 'Unknown');
353379
$phpVersion = PHP_VERSION;
354380
$os = PHP_OS;
355381

356382
$this->output->aList([
357-
"Console Application <info>{$this->config['name']}</info> Version <comment>$version</comment>(publish at $publishAt)",
383+
"Console Application <info>{$name}</info> Version <comment>$version</comment>(publish at $publishAt)",
358384
'System' => "PHP version <info>$phpVersion</info>, on OS <info>$os</info>, current Date $date",
359385
], null, [
360386
'leftChar' => ''
@@ -510,11 +536,9 @@ public function config($name, $default = null)
510536

511537
// allow get $config['top']['sub'] by 'top.sub'
512538
if (strpos($name, '.') > 1) {
513-
list($topKey, $subKey) = explode('.', $name, 2);
539+
$nodes = array_filter(explode('.', $name));
514540

515-
if (isset($this->config[$topKey], $this->config[$topKey][$subKey])) {
516-
return $this->config[$topKey][$subKey];
517-
}
541+
return Helper::findValueByNodes($this->config, $nodes, $default);
518542
}
519543

520544
return $this->config[$name] ?? $default;

src/AbstractCommand.php

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ abstract class AbstractCommand
4444
* Allow display message tags in the command annotation
4545
* @var array
4646
*/
47-
protected static $allowTags = [
47+
protected static $annotationTags = [
4848
// tag name => multi line align
4949
'description' => false,
5050
'usage' => false,
@@ -93,7 +93,7 @@ protected function configure()
9393
* validate input arguments and options
9494
* @return bool
9595
*/
96-
public function validate()
96+
public function validateInput()
9797
{
9898
if (!$definition = $this->definition) {
9999
return true;
@@ -114,10 +114,9 @@ public function validate()
114114
}
115115

116116
$defArgs = $definition->getArguments();
117-
118-
$missingArgs = array_filter(array_keys($defArgs), function ($name) use ($definition, $givenArgs) {
119-
return !array_key_exists($name, $givenArgs) && $definition->argumentIsRequired($name);
120-
});
117+
$missingArgs = array_filter(array_keys($defArgs), function ($name, $key) use ($definition, $givenArgs) {
118+
return !array_key_exists($key, $givenArgs) && $definition->argumentIsRequired($name);
119+
}, ARRAY_FILTER_USE_BOTH);
121120

122121
if (count($missingArgs) > 0) {
123122
throw new \RuntimeException(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArgs)));
@@ -173,7 +172,8 @@ protected function beforeRun()
173172
}
174173
}
175174

176-
$this->validate();
175+
// do validate input arg and opt
176+
$this->validateInput();
177177
}
178178

179179
/**
@@ -240,9 +240,9 @@ protected function showHelpByMethodAnnotation($method, $action = null)
240240
continue;
241241
}
242242

243-
if (isset(self::$allowTags[$tag])) {
243+
if (isset(self::$annotationTags[$tag])) {
244244
// need multi align
245-
if (self::$allowTags[$tag]) {
245+
if (self::$annotationTags[$tag]) {
246246
$lines = array_map(function ($line) {
247247
return trim($line);
248248
}, explode("\n", $msg));
@@ -304,18 +304,18 @@ public static function setDescription(string $description)
304304
/**
305305
* @return array
306306
*/
307-
public static function getAllowTags(): array
307+
public static function getAnnotationTags(): array
308308
{
309-
return self::$allowTags;
309+
return self::$annotationTags;
310310
}
311311

312312
/**
313-
* @param array $allowTags
313+
* @param array $annotationTags
314314
* @param bool $replace
315315
*/
316-
public static function setAllowTags(array $allowTags, $replace = false)
316+
public static function setAnnotationTags(array $annotationTags, $replace = false)
317317
{
318-
self::$allowTags = $replace ? $allowTags : array_merge(self::$allowTags, $allowTags);
318+
self::$annotationTags = $replace ? $annotationTags : array_merge(self::$annotationTags, $annotationTags);
319319
}
320320

321321
/**

src/Command.php

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ abstract class Command extends AbstractCommand
2323
*/
2424
public function run()
2525
{
26-
// load input definition
27-
// $this->configure();
26+
// load input definition configure
27+
$this->configure();
2828

2929
if ($this->input->sameOpt(['h','help'])) {
3030
return $this->showHelp();
@@ -40,7 +40,6 @@ public function run()
4040
$this->afterRun();
4141

4242
App::fire(App::ON_AFTER_EXEC, [$this]);
43-
4443
} catch (\Throwable $e) {
4544
App::fire(App::ON_EXEC_ERROR, [$e, $this]);
4645
$this->handleRuntimeException($e);
@@ -62,17 +61,21 @@ abstract protected function execute($input, $output);
6261
*/
6362
protected function configure()
6463
{
65-
$this
66-
->createDefinition()
67-
->addArgument('test')
68-
->addOption('test');
64+
// $this
65+
// ->createDefinition()
66+
// ->addArgument('test')
67+
// ->addOption('test');
6968
}
7069

7170
/**
7271
* @return int
7372
*/
74-
public function showHelp()
73+
protected function showHelp()
7574
{
75+
if ($def = $this->getDefinition()) {
76+
return $this->write($def->getSynopsis());
77+
}
78+
7679
return $this->showHelpByMethodAnnotation('execute');
7780
}
7881
}

src/Controller.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ protected function configure()
5858
*/
5959
public function run()
6060
{
61+
$this->configure();
6162
$action = $this->action;
62-
// $this->configure();
6363

6464
if ($action && $this->input->sameOpt(['h','help'])) {
6565
return $this->helpCommand();
@@ -124,7 +124,7 @@ final public function helpCommand()
124124

125125
$action = Helper::transName($action);
126126

127-
if ($def = $this->getDefinition()) {
127+
if ($def = $this->getDefinition()) { var_dump($def);
128128
return $this->write($def->getSynopsis());
129129
}
130130

0 commit comments

Comments
 (0)