Table.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\console\widgets;
  8. use Yii;
  9. use yii\base\Widget;
  10. use yii\helpers\ArrayHelper;
  11. use yii\helpers\Console;
  12. /**
  13. * Table class displays a table in console.
  14. *
  15. * For example,
  16. *
  17. * ```php
  18. * $table = new Table();
  19. *
  20. * echo $table
  21. * ->setHeaders(['test1', 'test2', 'test3'])
  22. * ->setRows([
  23. * ['col1', 'col2', 'col3'],
  24. * ['col1', 'col2', ['col3-0', 'col3-1', 'col3-2']],
  25. * ])
  26. * ->run();
  27. * ```
  28. *
  29. * or
  30. *
  31. * ```php
  32. * echo Table::widget([
  33. * 'headers' => ['test1', 'test2', 'test3'],
  34. * 'rows' => [
  35. * ['col1', 'col2', 'col3'],
  36. * ['col1', 'col2', ['col3-0', 'col3-1', 'col3-2']],
  37. * ],
  38. * ]);
  39. *
  40. * @author Daniel Gomez Pan <pana_1990@hotmail.com>
  41. * @since 2.0.13
  42. */
  43. class Table extends Widget
  44. {
  45. const DEFAULT_CONSOLE_SCREEN_WIDTH = 120;
  46. const CONSOLE_SCROLLBAR_OFFSET = 3;
  47. const CHAR_TOP = 'top';
  48. const CHAR_TOP_MID = 'top-mid';
  49. const CHAR_TOP_LEFT = 'top-left';
  50. const CHAR_TOP_RIGHT = 'top-right';
  51. const CHAR_BOTTOM = 'bottom';
  52. const CHAR_BOTTOM_MID = 'bottom-mid';
  53. const CHAR_BOTTOM_LEFT = 'bottom-left';
  54. const CHAR_BOTTOM_RIGHT = 'bottom-right';
  55. const CHAR_LEFT = 'left';
  56. const CHAR_LEFT_MID = 'left-mid';
  57. const CHAR_MID = 'mid';
  58. const CHAR_MID_MID = 'mid-mid';
  59. const CHAR_RIGHT = 'right';
  60. const CHAR_RIGHT_MID = 'right-mid';
  61. const CHAR_MIDDLE = 'middle';
  62. /**
  63. * @var array table headers
  64. * @since 2.0.19
  65. */
  66. protected $headers = [];
  67. /**
  68. * @var array table rows
  69. * @since 2.0.19
  70. */
  71. protected $rows = [];
  72. /**
  73. * @var array table chars
  74. * @since 2.0.19
  75. */
  76. protected $chars = [
  77. self::CHAR_TOP => '═',
  78. self::CHAR_TOP_MID => '╤',
  79. self::CHAR_TOP_LEFT => '╔',
  80. self::CHAR_TOP_RIGHT => '╗',
  81. self::CHAR_BOTTOM => '═',
  82. self::CHAR_BOTTOM_MID => '╧',
  83. self::CHAR_BOTTOM_LEFT => '╚',
  84. self::CHAR_BOTTOM_RIGHT => '╝',
  85. self::CHAR_LEFT => '║',
  86. self::CHAR_LEFT_MID => '╟',
  87. self::CHAR_MID => '─',
  88. self::CHAR_MID_MID => '┼',
  89. self::CHAR_RIGHT => '║',
  90. self::CHAR_RIGHT_MID => '╢',
  91. self::CHAR_MIDDLE => '│',
  92. ];
  93. /**
  94. * @var array table column widths
  95. * @since 2.0.19
  96. */
  97. protected $columnWidths = [];
  98. /**
  99. * @var int screen width
  100. * @since 2.0.19
  101. */
  102. protected $screenWidth;
  103. /**
  104. * @var string list prefix
  105. * @since 2.0.19
  106. */
  107. protected $listPrefix = '• ';
  108. /**
  109. * Set table headers.
  110. *
  111. * @param array $headers table headers
  112. * @return $this
  113. */
  114. public function setHeaders(array $headers)
  115. {
  116. $this->headers = array_values($headers);
  117. return $this;
  118. }
  119. /**
  120. * Set table rows.
  121. *
  122. * @param array $rows table rows
  123. * @return $this
  124. */
  125. public function setRows(array $rows)
  126. {
  127. $this->rows = array_map('array_values', $rows);
  128. return $this;
  129. }
  130. /**
  131. * Set table chars.
  132. *
  133. * @param array $chars table chars
  134. * @return $this
  135. */
  136. public function setChars(array $chars)
  137. {
  138. $this->chars = $chars;
  139. return $this;
  140. }
  141. /**
  142. * Set screen width.
  143. *
  144. * @param int $width screen width
  145. * @return $this
  146. */
  147. public function setScreenWidth($width)
  148. {
  149. $this->screenWidth = $width;
  150. return $this;
  151. }
  152. /**
  153. * Set list prefix.
  154. *
  155. * @param string $listPrefix list prefix
  156. * @return $this
  157. */
  158. public function setListPrefix($listPrefix)
  159. {
  160. $this->listPrefix = $listPrefix;
  161. return $this;
  162. }
  163. /**
  164. * @return string the rendered table
  165. */
  166. public function run()
  167. {
  168. $this->calculateRowsSize();
  169. $headerCount = count($this->headers);
  170. $buffer = $this->renderSeparator(
  171. $this->chars[self::CHAR_TOP_LEFT],
  172. $this->chars[self::CHAR_TOP_MID],
  173. $this->chars[self::CHAR_TOP],
  174. $this->chars[self::CHAR_TOP_RIGHT]
  175. );
  176. // Header
  177. if ($headerCount > 0) {
  178. $buffer .= $this->renderRow($this->headers,
  179. $this->chars[self::CHAR_LEFT],
  180. $this->chars[self::CHAR_MIDDLE],
  181. $this->chars[self::CHAR_RIGHT]
  182. );
  183. }
  184. // Content
  185. foreach ($this->rows as $i => $row) {
  186. if ($i > 0 || $headerCount > 0) {
  187. $buffer .= $this->renderSeparator(
  188. $this->chars[self::CHAR_LEFT_MID],
  189. $this->chars[self::CHAR_MID_MID],
  190. $this->chars[self::CHAR_MID],
  191. $this->chars[self::CHAR_RIGHT_MID]
  192. );
  193. }
  194. $buffer .= $this->renderRow($row,
  195. $this->chars[self::CHAR_LEFT],
  196. $this->chars[self::CHAR_MIDDLE],
  197. $this->chars[self::CHAR_RIGHT]);
  198. }
  199. $buffer .= $this->renderSeparator(
  200. $this->chars[self::CHAR_BOTTOM_LEFT],
  201. $this->chars[self::CHAR_BOTTOM_MID],
  202. $this->chars[self::CHAR_BOTTOM],
  203. $this->chars[self::CHAR_BOTTOM_RIGHT]
  204. );
  205. return $buffer;
  206. }
  207. /**
  208. * Renders a row of data into a string.
  209. *
  210. * @param array $row row of data
  211. * @param string $spanLeft character for left border
  212. * @param string $spanMiddle character for middle border
  213. * @param string $spanRight character for right border
  214. * @return string
  215. * @see \yii\console\widgets\Table::render()
  216. */
  217. protected function renderRow(array $row, $spanLeft, $spanMiddle, $spanRight)
  218. {
  219. $size = $this->columnWidths;
  220. $buffer = '';
  221. $arrayPointer = [];
  222. $finalChunk = [];
  223. for ($i = 0, ($max = $this->calculateRowHeight($row)) ?: $max = 1; $i < $max; $i++) {
  224. $buffer .= $spanLeft . ' ';
  225. foreach ($size as $index => $cellSize) {
  226. $cell = isset($row[$index]) ? $row[$index] : null;
  227. $prefix = '';
  228. if ($index !== 0) {
  229. $buffer .= $spanMiddle . ' ';
  230. }
  231. if (is_array($cell)) {
  232. if (empty($finalChunk[$index])) {
  233. $finalChunk[$index] = '';
  234. $start = 0;
  235. $prefix = $this->listPrefix;
  236. if (!isset($arrayPointer[$index])) {
  237. $arrayPointer[$index] = 0;
  238. }
  239. } else {
  240. $start = mb_strwidth($finalChunk[$index], Yii::$app->charset);
  241. }
  242. $chunk = mb_substr($cell[$arrayPointer[$index]], $start, $cellSize - 4, Yii::$app->charset);
  243. $finalChunk[$index] .= $chunk;
  244. if (isset($cell[$arrayPointer[$index] + 1]) && $finalChunk[$index] === $cell[$arrayPointer[$index]]) {
  245. $arrayPointer[$index]++;
  246. $finalChunk[$index] = '';
  247. }
  248. } else {
  249. $chunk = mb_substr($cell, ($cellSize * $i) - ($i * 2), $cellSize - 2, Yii::$app->charset);
  250. }
  251. $chunk = $prefix . $chunk;
  252. $repeat = $cellSize - mb_strwidth($chunk, Yii::$app->charset) - 1;
  253. $buffer .= $chunk;
  254. if ($repeat >= 0) {
  255. $buffer .= str_repeat(' ', $repeat);
  256. }
  257. }
  258. $buffer .= "$spanRight\n";
  259. }
  260. return $buffer;
  261. }
  262. /**
  263. * Renders separator.
  264. *
  265. * @param string $spanLeft character for left border
  266. * @param string $spanMid character for middle border
  267. * @param string $spanMidMid character for middle-middle border
  268. * @param string $spanRight character for right border
  269. * @return string the generated separator row
  270. * @see \yii\console\widgets\Table::render()
  271. */
  272. protected function renderSeparator($spanLeft, $spanMid, $spanMidMid, $spanRight)
  273. {
  274. $separator = $spanLeft;
  275. foreach ($this->columnWidths as $index => $rowSize) {
  276. if ($index !== 0) {
  277. $separator .= $spanMid;
  278. }
  279. $separator .= str_repeat($spanMidMid, $rowSize);
  280. }
  281. $separator .= $spanRight . "\n";
  282. return $separator;
  283. }
  284. /**
  285. * Calculate the size of rows to draw anchor of columns in console.
  286. *
  287. * @see \yii\console\widgets\Table::render()
  288. */
  289. protected function calculateRowsSize()
  290. {
  291. $this->columnWidths = $columns = [];
  292. $totalWidth = 0;
  293. $screenWidth = $this->getScreenWidth() - self::CONSOLE_SCROLLBAR_OFFSET;
  294. $headerCount = count($this->headers);
  295. if (empty($this->rows)) {
  296. $rowColCount = 0;
  297. } else {
  298. $rowColCount = max(array_map('count', $this->rows));
  299. }
  300. $count = max($headerCount, $rowColCount);
  301. for ($i = 0; $i < $count; $i++) {
  302. $columns[] = ArrayHelper::getColumn($this->rows, $i);
  303. if ($i < $headerCount) {
  304. $columns[$i][] = $this->headers[$i];
  305. }
  306. }
  307. foreach ($columns as $column) {
  308. $columnWidth = max(array_map(function ($val) {
  309. if (is_array($val)) {
  310. $encodings = array_fill(0, count($val), Yii::$app->charset);
  311. return max(array_map('mb_strwidth', $val, $encodings)) + mb_strwidth($this->listPrefix, Yii::$app->charset);
  312. }
  313. return mb_strwidth($val, Yii::$app->charset);
  314. }, $column)) + 2;
  315. $this->columnWidths[] = $columnWidth;
  316. $totalWidth += $columnWidth;
  317. }
  318. $relativeWidth = $screenWidth / $totalWidth;
  319. if ($totalWidth > $screenWidth) {
  320. foreach ($this->columnWidths as $j => $width) {
  321. $this->columnWidths[$j] = (int) ($width * $relativeWidth);
  322. if ($j === count($this->columnWidths)) {
  323. $this->columnWidths = $totalWidth;
  324. }
  325. $totalWidth -= $this->columnWidths[$j];
  326. }
  327. }
  328. }
  329. /**
  330. * Calculate the height of a row.
  331. *
  332. * @param array $row
  333. * @return int maximum row per cell
  334. * @see \yii\console\widgets\Table::render()
  335. */
  336. protected function calculateRowHeight($row)
  337. {
  338. $rowsPerCell = array_map(function ($size, $columnWidth) {
  339. if (is_array($columnWidth)) {
  340. $rows = 0;
  341. foreach ($columnWidth as $width) {
  342. $rows += ceil($width / ($size - 2));
  343. }
  344. return $rows;
  345. }
  346. return ceil($columnWidth / ($size - 2));
  347. }, $this->columnWidths, array_map(function ($val) {
  348. if (is_array($val)) {
  349. $encodings = array_fill(0, count($val), Yii::$app->charset);
  350. return array_map('mb_strwidth', $val, $encodings);
  351. }
  352. return mb_strwidth($val, Yii::$app->charset);
  353. }, $row)
  354. );
  355. return max($rowsPerCell);
  356. }
  357. /**
  358. * Getting screen width.
  359. * If it is not able to determine screen width, default value `123` will be set.
  360. *
  361. * @return int screen width
  362. */
  363. protected function getScreenWidth()
  364. {
  365. if (!$this->screenWidth) {
  366. $size = Console::getScreenSize();
  367. $this->screenWidth = isset($size[0])
  368. ? $size[0]
  369. : self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET;
  370. }
  371. return $this->screenWidth;
  372. }
  373. }