Drupal investigation

Table.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Helper;
  11. use Symfony\Component\Console\Output\OutputInterface;
  12. use Symfony\Component\Console\Exception\InvalidArgumentException;
  13. /**
  14. * Provides helpers to display a table.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Саша Стаменковић <umpirsky@gmail.com>
  18. * @author Abdellatif Ait boudad <a.aitboudad@gmail.com>
  19. * @author Max Grigorian <maxakawizard@gmail.com>
  20. */
  21. class Table
  22. {
  23. /**
  24. * Table headers.
  25. *
  26. * @var array
  27. */
  28. private $headers = array();
  29. /**
  30. * Table rows.
  31. *
  32. * @var array
  33. */
  34. private $rows = array();
  35. /**
  36. * Column widths cache.
  37. *
  38. * @var array
  39. */
  40. private $columnWidths = array();
  41. /**
  42. * Number of columns cache.
  43. *
  44. * @var array
  45. */
  46. private $numberOfColumns;
  47. /**
  48. * @var OutputInterface
  49. */
  50. private $output;
  51. /**
  52. * @var TableStyle
  53. */
  54. private $style;
  55. /**
  56. * @var array
  57. */
  58. private $columnStyles = array();
  59. private static $styles;
  60. public function __construct(OutputInterface $output)
  61. {
  62. $this->output = $output;
  63. if (!self::$styles) {
  64. self::$styles = self::initStyles();
  65. }
  66. $this->setStyle('default');
  67. }
  68. /**
  69. * Sets a style definition.
  70. *
  71. * @param string $name The style name
  72. * @param TableStyle $style A TableStyle instance
  73. */
  74. public static function setStyleDefinition($name, TableStyle $style)
  75. {
  76. if (!self::$styles) {
  77. self::$styles = self::initStyles();
  78. }
  79. self::$styles[$name] = $style;
  80. }
  81. /**
  82. * Gets a style definition by name.
  83. *
  84. * @param string $name The style name
  85. *
  86. * @return TableStyle
  87. */
  88. public static function getStyleDefinition($name)
  89. {
  90. if (!self::$styles) {
  91. self::$styles = self::initStyles();
  92. }
  93. if (isset(self::$styles[$name])) {
  94. return self::$styles[$name];
  95. }
  96. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  97. }
  98. /**
  99. * Sets table style.
  100. *
  101. * @param TableStyle|string $name The style name or a TableStyle instance
  102. *
  103. * @return $this
  104. */
  105. public function setStyle($name)
  106. {
  107. $this->style = $this->resolveStyle($name);
  108. return $this;
  109. }
  110. /**
  111. * Gets the current table style.
  112. *
  113. * @return TableStyle
  114. */
  115. public function getStyle()
  116. {
  117. return $this->style;
  118. }
  119. /**
  120. * Sets table column style.
  121. *
  122. * @param int $columnIndex Column index
  123. * @param TableStyle|string $name The style name or a TableStyle instance
  124. *
  125. * @return $this
  126. */
  127. public function setColumnStyle($columnIndex, $name)
  128. {
  129. $columnIndex = intval($columnIndex);
  130. $this->columnStyles[$columnIndex] = $this->resolveStyle($name);
  131. return $this;
  132. }
  133. /**
  134. * Gets the current style for a column.
  135. *
  136. * If style was not set, it returns the global table style.
  137. *
  138. * @param int $columnIndex Column index
  139. *
  140. * @return TableStyle
  141. */
  142. public function getColumnStyle($columnIndex)
  143. {
  144. if (isset($this->columnStyles[$columnIndex])) {
  145. return $this->columnStyles[$columnIndex];
  146. }
  147. return $this->getStyle();
  148. }
  149. public function setHeaders(array $headers)
  150. {
  151. $headers = array_values($headers);
  152. if (!empty($headers) && !is_array($headers[0])) {
  153. $headers = array($headers);
  154. }
  155. $this->headers = $headers;
  156. return $this;
  157. }
  158. public function setRows(array $rows)
  159. {
  160. $this->rows = array();
  161. return $this->addRows($rows);
  162. }
  163. public function addRows(array $rows)
  164. {
  165. foreach ($rows as $row) {
  166. $this->addRow($row);
  167. }
  168. return $this;
  169. }
  170. public function addRow($row)
  171. {
  172. if ($row instanceof TableSeparator) {
  173. $this->rows[] = $row;
  174. return $this;
  175. }
  176. if (!is_array($row)) {
  177. throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
  178. }
  179. $this->rows[] = array_values($row);
  180. return $this;
  181. }
  182. public function setRow($column, array $row)
  183. {
  184. $this->rows[$column] = $row;
  185. return $this;
  186. }
  187. /**
  188. * Renders table to output.
  189. *
  190. * Example:
  191. * +---------------+-----------------------+------------------+
  192. * | ISBN | Title | Author |
  193. * +---------------+-----------------------+------------------+
  194. * | 99921-58-10-7 | Divine Comedy | Dante Alighieri |
  195. * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  196. * | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien |
  197. * +---------------+-----------------------+------------------+
  198. */
  199. public function render()
  200. {
  201. $this->calculateNumberOfColumns();
  202. $rows = $this->buildTableRows($this->rows);
  203. $headers = $this->buildTableRows($this->headers);
  204. $this->calculateColumnsWidth(array_merge($headers, $rows));
  205. $this->renderRowSeparator();
  206. if (!empty($headers)) {
  207. foreach ($headers as $header) {
  208. $this->renderRow($header, $this->style->getCellHeaderFormat());
  209. $this->renderRowSeparator();
  210. }
  211. }
  212. foreach ($rows as $row) {
  213. if ($row instanceof TableSeparator) {
  214. $this->renderRowSeparator();
  215. } else {
  216. $this->renderRow($row, $this->style->getCellRowFormat());
  217. }
  218. }
  219. if (!empty($rows)) {
  220. $this->renderRowSeparator();
  221. }
  222. $this->cleanup();
  223. }
  224. /**
  225. * Renders horizontal header separator.
  226. *
  227. * Example: +-----+-----------+-------+
  228. */
  229. private function renderRowSeparator()
  230. {
  231. if (0 === $count = $this->numberOfColumns) {
  232. return;
  233. }
  234. if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
  235. return;
  236. }
  237. $markup = $this->style->getCrossingChar();
  238. for ($column = 0; $column < $count; ++$column) {
  239. $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->columnWidths[$column]).$this->style->getCrossingChar();
  240. }
  241. $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
  242. }
  243. /**
  244. * Renders vertical column separator.
  245. */
  246. private function renderColumnSeparator()
  247. {
  248. return sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar());
  249. }
  250. /**
  251. * Renders table row.
  252. *
  253. * Example: | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
  254. *
  255. * @param array $row
  256. * @param string $cellFormat
  257. */
  258. private function renderRow(array $row, $cellFormat)
  259. {
  260. if (empty($row)) {
  261. return;
  262. }
  263. $rowContent = $this->renderColumnSeparator();
  264. foreach ($this->getRowColumns($row) as $column) {
  265. $rowContent .= $this->renderCell($row, $column, $cellFormat);
  266. $rowContent .= $this->renderColumnSeparator();
  267. }
  268. $this->output->writeln($rowContent);
  269. }
  270. /**
  271. * Renders table cell with padding.
  272. *
  273. * @param array $row
  274. * @param int $column
  275. * @param string $cellFormat
  276. */
  277. private function renderCell(array $row, $column, $cellFormat)
  278. {
  279. $cell = isset($row[$column]) ? $row[$column] : '';
  280. $width = $this->columnWidths[$column];
  281. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  282. // add the width of the following columns(numbers of colspan).
  283. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $nextColumn) {
  284. $width += $this->getColumnSeparatorWidth() + $this->columnWidths[$nextColumn];
  285. }
  286. }
  287. // str_pad won't work properly with multi-byte strings, we need to fix the padding
  288. if (false !== $encoding = mb_detect_encoding($cell, null, true)) {
  289. $width += strlen($cell) - mb_strwidth($cell, $encoding);
  290. }
  291. $style = $this->getColumnStyle($column);
  292. if ($cell instanceof TableSeparator) {
  293. return sprintf($style->getBorderFormat(), str_repeat($style->getHorizontalBorderChar(), $width));
  294. }
  295. $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  296. $content = sprintf($style->getCellRowContentFormat(), $cell);
  297. return sprintf($cellFormat, str_pad($content, $width, $style->getPaddingChar(), $style->getPadType()));
  298. }
  299. /**
  300. * Calculate number of columns for this table.
  301. */
  302. private function calculateNumberOfColumns()
  303. {
  304. if (null !== $this->numberOfColumns) {
  305. return;
  306. }
  307. $columns = array(0);
  308. foreach (array_merge($this->headers, $this->rows) as $row) {
  309. if ($row instanceof TableSeparator) {
  310. continue;
  311. }
  312. $columns[] = $this->getNumberOfColumns($row);
  313. }
  314. $this->numberOfColumns = max($columns);
  315. }
  316. private function buildTableRows($rows)
  317. {
  318. $unmergedRows = array();
  319. for ($rowKey = 0; $rowKey < count($rows); ++$rowKey) {
  320. $rows = $this->fillNextRows($rows, $rowKey);
  321. // Remove any new line breaks and replace it with a new line
  322. foreach ($rows[$rowKey] as $column => $cell) {
  323. if (!strstr($cell, "\n")) {
  324. continue;
  325. }
  326. $lines = explode("\n", $cell);
  327. foreach ($lines as $lineKey => $line) {
  328. if ($cell instanceof TableCell) {
  329. $line = new TableCell($line, array('colspan' => $cell->getColspan()));
  330. }
  331. if (0 === $lineKey) {
  332. $rows[$rowKey][$column] = $line;
  333. } else {
  334. $unmergedRows[$rowKey][$lineKey][$column] = $line;
  335. }
  336. }
  337. }
  338. }
  339. $tableRows = array();
  340. foreach ($rows as $rowKey => $row) {
  341. $tableRows[] = $this->fillCells($row);
  342. if (isset($unmergedRows[$rowKey])) {
  343. $tableRows = array_merge($tableRows, $unmergedRows[$rowKey]);
  344. }
  345. }
  346. return $tableRows;
  347. }
  348. /**
  349. * fill rows that contains rowspan > 1.
  350. *
  351. * @param array $rows
  352. * @param int $line
  353. *
  354. * @return array
  355. */
  356. private function fillNextRows($rows, $line)
  357. {
  358. $unmergedRows = array();
  359. foreach ($rows[$line] as $column => $cell) {
  360. if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
  361. $nbLines = $cell->getRowspan() - 1;
  362. $lines = array($cell);
  363. if (strstr($cell, "\n")) {
  364. $lines = explode("\n", $cell);
  365. $nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
  366. $rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
  367. unset($lines[0]);
  368. }
  369. // create a two dimensional array (rowspan x colspan)
  370. $unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
  371. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  372. $value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
  373. $unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
  374. if ($nbLines === $unmergedRowKey - $line) {
  375. break;
  376. }
  377. }
  378. }
  379. }
  380. foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
  381. // we need to know if $unmergedRow will be merged or inserted into $rows
  382. if (isset($rows[$unmergedRowKey]) && is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
  383. foreach ($unmergedRow as $cellKey => $cell) {
  384. // insert cell into row at cellKey position
  385. array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
  386. }
  387. } else {
  388. $row = $this->copyRow($rows, $unmergedRowKey - 1);
  389. foreach ($unmergedRow as $column => $cell) {
  390. if (!empty($cell)) {
  391. $row[$column] = $unmergedRow[$column];
  392. }
  393. }
  394. array_splice($rows, $unmergedRowKey, 0, array($row));
  395. }
  396. }
  397. return $rows;
  398. }
  399. /**
  400. * fill cells for a row that contains colspan > 1.
  401. *
  402. * @param array $row
  403. *
  404. * @return array
  405. */
  406. private function fillCells($row)
  407. {
  408. $newRow = array();
  409. foreach ($row as $column => $cell) {
  410. $newRow[] = $cell;
  411. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  412. foreach (range($column + 1, $column + $cell->getColspan() - 1) as $position) {
  413. // insert empty value at column position
  414. $newRow[] = '';
  415. }
  416. }
  417. }
  418. return $newRow ?: $row;
  419. }
  420. /**
  421. * @param array $rows
  422. * @param int $line
  423. *
  424. * @return array
  425. */
  426. private function copyRow($rows, $line)
  427. {
  428. $row = $rows[$line];
  429. foreach ($row as $cellKey => $cellValue) {
  430. $row[$cellKey] = '';
  431. if ($cellValue instanceof TableCell) {
  432. $row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
  433. }
  434. }
  435. return $row;
  436. }
  437. /**
  438. * Gets number of columns by row.
  439. *
  440. * @param array $row
  441. *
  442. * @return int
  443. */
  444. private function getNumberOfColumns(array $row)
  445. {
  446. $columns = count($row);
  447. foreach ($row as $column) {
  448. $columns += $column instanceof TableCell ? ($column->getColspan() - 1) : 0;
  449. }
  450. return $columns;
  451. }
  452. /**
  453. * Gets list of columns for the given row.
  454. *
  455. * @param array $row
  456. *
  457. * @return array
  458. */
  459. private function getRowColumns($row)
  460. {
  461. $columns = range(0, $this->numberOfColumns - 1);
  462. foreach ($row as $cellKey => $cell) {
  463. if ($cell instanceof TableCell && $cell->getColspan() > 1) {
  464. // exclude grouped columns.
  465. $columns = array_diff($columns, range($cellKey + 1, $cellKey + $cell->getColspan() - 1));
  466. }
  467. }
  468. return $columns;
  469. }
  470. /**
  471. * Calculates columns widths.
  472. *
  473. * @param array $rows
  474. */
  475. private function calculateColumnsWidth($rows)
  476. {
  477. for ($column = 0; $column < $this->numberOfColumns; ++$column) {
  478. $lengths = array();
  479. foreach ($rows as $row) {
  480. if ($row instanceof TableSeparator) {
  481. continue;
  482. }
  483. foreach ($row as $i => $cell) {
  484. if ($cell instanceof TableCell) {
  485. $textLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  486. if ($textLength > 0) {
  487. $contentColumns = str_split($cell, ceil($textLength / $cell->getColspan()));
  488. foreach ($contentColumns as $position => $content) {
  489. $row[$i + $position] = $content;
  490. }
  491. }
  492. }
  493. }
  494. $lengths[] = $this->getCellWidth($row, $column);
  495. }
  496. $this->columnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
  497. }
  498. }
  499. /**
  500. * Gets column width.
  501. *
  502. * @return int
  503. */
  504. private function getColumnSeparatorWidth()
  505. {
  506. return strlen(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
  507. }
  508. /**
  509. * Gets cell width.
  510. *
  511. * @param array $row
  512. * @param int $column
  513. *
  514. * @return int
  515. */
  516. private function getCellWidth(array $row, $column)
  517. {
  518. if (isset($row[$column])) {
  519. $cell = $row[$column];
  520. $cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  521. return $cellWidth;
  522. }
  523. return 0;
  524. }
  525. /**
  526. * Called after rendering to cleanup cache data.
  527. */
  528. private function cleanup()
  529. {
  530. $this->columnWidths = array();
  531. $this->numberOfColumns = null;
  532. }
  533. private static function initStyles()
  534. {
  535. $borderless = new TableStyle();
  536. $borderless
  537. ->setHorizontalBorderChar('=')
  538. ->setVerticalBorderChar(' ')
  539. ->setCrossingChar(' ')
  540. ;
  541. $compact = new TableStyle();
  542. $compact
  543. ->setHorizontalBorderChar('')
  544. ->setVerticalBorderChar(' ')
  545. ->setCrossingChar('')
  546. ->setCellRowContentFormat('%s')
  547. ;
  548. $styleGuide = new TableStyle();
  549. $styleGuide
  550. ->setHorizontalBorderChar('-')
  551. ->setVerticalBorderChar(' ')
  552. ->setCrossingChar(' ')
  553. ->setCellHeaderFormat('%s')
  554. ;
  555. return array(
  556. 'default' => new TableStyle(),
  557. 'borderless' => $borderless,
  558. 'compact' => $compact,
  559. 'symfony-style-guide' => $styleGuide,
  560. );
  561. }
  562. private function resolveStyle($name)
  563. {
  564. if ($name instanceof TableStyle) {
  565. return $name;
  566. }
  567. if (isset(self::$styles[$name])) {
  568. return self::$styles[$name];
  569. }
  570. throw new InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  571. }
  572. }