Table.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. $headerCount = count($this->_headers);
  167. $buffer = $this->renderSeparator(
  168. $this->_chars[self::CHAR_TOP_LEFT],
  169. $this->_chars[self::CHAR_TOP_MID],
  170. $this->_chars[self::CHAR_TOP],
  171. $this->_chars[self::CHAR_TOP_RIGHT]
  172. );
  173. // Header
  174. if ($headerCount > 0) {
  175. $buffer .= $this->renderRow($this->_headers,
  176. $this->_chars[self::CHAR_LEFT],
  177. $this->_chars[self::CHAR_MIDDLE],
  178. $this->_chars[self::CHAR_RIGHT]
  179. );
  180. }
  181. // Content
  182. foreach ($this->_rows as $i => $row) {
  183. if ($i > 0 || $headerCount > 0) {
  184. $buffer .= $this->renderSeparator(
  185. $this->_chars[self::CHAR_LEFT_MID],
  186. $this->_chars[self::CHAR_MID_MID],
  187. $this->_chars[self::CHAR_MID],
  188. $this->_chars[self::CHAR_RIGHT_MID]
  189. );
  190. }
  191. $buffer .= $this->renderRow($row,
  192. $this->_chars[self::CHAR_LEFT],
  193. $this->_chars[self::CHAR_MIDDLE],
  194. $this->_chars[self::CHAR_RIGHT]);
  195. }
  196. $buffer .= $this->renderSeparator(
  197. $this->_chars[self::CHAR_BOTTOM_LEFT],
  198. $this->_chars[self::CHAR_BOTTOM_MID],
  199. $this->_chars[self::CHAR_BOTTOM],
  200. $this->_chars[self::CHAR_BOTTOM_RIGHT]
  201. );
  202. return $buffer;
  203. }
  204. /**
  205. * Renders a row of data into a string.
  206. *
  207. * @param array $row row of data
  208. * @param string $spanLeft character for left border
  209. * @param string $spanMiddle character for middle border
  210. * @param string $spanRight character for right border
  211. * @return string
  212. * @see \yii\console\widgets\Table::render()
  213. */
  214. protected function renderRow(array $row, $spanLeft, $spanMiddle, $spanRight)
  215. {
  216. $size = $this->_columnWidths;
  217. $buffer = '';
  218. $arrayPointer = [];
  219. $finalChunk = [];
  220. for ($i = 0, ($max = $this->calculateRowHeight($row)) ?: $max = 1; $i < $max; $i++) {
  221. $buffer .= $spanLeft . ' ';
  222. foreach ($size as $index => $cellSize) {
  223. $cell = isset($row[$index]) ? $row[$index] : null;
  224. $prefix = '';
  225. if ($index !== 0) {
  226. $buffer .= $spanMiddle . ' ';
  227. }
  228. if (is_array($cell)) {
  229. if (empty($finalChunk[$index])) {
  230. $finalChunk[$index] = '';
  231. $start = 0;
  232. $prefix = $this->_listPrefix;
  233. if (!isset($arrayPointer[$index])) {
  234. $arrayPointer[$index] = 0;
  235. }
  236. } else {
  237. $start = mb_strwidth($finalChunk[$index], Yii::$app->charset);
  238. }
  239. $chunk = mb_substr($cell[$arrayPointer[$index]], $start, $cellSize - 4, Yii::$app->charset);
  240. $finalChunk[$index] .= $chunk;
  241. if (isset($cell[$arrayPointer[$index] + 1]) && $finalChunk[$index] === $cell[$arrayPointer[$index]]) {
  242. $arrayPointer[$index]++;
  243. $finalChunk[$index] = '';
  244. }
  245. } else {
  246. $chunk = mb_substr($cell, ($cellSize * $i) - ($i * 2), $cellSize - 2, Yii::$app->charset);
  247. }
  248. $chunk = $prefix . $chunk;
  249. $repeat = $cellSize - mb_strwidth($chunk, Yii::$app->charset) - 1;
  250. $buffer .= $chunk;
  251. if ($repeat >= 0) {
  252. $buffer .= str_repeat(' ', $repeat);
  253. }
  254. }
  255. $buffer .= "$spanRight\n";
  256. }
  257. return $buffer;
  258. }
  259. /**
  260. * Renders separator.
  261. *
  262. * @param string $spanLeft character for left border
  263. * @param string $spanMid character for middle border
  264. * @param string $spanMidMid character for middle-middle border
  265. * @param string $spanRight character for right border
  266. * @return string the generated separator row
  267. * @see \yii\console\widgets\Table::render()
  268. */
  269. protected function renderSeparator($spanLeft, $spanMid, $spanMidMid, $spanRight)
  270. {
  271. $separator = $spanLeft;
  272. foreach ($this->_columnWidths as $index => $rowSize) {
  273. if ($index !== 0) {
  274. $separator .= $spanMid;
  275. }
  276. $separator .= str_repeat($spanMidMid, $rowSize);
  277. }
  278. $separator .= $spanRight . "\n";
  279. return $separator;
  280. }
  281. /**
  282. * Calculate the size of rows to draw anchor of columns in console.
  283. *
  284. * @see \yii\console\widgets\Table::render()
  285. */
  286. protected function calculateRowsSize()
  287. {
  288. $this->_columnWidths = $columns = [];
  289. $totalWidth = 0;
  290. $screenWidth = $this->getScreenWidth() - self::CONSOLE_SCROLLBAR_OFFSET;
  291. $headerCount = count($this->_headers);
  292. if (empty($this->_rows)) {
  293. $rowColCount = 0;
  294. } else {
  295. $rowColCount = max(array_map('count', $this->_rows));
  296. }
  297. $count = max($headerCount, $rowColCount);
  298. for ($i = 0; $i < $count; $i++) {
  299. $columns[] = ArrayHelper::getColumn($this->_rows, $i);
  300. if ($i < $headerCount) {
  301. $columns[$i][] = $this->_headers[$i];
  302. }
  303. }
  304. foreach ($columns as $column) {
  305. $columnWidth = max(array_map(function ($val) {
  306. if (is_array($val)) {
  307. $encodings = array_fill(0, count($val), Yii::$app->charset);
  308. return max(array_map('mb_strwidth', $val, $encodings)) + mb_strwidth($this->_listPrefix, Yii::$app->charset);
  309. }
  310. return mb_strwidth($val, Yii::$app->charset);
  311. }, $column)) + 2;
  312. $this->_columnWidths[] = $columnWidth;
  313. $totalWidth += $columnWidth;
  314. }
  315. $relativeWidth = $screenWidth / $totalWidth;
  316. if ($totalWidth > $screenWidth) {
  317. foreach ($this->_columnWidths as $j => $width) {
  318. $this->_columnWidths[$j] = (int) ($width * $relativeWidth);
  319. if ($j === count($this->_columnWidths)) {
  320. $this->_columnWidths = $totalWidth;
  321. }
  322. $totalWidth -= $this->_columnWidths[$j];
  323. }
  324. }
  325. }
  326. /**
  327. * Calculate the height of a row.
  328. *
  329. * @param array $row
  330. * @return int maximum row per cell
  331. * @see \yii\console\widgets\Table::render()
  332. */
  333. protected function calculateRowHeight($row)
  334. {
  335. $rowsPerCell = array_map(function ($size, $columnWidth) {
  336. if (is_array($columnWidth)) {
  337. $rows = 0;
  338. foreach ($columnWidth as $width) {
  339. $rows += ceil($width / ($size - 2));
  340. }
  341. return $rows;
  342. }
  343. return ceil($columnWidth / ($size - 2));
  344. }, $this->_columnWidths, array_map(function ($val) {
  345. if (is_array($val)) {
  346. $encodings = array_fill(0, count($val), Yii::$app->charset);
  347. return array_map('mb_strwidth', $val, $encodings);
  348. }
  349. return mb_strwidth($val, Yii::$app->charset);
  350. }, $row)
  351. );
  352. return max($rowsPerCell);
  353. }
  354. /**
  355. * Getting screen width.
  356. * If it is not able to determine screen width, default value `123` will be set.
  357. *
  358. * @return int screen width
  359. */
  360. protected function getScreenWidth()
  361. {
  362. if (!$this->_screenWidth) {
  363. $size = Console::getScreenSize();
  364. $this->_screenWidth = isset($size[0])
  365. ? $size[0]
  366. : self::DEFAULT_CONSOLE_SCREEN_WIDTH + self::CONSOLE_SCROLLBAR_OFFSET;
  367. }
  368. return $this->_screenWidth;
  369. }
  370. }