Replace use of `StringUtil::split()` by `\mb_str_split()`
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / util / CLIUtil.class.php
1 <?php
2
3 namespace wcf\util;
4
5 use phpline\internal\AnsiUtil;
6 use wcf\system\CLIWCF;
7
8 /**
9 * Provide convenience methods for use on command line interface.
10 *
11 * @author Tim Duesterhus
12 * @copyright 2001-2019 WoltLab GmbH
13 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
14 * @package WoltLabSuite\Core\Util
15 */
16 final class CLIUtil
17 {
18 /**
19 * Generates a table.
20 *
21 * @param array $table
22 * @return string
23 */
24 public static function generateTable(array $table)
25 {
26 $columnSize = [];
27 foreach ($table as $row) {
28 $i = 0;
29 foreach ($row as $column) {
30 if (!isset($columnSize[$i])) {
31 $columnSize[$i] = 0;
32 }
33 $columnSize[$i] = \max($columnSize[$i], \mb_strlen(AnsiUtil::stripAnsi($column)));
34 $i++;
35 }
36 }
37
38 $result = '';
39 $result .= '+';
40 foreach ($columnSize as $column) {
41 $result .= \str_repeat('-', $column + 2) . '+';
42 }
43 $result .= \PHP_EOL;
44
45 foreach ($table as $row) {
46 $result .= "|";
47 $i = 0;
48 foreach ($row as $column) {
49 $paddedString = StringUtil::pad(
50 AnsiUtil::stripAnsi($column),
51 $columnSize[$i],
52 ' ',
53 (\is_numeric($column) ? \STR_PAD_LEFT : \STR_PAD_RIGHT)
54 );
55 $result .= ' ' . \str_replace(AnsiUtil::stripAnsi($column), $column, $paddedString) . ' |';
56 $i++;
57 }
58
59 $result .= \PHP_EOL . "+";
60 foreach ($columnSize as $column) {
61 $result .= \str_repeat('-', $column + 2) . '+';
62 }
63 $result .= \PHP_EOL;
64 }
65
66 return $result;
67 }
68
69 /**
70 * Generates a list.
71 *
72 * @param array $list
73 * @return string
74 */
75 public static function generateList(array $list)
76 {
77 $result = '';
78 foreach ($list as $row) {
79 $parts = \mb_str_split($row, CLIWCF::getTerminal()->getWidth() - 2);
80 $result .= '* ' . \implode(\PHP_EOL . ' ', $parts) . \PHP_EOL;
81 }
82
83 return $result;
84 }
85
86 /**
87 * Formats time.
88 *
89 * @param int $timestamp
90 * @return string
91 */
92 public static function formatTime($timestamp)
93 {
94 $dateTimeObject = DateUtil::getDateTimeByTimestamp($timestamp);
95 $date = DateUtil::format($dateTimeObject, DateUtil::DATE_FORMAT);
96 $time = DateUtil::format($dateTimeObject, DateUtil::TIME_FORMAT);
97
98 return \str_replace(
99 '%time%',
100 $time,
101 \str_replace('%date%', $date, CLIWCF::getLanguage()->get('wcf.date.dateTimeFormat'))
102 );
103 }
104
105 /**
106 * Formats dates.
107 *
108 * @param int $timestamp
109 * @return string
110 */
111 public static function formatDate($timestamp)
112 {
113 return DateUtil::format(DateUtil::getDateTimeByTimestamp($timestamp), DateUtil::DATE_FORMAT);
114 }
115
116 /**
117 * Forbid creation of CLIUtil objects.
118 */
119 private function __construct()
120 {
121 // does nothing
122 }
123 }