forked from inhere/php-console
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHelper.php
More file actions
738 lines (633 loc) · 19.6 KB
/
Copy pathHelper.php
File metadata and controls
738 lines (633 loc) · 19.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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
<?php
/**
* Created by PhpStorm.
* User: Inhere
* Date: 16-4-1
* Time: 上午10:08
* Used:
* file: Color.php
*/
namespace Inhere\Console\Utils;
/**
* Class Helper
* @package Inhere\Console\Utils
*/
class Helper
{
/**
* Returns true if the console is running on windows
* @return boolean
*/
public static function isOnWindows(): bool
{
return DIRECTORY_SEPARATOR === '\\';
}
/**
* @return bool
*/
public static function isWindows(): bool
{
return stripos(PHP_OS, 'WIN') !== false;
}
/**
* @return bool
*/
public static function isUnix(): bool
{
$uNames = ['CYG', 'DAR', 'FRE', 'HP-', 'IRI', 'LIN', 'NET', 'OPE', 'SUN', 'UNI'];
return \in_array(strtoupper(substr(PHP_OS, 0, 3)), $uNames, true);
}
/**
* @return bool
*/
public static function isRoot(): bool
{
if (\function_exists('posix_getuid')) {
return posix_getuid() === 0;
}
return getmyuid() === 0;
}
/**
* Returns true if STDOUT supports colorization.
* This code has been copied and adapted from
* \Symfony\Component\Console\Output\OutputStream.
* @return boolean
*/
public static function isSupportColor()
{
if (DIRECTORY_SEPARATOR === '\\') {
return
'10.0.10586' === PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . '.' . PHP_WINDOWS_VERSION_BUILD ||
// 0 == strpos(PHP_WINDOWS_VERSION_MAJOR . '.' . PHP_WINDOWS_VERSION_MINOR . PHP_WINDOWS_VERSION_BUILD, '10.') ||
false !== getenv('ANSICON') ||
'ON' === getenv('ConEmuANSI') ||
'xterm' === getenv('TERM')// || 'cygwin' === getenv('TERM')
;
}
if (!\defined('STDOUT')) {
return false;
}
return self::isInteractive(STDOUT);
}
/**
* @return bool
*/
public function isSupport256Color()
{
return DIRECTORY_SEPARATOR === '/' && strpos(getenv('TERM'), '256color') !== false;
}
/**
* @return bool
*/
public static function isAnsiSupport()
{
return getenv('ANSICON') === true || getenv('ConEmuANSI') === 'ON';
}
/**
* Returns if the file descriptor is an interactive terminal or not.
* @param int|resource $fileDescriptor
* @return boolean
*/
public static function isInteractive($fileDescriptor)
{
return \function_exists('posix_isatty') && @posix_isatty($fileDescriptor);
}
/**
* @return string
*/
public static function getNullDevice()
{
if (self::isUnix()) {
return '/dev/null';
}
return 'NUL';
}
/**
* run a command in background
* @param string $cmd
*/
public static function execInBackground($cmd)
{
if (self::isWindows()) {
pclose(popen('start /B ' . $cmd, 'r'));
} else {
exec($cmd . ' > /dev/null &');
}
}
/**
* @param string $command
* @param null|string $logfile
* @param null|string $user
* @return mixed
* @throws \RuntimeException
*/
public static function exec($command, $logfile = null, $user = null)
{
// If should run as another user, we must be on *nix and must have sudo privileges.
$suDo = '';
if ($user && self::isUnix() && self::isRoot()) {
$suDo = "sudo -u $user";
}
// Start execution. Run in foreground (will block).
$logfile = $logfile ?: self::getNullDevice();
// Start execution. Run in foreground (will block).
exec("$suDo $command 1>> \"$logfile\" 2>&1", $dummy, $retVal);
if ($retVal !== 0) {
throw new \RuntimeException("command exited with status '$retVal'.");
}
return $dummy;
}
/**
* Method to execute a command in the sys
* Uses :
* 1. system
* 2. passthru
* 3. exec
* 4. shell_exec
* @param $command
* @param bool $returnStatus
* @return array|string
*/
public static function runCommand($command, $returnStatus = true)
{
$return_var = 1;
//system
if (\function_exists('system')) {
ob_start();
system($command, $return_var);
$output = ob_get_contents();
ob_end_clean();
// passthru
} elseif (\function_exists('passthru')) {
ob_start();
passthru($command, $return_var);
$output = ob_get_contents();
ob_end_clean();
//exec
} else if (\function_exists('exec')) {
exec($command, $output, $return_var);
$output = implode("\n", $output);
//shell_exec
} else if (\function_exists('shell_exec')) {
$output = shell_exec($command);
} else {
$output = 'Command execution not possible on this system';
$return_var = 0;
}
if ($returnStatus) {
return ['output' => trim($output), 'status' => $return_var];
}
return trim($output);
}
/**
* @return string
*/
public static function getTempDir()
{
// @codeCoverageIgnoreStart
if (\function_exists('sys_get_temp_dir')) {
$tmp = sys_get_temp_dir();
} elseif (!empty($_SERVER['TMP'])) {
$tmp = $_SERVER['TMP'];
} elseif (!empty($_SERVER['TEMP'])) {
$tmp = $_SERVER['TEMP'];
} elseif (!empty($_SERVER['TMPDIR'])) {
$tmp = $_SERVER['TMPDIR'];
} else {
$tmp = getcwd();
}
// @codeCoverageIgnoreEnd
return $tmp;
}
/**
* @param string $program
* @return int|string
*/
public static function getCpuUsage($program)
{
if (!$program) {
return -1;
}
$info = exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $3"}');
return $info;
}
/**
* @param $program
* @return int|string
*/
public static function getMemUsage($program)
{
if (!$program) {
return -1;
}
$info = exec('ps aux | grep ' . $program . ' | grep -v grep | grep -v su | awk {"print $4"}');
return $info;
}
/**
* 给对象设置属性值
* @param $object
* @param array $options
*/
public static function init($object, array $options)
{
foreach ($options as $property => $value) {
$object->$property = $value;
}
}
/**
* @param string $srcDir
* @param callable $filter
* @return \RecursiveIteratorIterator
* @throws \InvalidArgumentException
*/
public static function recursiveDirectoryIterator(string $srcDir, callable $filter)
{
if (!$srcDir || !file_exists($srcDir)) {
throw new \InvalidArgumentException('Please provide a exists source directory.');
}
$directory = new \RecursiveDirectoryIterator($srcDir);
$filterIterator = new \RecursiveCallbackFilterIterator($directory, $filter);
return new \RecursiveIteratorIterator($filterIterator);
}
/**
* wrap a style tag
* @param string $string
* @param string $tag
* @return string
*/
public static function wrapTag($string, $tag)
{
if (!$string) {
return '';
}
if (!$tag) {
return $string;
}
return "<$tag>$string</$tag>";
}
/**
* clear Ansi Code
* @param $string
* @return mixed
*/
public static function stripAnsiCode($string)
{
return preg_replace('/\033\[[\d;?]*\w/', '', $string);
}
/**
* @param $string
* @return int
*/
public static function strUtf8Len($string)
{
return mb_strlen($string, 'utf-8');
}
/**
* from Symfony
* @param $string
* @return int
*/
public static function strLen($string)
{
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return \strlen($string);
}
return mb_strwidth($string, $encoding);
}
/**
* to camel
* @param string $name
* @return mixed|string
*/
public static function camelCase($name)
{
$name = trim($name, '-_');
// convert 'first-second' to 'firstSecond'
if (strpos($name, '-')) {
$name = ucwords(str_replace('-', ' ', $name));
$name = str_replace(' ', '', lcfirst($name));
}
return $name;
}
/**
* findValueByNodes
* @param array $data
* @param array $nodes
* @param mixed $default
* @return mixed
*/
public static function findValueByNodes(array $data, array $nodes, $default = null)
{
$temp = $data;
foreach ($nodes as $name) {
if (isset($temp[$name])) {
$temp = $temp[$name];
} else {
$temp = $default;
break;
}
}
return $temp;
}
/**
* @param $string
* @param $width
* @return array
*/
public static function splitStringByWidth($string, $width)
{
// str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
// additionally, array_slice() is not enough as some character has doubled width.
// we need a function to split string not by character count but by string width
if (false === $encoding = mb_detect_encoding($string, null, true)) {
return str_split($string, $width);
}
$utf8String = mb_convert_encoding($string, 'utf8', $encoding);
$lines = array();
$line = '';
foreach (preg_split('//u', $utf8String) as $char) {
// test if $char could be appended to current line
if (mb_strwidth($line . $char, 'utf8') <= $width) {
$line .= $char;
continue;
}
// if not, push current line to array and make new line
$lines[] = str_pad($line, $width);
$line = $char;
}
if ('' !== $line) {
$lines[] = \count($lines) ? str_pad($line, $width) : $line;
}
mb_convert_variables($encoding, 'utf8', $lines);
return $lines;
}
/**
* @param $memory
* @return string
* ```
* Helper::formatMemory(memory_get_usage(true));
* ```
*/
public static function formatMemory($memory)
{
if ($memory >= 1024 * 1024 * 1024) {
return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024);
}
if ($memory >= 1024 * 1024) {
return sprintf('%.1f MiB', $memory / 1024 / 1024);
}
if ($memory >= 1024) {
return sprintf('%d KiB', $memory / 1024);
}
return sprintf('%d B', $memory);
}
/**
* formatTime
* @param int $secs
* @return string
*/
public static function formatTime($secs)
{
static $timeFormats = [
[0, '< 1 sec'],
[1, '1 sec'],
[2, 'secs', 1],
[60, '1 min'],
[120, 'mins', 60],
[3600, '1 hr'],
[7200, 'hrs', 3600],
[86400, '1 day'],
[172800, 'days', 86400],
];
foreach ($timeFormats as $index => $format) {
if ($secs >= $format[0]) {
if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0])
|| $index === \count($timeFormats) - 1
) {
if (2 === \count($format)) {
return $format[1];
}
return floor($secs / $format[2]) . ' ' . $format[1];
}
}
}
return date('Y-m-d H:i:s', $secs);
}
/**
* get key Max Width
*
* @param array $data
* [
* 'key1' => 'value1',
* 'key2-test' => 'value2',
* ]
* @param bool $expectInt
* @return int
*/
public static function getKeyMaxWidth(array $data, $expectInt = false)
{
$keyMaxWidth = 0;
foreach ($data as $key => $value) {
// key is not a integer
if (!$expectInt || !is_numeric($key)) {
$width = mb_strlen($key, 'UTF-8');
$keyMaxWidth = $width > $keyMaxWidth ? $width : $keyMaxWidth;
}
}
return $keyMaxWidth;
}
/**
* spliceArray
* @param array $data
* e.g [
* 'system' => 'Linux',
* 'version' => '4.4.5',
* ]
* @param array $opts
* @return string
*/
public static function spliceKeyValue(array $data, array $opts = [])
{
$text = '';
$opts = array_merge([
'leftChar' => '', // e.g ' ', ' * '
'sepChar' => ' ', // e.g ' | ' OUT: key | value
'keyStyle' => '', // e.g 'info','comment'
'valStyle' => '', // e.g 'info','comment'
'keyMinWidth' => 8,
'keyMaxWidth' => null, // if not set, will automatic calculation
'ucFirst' => true, // upper first char
], $opts);
if (!is_numeric($opts['keyMaxWidth'])) {
$opts['keyMaxWidth'] = self::getKeyMaxWidth($data);
}
// compare
if ((int)$opts['keyMinWidth'] > $opts['keyMaxWidth']) {
$opts['keyMaxWidth'] = $opts['keyMinWidth'];
}
$keyStyle = trim($opts['keyStyle']);
foreach ($data as $key => $value) {
$hasKey = !\is_int($key);
$text .= $opts['leftChar'];
if ($hasKey && $opts['keyMaxWidth']) {
$key = str_pad($key, $opts['keyMaxWidth'], ' ');
// $text .= ($keyStyle ? "<{$keyStyle}>$key</{$keyStyle}> " : $key) . $opts['sepChar'];
$text .= self::wrapTag($key, $keyStyle) . $opts['sepChar'];
}
// if value is array, translate array to string
if (\is_array($value)) {
$temp = '';
/** @var array $value */
foreach ($value as $k => $val) {
if (\is_bool($val)) {
$val = $val ? 'True' : 'False';
} else {
$val = is_scalar($val) ? (string)$val : \gettype($val);
}
$temp .= (!is_numeric($k) ? "$k: " : '') . "$val, ";
}
$value = rtrim($temp, ' ,');
} else if (\is_bool($value)) {
$value = $value ? 'True' : 'False';
} else {
$value = (string)$value;
}
$value = $hasKey && $opts['ucFirst'] ? ucfirst($value) : $value;
$text .= self::wrapTag($value, $opts['valStyle']) . "\n";
}
return $text;
}
// next: form yii2
/**
* Usage: list($width, $height) = ConsoleHelper::getScreenSize();
*
* @param boolean $refresh whether to force checking and not re-use cached size value.
* This is useful to detect changing window size while the application is running but may
* not get up to date values on every terminal.
* @return array|boolean An array of ($width, $height) or false when it was not able to determine size.
*/
public static function getScreenSize($refresh = false)
{
static $size;
if ($size !== null && !$refresh) {
return $size;
}
if (self::isOnWindows()) {
$output = [];
exec('mode con', $output);
if (isset($output[1]) && strpos($output[1], 'CON') !== false) {
return ($size = [
(int)preg_replace('~\D~', '', $output[3]),
(int)preg_replace('~\D~', '', $output[4])
]);
}
} else {
// try stty if available
$stty = [];
if (exec('stty -a 2>&1', $stty) && preg_match('/rows\s+(\d+);\s*columns\s+(\d+);/mi', implode(' ', $stty), $matches)) {
return ($size = [$matches[2], $matches[1]]);
}
// fallback to tput, which may not be updated on terminal resize
if (($width = (int)exec('tput cols 2>&1')) > 0 && ($height = (int)exec('tput lines 2>&1')) > 0) {
return ($size = [$width, $height]);
}
// fallback to ENV variables, which may not be updated on terminal resize
if (($width = (int)getenv('COLUMNS')) > 0 && ($height = (int)getenv('LINES')) > 0) {
return ($size = [$width, $height]);
}
}
return ($size = false);
}
/**
* Word wrap text with indentation to fit the screen size
*
* If screen size could not be detected, or the indentation is greater than the screen size, the text will not be wrapped.
*
* The first line will **not** be indented, so `Console::wrapText("Lorem ipsum dolor sit amet.", 4)` will result in the
* following output, given the screen width is 16 characters:
*
* ```
* Lorem ipsum
* dolor sit
* amet.
* ```
*
* @param string $text the text to be wrapped
* @param integer $indent number of spaces to use for indentation.
* @param integer $width
* @return string the wrapped text.
* @from yii2
*/
public static function wrapText($text, $indent = 0, $width = 0)
{
if (!$text) {
return $text;
}
if ((int)$width <= 0) {
$size = static::getScreenSize();
if ($size === false || $size[0] <= $indent) {
return $text;
}
$width = $size[0];
}
$pad = str_repeat(' ', $indent);
$lines = explode("\n", wordwrap($text, $width - $indent, "\n", true));
$first = true;
foreach ($lines as $i => $line) {
if ($first) {
$first = false;
continue;
}
$lines[$i] = $pad . $line;
}
return $pad . ' ' . implode("\n", $lines);
}
/**
* 获取资源消耗
* @param int $startTime
* @param int|float $startMem
* @param array $info
* @return array
*/
public static function runtime($startTime, $startMem, array $info = [])
{
$info['startTime'] = $startTime;
$info['endTime'] = microtime(true);
$info['endMemory'] = memory_get_usage(true);
// 计算运行时间
$info['runtime'] = number_format(($info['endTime'] - $startTime) * 1000, 3) . 'ms';
if ($startMem) {
$startMem = array_sum(explode(' ', $startMem));
$endMem = array_sum(explode(' ', $info['endMemory']));
$info['memory'] = number_format(($endMem - $startMem) / 1024, 3) . 'kb';
}
$peakMem = memory_get_peak_usage() / 1024 / 1024;
$info['peakMemory'] = number_format($peakMem, 3) . 'Mb';
return $info;
}
/**
* dump vars
* @param array ...$args
* @return string
*/
public static function dumpVars(...$args)
{
ob_start();
var_dump(...$args);
$string = ob_get_clean();
return preg_replace("/=>\n\s+/", '=> ', $string);
}
/**
* print vars
* @param array ...$args
* @return string
*/
public static function printVars(...$args)
{
$string = '';
foreach ($args as $arg) {
$string .= print_r($arg, 1) . PHP_EOL;
}
return preg_replace("/Array\n\s+\(/", 'Array (', $string);
}
}