Table.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. * @property string $listPrefix List prefix. This property is write-only.
  41. * @property int $screenWidth Screen width. This property is write-only.
  42. *
  43. * @author Daniel Gomez Pan <pana_1990@hotmail.com>
  44. * @since 2.0.13
  45. */
  46. class Table extends Widget
  47. {
  48. const DEFAULT_CONSOLE_SCREEN_WIDTH = 120;
  49. const CONSOLE_SCROLLBAR_OFFSET = 3;
  50. const CHAR_TOP = 'top';
  51. const CHAR_TOP_MID = 'top-mid';
  52. const CHAR_TOP_LEFT = 'top-left';
  53. const CHAR_TOP_RIGHT = 'top-right';
  54. const CHAR_BOTTOM = 'bottom';
  55. const CHAR_BOTTOM_MID = 'bottom-mid';
  56. const CHAR_BOTTOM_LEFT = 'bottom-left';
  57. const CHAR_BOTTOM_RIGHT = 'bottom-right';
  58. const CHAR_LEFT = 'left';
  59. const CHAR_LEFT_MID = 'left-mid';
  60. const CHAR_MID = 'mid';
  61. const CHAR_MID_MID = 'mid-mid';
  62. const CHAR_RIGHT = 'right';
  63. const CHAR_RIGHT_MID = 'right-mid';
  64. const CHAR_MIDDLE = 'middle';
  65. /**
  66. * @var array table headers
  67. */
  68. private $_headers = [];
  69. /**
  70. * @var array table rows
  71. */
  72. private $_rows = [];
  73. /**
  74. * @var array table chars
  75. */
  76. private $_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. */
  96. private $_columnWidths = [];
  97. /**
  98. * @var int screen width
  99. */
  100. private $_screenWidth;
  101. /**
  102. * @var string list prefix
  103. */
  104. private $_listPrefix = '• ';
  105. /**
  106. * Set table headers.
  107. *
  108. * @param array $headers table headers
  109. * @return $this
  110. */
  111. public function setHeaders(array $headers)
  112. {
  113. $this->_headers = array_values($headers);
  114. return $this;
  115. }
  116. /**
  117. * Set table rows.
  118. *
  119. * @param array $rows table rows
  120. * @return $this
  121. */
  122. public function setRows(array $rows)
  123. {
  124. $this->_rows = array_map('array_values', $rows);
  125. return $this;
  126. }
  127. /**
  128. * Set table chars.
  129. *
  130. * @param array $chars table chars
  131. * @return $this
  132. */
  133. public function setChars(array $chars)
  134. {
  135. $this->_chars = $chars;
  136. return $this;
  137. }
  138. /**
  139. * Set screen width.
  140. *
  141. * @param int $width screen width
  142. * @return $this
  143. */
  144. public function setScreenWidth($width)
  145. {
  146. $this->_screenWidth = $width;
  147. return $this;
  148. }
  149. /**
  150. * Set list prefix.
  151. *
  152. * @param string $listPrefix list prefix
  153. * @return $this
  154. */
  155. public function setListPrefix($listPrefix)
  156. {
  157. $this->_listPrefix = $listPrefix;
  158. return $this;
  159. }
  160. /**
  161. * @return string the rendered table
  162. */
  163. public function run()
  164. {
  165. $this->calculateRowsSize();
  166. $buffer = $this->renderSeparator(
  167. $this->_chars[self::CHAR_TOP_LEFT],
  168. $this->_chars[self::CHAR_TOP_MID],
  169. $this->_chars[self::CHAR_TOP],
  170. $this->_chars[self::CHAR_TOP_RIGHT]
  171. );
  172. // Header
  173. $buffer .= $this->renderRow($this->_headers,
  174. $this->_chars[self::CHAR_LEFT],
  175. $this->_chars[self::CHAR_MIDDLE],
  176. $this->_chars[self::CHAR_RIGHT]
  177. );
  178. // Content
  179. foreach ($this->_rows as $row) {
  180. $buffer .= $this->renderSeparator(
  181. $this->_chars[self::CHAR_LEFT_MID],
  182. $this->_chars[self::CHAR_MID_MID],
  183. $this->_chars[self::CHAR_MID],
  184. $this->_chars[self::CHAR_RIGHT_MID]
  185. );
  186. $buffer .= $this->renderRow($row,
  187. $this->_chars[self::CHAR_LEFT],
  188. $this->_chars[self::CHAR_MIDDLE],
  189. $this->_chars[self::CHAR_RIGHT]);
  190. }
  191. $buffer .= $this->renderSeparator(
  192. $this->_chars[self::CHAR_BOTTOM_LEFT],
  193. $this->_chars[self::CHAR_BOTTOM_MID],
  194. $this->_chars[self::CHAR_BOTTOM],
  195. $this->_chars[self::CHAR_BOTTOM_RIGHT]
  196. );
  197. return $buffer;
  198. }
  199. /**
  200. * Renders a row of data into a string.
  201. *
  202. * @param array $row row of data
  203. * @param string $spanLeft character for left border
  204. * @param string $spanMiddle character for middle border
  205. * @param string $spanRight character for right border
  206. * @return string
  207. * @see \yii\console\widgets\Table::render()
  208. */
  209. protected function renderRow(array $row, $spanLeft, $spanMiddle, $spanRight)
  210. {
  211. $size = $this->_columnWidths;
  212. $buffer = '';
  213. $arrayPointer = [];
  214. $finalChunk = [];
  215. for ($i = 0, ($max = $this->calculateRowHeight($row)) ?: $max = 1; $i < $max; $i++) {
  216. $buffer .= $spanLeft . ' ';
  217. foreach ($size as $index => $cellSize) {
  218. $cell = isset($row[$index]) ? $row[$index] : null;
  219. $prefix = '';
  220. if ($index !== 0) {
  221. $buffer .= $spanMiddle . ' ';
  222. }
  223. if (is_array($cell)) {
  224. if (empty($finalChunk[$index])) {
  225. $finalChunk[$index] = '';
  226. $start = 0;
  227. $prefix = $this->_listPrefix;
  228. if (!isset($arrayPointer[$index])) {
  229. $arrayPointer[$index] = 0;
  230. }
  231. } else {
  232. $start = mb_strwidth($finalChunk[$index], Yii::$app->charset);
  233. }
  234. $chunk = mb_substr($cell[$arrayPointer[$index]], $start, $cellSize - 4, Yii::$app->charset);
  235. $finalChunk[$index] .= $chunk;
  236. if (isset($cell[$arrayPointer[$index] + 1]) && $finalChunk[$index] === $cell[$arrayPointer[$index]]) {
  237. $arrayPointer[$index]++;
  238. $finalChunk[$index] = '';
  239. }
  240. } else {
  241. $chunk = mb_substr($cell, ($cellSize * $i) - ($i * 2), $cellSize - 2, Yii::$app->charset);
  242. }
  243. $chunk = $prefix . $chunk;
  244. $repeat = $cellSize - mb_strwidth($chunk, Yii::$app->charset) - 1;
  245. $buffer .= $chunk;
  246. if ($repeat >= 0) {
  247. $buffer .= str_repeat(' ', $repeat);
  248. }
  249. }
  250. $buffer .= "$spanRight\n";
  251. }
  252. return $buffer;
  253. }
  254. /**
  255. * Renders separator.
  256. *
  257. * @param string $spanLeft character for left border
  258. * @param string $spanMid character for middle border
  259. * @param string $spanMidMid character for middle-middle border
  260. * @param string $spanRight character for right border
  261. * @return string the generated separator row
  262. * @see \yii\console\widgets\Table::render()
  263. */
  264. protected function renderSeparator($spanLeft, $spanMid, $spanMidMid, $spanRight)
  265. {
  266. $separator = $spanLeft;
  267. foreach ($this->_columnWidths as $index => $rowSize) {
  268. if ($index !== 0) {
  269. $separator .= $spanMid;
  270. }
  271. $separator .= str_repeat($spanMidMid, $rowSize);
  272. }
  273. $separator .= $spanRight . "\n";
  274. return $separator;
  275. }
  276. /**
  277. * Calculate the size of rows to draw anchor of columns in console.
  278. *
  279. * @see \yii\console\widgets\Table::render()
  280. */
  281. protected function calculateRowsSize()
  282. {
  283. $this->_columnWidths = $columns = [];
  284. $totalWidth = 0;
  285. $screenWidth = $this->getScreenWidth() - self::CONSOLE_SCROLLBAR_OFFSET;
  286. for ($i = 0, $count = count($this->_headers); $i < $count; $i++) {
  287. $columns[] = ArrayHelper::getColumn($this->_rows, $i);
  288. $columns[$i][] = $this->_headers[$i];
  289. }
  290. foreach ($columns as $column) {
  291. $columnWidth = max(array_map(function ($val) {
  292. if (is_array($val)) {
  293. $encodings = array_fill(0, count($val), Yii::$app->charset);
  294. return max(array_map('mb_strwidth', $val, $encodings)) + mb_strwidth($this->_listPrefix, Yii::$app->charset);
  295. }
  296. return mb_strwidth($val, Yii::$app->charset);
  297. }, $column)) + 2;
  298. $this->_columnWidths[] = $columnWidth;
  299. $totalWidth += $columnWidth;
  300. }
  301. $relativeWidth = $screenWidth / $totalWidth;
  302. if ($totalWidth > $screenWidth) {
  303. foreach ($this->_columnWidths as $j => $width) {
  304. $this->_columnWidths[$j] = (int) ($width * $relativeWidth);
  305. if ($j === count($this->_columnWidths)) {
  306. $this->_columnWidths = $totalWidth;
  307. }
  308. $totalWidth -= $this->_columnWidths[$j];
  309. }
  310. }
  311. }
  312. /**
  313. * Calculate the height of a row.
  314. *
  315. * @param array $row
  316. * @return int maximum row per cell
  317. * @see \yii\console\widgets\Table::render()
  318. */
  319. protected function calculateRowHeight($row)
  320. {
  321. $rowsPerCell = array_map(function ($size, $columnWidth) {
  322. if (is_array($columnWidth)) {
  323. $rows = 0;
  324. foreach ($columnWidth as $width) {
  325. $rows += ceil($width / ($size - 2));
  326. }
  327. return $rows;
  328. }
  329. return ceil($columnWidth / ($size - 2));
  330. }, $this->_columnWidths, array_map(function ($val) {
  331. if (is_array($val)) {
  332. $encodings = array_fill(0, count($val), Yii::$app->charset);
  333. return array_map('mb_strwidth', $val, $encodings);
  334. }
  335. return mb_strwidth($val, Yii::$app->charset);
  336. }, $row)
  337. );
  338. return max($rowsPerCell);
  339. }
  340. /**
  341. * Getting screen width.
  342. * If it is not able to determine screen width, default value `123` will be set.
  343. *
  344. * @return int screen width
  345. */
  346. protected function getScreenWidth()
  347. {
  348. if (!$this->_screenWidth) {
  349. $size = Console::getScreenSize();
  350. $this->_screenWidth = isset($size[0])
  351. ? $size[0]
  352. : self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET;
  353. }
  354. return $this->_screenWidth;
  355. }
  356. }