3 * Utility for printing tables from commandline scripts.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
12 * o Redistributions of source code must retain the above copyright notice,
13 * this list of conditions and the following disclaimer.
14 * o Redistributions in binary form must reproduce the above copyright notice,
15 * this list of conditions and the following disclaimer in the documentation
16 * and/or other materials provided with the distribution.
17 * o The names of the authors may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
33 * @package Console_Table
34 * @author Richard Heyes <richard@phpguru.org>
35 * @author Jan Schneider <jan@horde.org>
36 * @copyright 2002-2005 Richard Heyes
37 * @copyright 2006-2008 Jan Schneider
38 * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
40 * @link http://pear.php.net/package/Console_Table
43 define('CONSOLE_TABLE_HORIZONTAL_RULE', 1);
44 define('CONSOLE_TABLE_ALIGN_LEFT', -1);
45 define('CONSOLE_TABLE_ALIGN_CENTER', 0);
46 define('CONSOLE_TABLE_ALIGN_RIGHT', 1);
47 define('CONSOLE_TABLE_BORDER_ASCII', -1);
53 * @package Console_Table
54 * @author Jan Schneider <jan@horde.org>
55 * @license http://www.debian.org/misc/bsd.license BSD License (3 Clause)
56 * @link http://pear.php.net/package/Console_Table
65 var $_headers = array();
68 * The data of the table.
75 * The maximum number of columns in a row.
82 * The maximum number of rows in the table.
89 * Lengths of the columns, calculated when rows are added to the table.
93 var $_cell_lengths = array();
96 * Heights of the rows.
100 var $_row_heights = array();
103 * How many spaces to use to pad the table.
114 var $_filters = array();
117 * Columns to calculate totals for.
121 var $_calculateTotals;
124 * Alignment of the columns.
128 var $_col_align = array();
131 * Default alignment of columns.
138 * Character set of the data.
142 var $_charset = 'utf-8';
147 * - intersection - intersection ("+")
148 * - horizontal - horizontal rule character ("-")
149 * - vertical - vertical rule character ("|")
153 var $_border = array(
154 'intersection' => '+',
160 * If borders are shown or not
161 * Allowed keys: top, right, bottom, left, inner: true and false
165 var $_borderVisibility = array(
174 * Whether the data has ANSI colors.
176 * @var Console_Color2
178 var $_ansiColor = false;
183 * @param integer $align Default alignment. One of
184 * CONSOLE_TABLE_ALIGN_LEFT,
185 * CONSOLE_TABLE_ALIGN_CENTER or
186 * CONSOLE_TABLE_ALIGN_RIGHT.
187 * @param string $border The character used for table borders or
188 * CONSOLE_TABLE_BORDER_ASCII.
189 * @param integer $padding How many spaces to use to pad the table.
190 * @param string $charset A charset supported by the mbstring PHP
192 * @param boolean $color Whether the data contains ansi color codes.
194 function __construct($align = CONSOLE_TABLE_ALIGN_LEFT,
195 $border = CONSOLE_TABLE_BORDER_ASCII, $padding = 1,
196 $charset = null, $color = false)
198 $this->_defaultAlign = $align;
199 $this->setBorder($border);
200 $this->_padding = $padding;
202 if (!class_exists('Console_Color2')) {
203 include_once 'Console/Color2.php';
205 $this->_ansiColor = new Console_Color2();
207 if (!empty($charset)) {
208 $this->setCharset($charset);
213 * Converts an array to a table.
215 * @param array $headers Headers for the table.
216 * @param array $data A two dimensional array with the table
218 * @param boolean $returnObject Whether to return the Console_Table object
219 * instead of the rendered table.
223 * @return Console_Table|string A Console_Table object or the generated
226 function fromArray($headers, $data, $returnObject = false)
228 if (!is_array($headers) || !is_array($data)) {
232 $table = new Console_Table();
233 $table->setHeaders($headers);
235 foreach ($data as $row) {
236 $table->addRow($row);
239 return $returnObject ? $table : $table->getTable();
243 * Adds a filter to a column.
245 * Filters are standard PHP callbacks which are run on the data before
246 * table generation is performed. Filters are applied in the order they
247 * are added. The callback function must accept a single argument, which
248 * is a single table cell.
250 * @param integer $col Column to apply filter to.
251 * @param mixed &$callback PHP callback to apply.
255 function addFilter($col, &$callback)
257 $this->_filters[] = array($col, &$callback);
261 * Sets the charset of the provided table data.
263 * @param string $charset A charset supported by the mbstring PHP
268 function setCharset($charset)
270 $locale = setlocale(LC_CTYPE, 0);
271 setlocale(LC_CTYPE, 'en_US');
272 $this->_charset = strtolower($charset);
273 setlocale(LC_CTYPE, $locale);
277 * Set the table border settings
279 * Border definition modes:
280 * - CONSOLE_TABLE_BORDER_ASCII: Default border with +, - and |
281 * - array with keys "intersection", "horizontal" and "vertical"
282 * - single character string that sets all three of the array keys
284 * @param mixed $border Border definition
289 function setBorder($border)
291 if ($border === CONSOLE_TABLE_BORDER_ASCII) {
295 } else if (is_string($border)) {
296 $intersection = $horizontal = $vertical = $border;
297 } else if ($border == '') {
298 $intersection = $horizontal = $vertical = '';
303 $this->_border = array(
304 'intersection' => $intersection,
305 'horizontal' => $horizontal,
306 'vertical' => $vertical,
311 * Set which borders shall be shown.
313 * @param array $visibility Visibility settings.
314 * Allowed keys: left, right, top, bottom, inner
317 * @see $_borderVisibility
319 function setBorderVisibility($visibility)
321 $this->_borderVisibility = array_merge(
322 $this->_borderVisibility,
325 $this->_borderVisibility
331 * Sets the alignment for the columns.
333 * @param integer $col_id The column number.
334 * @param integer $align Alignment to set for this column. One of
335 * CONSOLE_TABLE_ALIGN_LEFT
336 * CONSOLE_TABLE_ALIGN_CENTER
337 * CONSOLE_TABLE_ALIGN_RIGHT.
341 function setAlign($col_id, $align = CONSOLE_TABLE_ALIGN_LEFT)
344 case CONSOLE_TABLE_ALIGN_CENTER:
347 case CONSOLE_TABLE_ALIGN_RIGHT:
351 $pad = STR_PAD_RIGHT;
354 $this->_col_align[$col_id] = $pad;
358 * Specifies which columns are to have totals calculated for them and
359 * added as a new row at the bottom.
361 * @param array $cols Array of column numbers (starting with 0).
365 function calculateTotalsFor($cols)
367 $this->_calculateTotals = $cols;
371 * Sets the headers for the columns.
373 * @param array $headers The column headers.
377 function setHeaders($headers)
379 $this->_headers = array(array_values($headers));
380 $this->_updateRowsCols($headers);
384 * Adds a row to the table.
386 * @param array $row The row data to add.
387 * @param boolean $append Whether to append or prepend the row.
391 function addRow($row, $append = true)
394 $this->_data[] = array_values($row);
396 array_unshift($this->_data, array_values($row));
399 $this->_updateRowsCols($row);
403 * Inserts a row after a given row number in the table.
405 * If $row_id is not given it will prepend the row.
407 * @param array $row The data to insert.
408 * @param integer $row_id Row number to insert before.
412 function insertRow($row, $row_id = 0)
414 array_splice($this->_data, $row_id, 0, array($row));
416 $this->_updateRowsCols($row);
420 * Adds a column to the table.
422 * @param array $col_data The data of the column.
423 * @param integer $col_id The column index to populate.
424 * @param integer $row_id If starting row is not zero, specify it here.
428 function addCol($col_data, $col_id = 0, $row_id = 0)
430 foreach ($col_data as $col_cell) {
431 $this->_data[$row_id++][$col_id] = $col_cell;
434 $this->_updateRowsCols();
435 $this->_max_cols = max($this->_max_cols, $col_id + 1);
439 * Adds data to the table.
441 * @param array $data A two dimensional array with the table data.
442 * @param integer $col_id Starting column number.
443 * @param integer $row_id Starting row number.
447 function addData($data, $col_id = 0, $row_id = 0)
449 foreach ($data as $row) {
450 if ($row === CONSOLE_TABLE_HORIZONTAL_RULE) {
451 $this->_data[$row_id] = CONSOLE_TABLE_HORIZONTAL_RULE;
455 $starting_col = $col_id;
456 foreach ($row as $cell) {
457 $this->_data[$row_id][$starting_col++] = $cell;
459 $this->_updateRowsCols();
460 $this->_max_cols = max($this->_max_cols, $starting_col);
466 * Adds a horizontal seperator to the table.
470 function addSeparator()
472 $this->_data[] = CONSOLE_TABLE_HORIZONTAL_RULE;
476 * Returns the generated table.
478 * @return string The generated table.
482 $this->_applyFilters();
483 $this->_calculateTotals();
484 $this->_validateTable();
486 return $this->_buildTable();
490 * Calculates totals for columns.
494 function _calculateTotals()
496 if (empty($this->_calculateTotals)) {
500 $this->addSeparator();
503 foreach ($this->_data as $row) {
504 if (is_array($row)) {
505 foreach ($this->_calculateTotals as $columnID) {
506 $totals[$columnID] += $row[$columnID];
511 $this->_data[] = $totals;
512 $this->_updateRowsCols();
516 * Applies any column filters to the data.
520 function _applyFilters()
522 if (empty($this->_filters)) {
526 foreach ($this->_filters as $filter) {
527 $column = $filter[0];
528 $callback = $filter[1];
530 foreach ($this->_data as $row_id => $row_data) {
531 if ($row_data !== CONSOLE_TABLE_HORIZONTAL_RULE) {
532 $this->_data[$row_id][$column] =
533 call_user_func($callback, $row_data[$column]);
540 * Ensures that column and row counts are correct.
544 function _validateTable()
546 if (!empty($this->_headers)) {
547 $this->_calculateRowHeight(-1, $this->_headers[0]);
550 for ($i = 0; $i < $this->_max_rows; $i++) {
551 for ($j = 0; $j < $this->_max_cols; $j++) {
552 if (!isset($this->_data[$i][$j]) &&
553 (!isset($this->_data[$i]) ||
554 $this->_data[$i] !== CONSOLE_TABLE_HORIZONTAL_RULE)) {
555 $this->_data[$i][$j] = '';
559 $this->_calculateRowHeight($i, $this->_data[$i]);
561 if ($this->_data[$i] !== CONSOLE_TABLE_HORIZONTAL_RULE) {
562 ksort($this->_data[$i]);
567 $this->_splitMultilineRows();
569 // Update cell lengths.
570 for ($i = 0; $i < count($this->_headers); $i++) {
571 $this->_calculateCellLengths($this->_headers[$i]);
573 for ($i = 0; $i < $this->_max_rows; $i++) {
574 $this->_calculateCellLengths($this->_data[$i]);
581 * Splits multiline rows into many smaller one-line rows.
585 function _splitMultilineRows()
588 $sections = array(&$this->_headers, &$this->_data);
589 $max_rows = array(count($this->_headers), $this->_max_rows);
590 $row_height_offset = array(-1, 0);
592 for ($s = 0; $s <= 1; $s++) {
594 $new_data = $sections[$s];
596 for ($i = 0; $i < $max_rows[$s]; $i++) {
597 // Process only rows that have many lines.
598 $height = $this->_row_heights[$i + $row_height_offset[$s]];
600 // Split column data into one-liners.
602 for ($j = 0; $j < $this->_max_cols; $j++) {
603 $split[$j] = preg_split('/\r?\n|\r/',
604 $sections[$s][$i][$j]);
608 // Construct new 'virtual' rows - insert empty strings for
609 // columns that have less lines that the highest one.
610 for ($i2 = 0; $i2 < $height; $i2++) {
611 for ($j = 0; $j < $this->_max_cols; $j++) {
612 $new_rows[$i2][$j] = !isset($split[$j][$i2])
618 // Replace current row with smaller rows. $inserted is
619 // used to take account of bigger array because of already
621 array_splice($new_data, $i + $inserted, 1, $new_rows);
622 $inserted += count($new_rows) - 1;
626 // Has the data been modified?
628 $sections[$s] = $new_data;
629 $this->_updateRowsCols();
637 * @return string The generated table string.
639 function _buildTable()
641 if (!count($this->_data)) {
645 $vertical = $this->_border['vertical'];
646 $separator = $this->_getSeparator();
649 for ($i = 0; $i < count($this->_data); $i++) {
650 if (is_array($this->_data[$i])) {
651 for ($j = 0; $j < count($this->_data[$i]); $j++) {
652 if ($this->_data[$i] !== CONSOLE_TABLE_HORIZONTAL_RULE &&
653 $this->_strlen($this->_data[$i][$j]) <
654 $this->_cell_lengths[$j]) {
655 $this->_data[$i][$j] = $this->_strpad($this->_data[$i][$j],
656 $this->_cell_lengths[$j],
658 $this->_col_align[$j]);
663 if ($this->_data[$i] !== CONSOLE_TABLE_HORIZONTAL_RULE) {
664 $row_begin = $this->_borderVisibility['left']
665 ? $vertical . str_repeat(' ', $this->_padding)
667 $row_end = $this->_borderVisibility['right']
668 ? str_repeat(' ', $this->_padding) . $vertical
670 $implode_char = str_repeat(' ', $this->_padding) . $vertical
671 . str_repeat(' ', $this->_padding);
672 $return[] = $row_begin
673 . implode($implode_char, $this->_data[$i]) . $row_end;
674 } elseif (!empty($separator)) {
675 $return[] = $separator;
680 $return = implode(PHP_EOL, $return);
681 if (!empty($separator)) {
682 if ($this->_borderVisibility['inner']) {
683 $return = $separator . PHP_EOL . $return;
685 if ($this->_borderVisibility['bottom']) {
686 $return .= PHP_EOL . $separator;
691 if (!empty($this->_headers)) {
692 $return = $this->_getHeaderLine() . PHP_EOL . $return;
699 * Creates a horizontal separator for header separation and table
702 * @return string The horizontal separator.
704 function _getSeparator()
706 if (!$this->_border) {
710 $horizontal = $this->_border['horizontal'];
711 $intersection = $this->_border['intersection'];
714 foreach ($this->_cell_lengths as $cl) {
715 $return[] = str_repeat($horizontal, $cl);
718 $row_begin = $this->_borderVisibility['left']
719 ? $intersection . str_repeat($horizontal, $this->_padding)
721 $row_end = $this->_borderVisibility['right']
722 ? str_repeat($horizontal, $this->_padding) . $intersection
724 $implode_char = str_repeat($horizontal, $this->_padding) . $intersection
725 . str_repeat($horizontal, $this->_padding);
727 return $row_begin . implode($implode_char, $return) . $row_end;
731 * Returns the header line for the table.
733 * @return string The header line of the table.
735 function _getHeaderLine()
737 // Make sure column count is correct
738 for ($j = 0; $j < count($this->_headers); $j++) {
739 for ($i = 0; $i < $this->_max_cols; $i++) {
740 if (!isset($this->_headers[$j][$i])) {
741 $this->_headers[$j][$i] = '';
746 for ($j = 0; $j < count($this->_headers); $j++) {
747 for ($i = 0; $i < count($this->_headers[$j]); $i++) {
748 if ($this->_strlen($this->_headers[$j][$i]) <
749 $this->_cell_lengths[$i]) {
750 $this->_headers[$j][$i] =
751 $this->_strpad($this->_headers[$j][$i],
752 $this->_cell_lengths[$i],
754 $this->_col_align[$i]);
759 $vertical = $this->_border['vertical'];
760 $row_begin = $this->_borderVisibility['left']
761 ? $vertical . str_repeat(' ', $this->_padding)
763 $row_end = $this->_borderVisibility['right']
764 ? str_repeat(' ', $this->_padding) . $vertical
766 $implode_char = str_repeat(' ', $this->_padding) . $vertical
767 . str_repeat(' ', $this->_padding);
769 $separator = $this->_getSeparator();
770 if (!empty($separator) && $this->_borderVisibility['top']) {
771 $return[] = $separator;
773 for ($j = 0; $j < count($this->_headers); $j++) {
774 $return[] = $row_begin
775 . implode($implode_char, $this->_headers[$j]) . $row_end;
778 return implode(PHP_EOL, $return);
782 * Updates values for maximum columns and rows.
784 * @param array $rowdata Data array of a single row.
788 function _updateRowsCols($rowdata = null)
790 // Update maximum columns.
791 $this->_max_cols = max($this->_max_cols, is_array($rowdata) ? count($rowdata) : 0);
793 // Update maximum rows.
795 $keys = array_keys($this->_data);
796 $this->_max_rows = end($keys) + 1;
798 switch ($this->_defaultAlign) {
799 case CONSOLE_TABLE_ALIGN_CENTER:
802 case CONSOLE_TABLE_ALIGN_RIGHT:
806 $pad = STR_PAD_RIGHT;
810 // Set default column alignments
811 for ($i = 0; $i < $this->_max_cols; $i++) {
812 if (!isset($this->_col_align[$i])) {
813 $this->_col_align[$i] = $pad;
819 * Calculates the maximum length for each column of a row.
821 * @param array $row The row data.
825 function _calculateCellLengths($row)
827 if (is_array($row)) {
828 for ($i = 0; $i < count($row); $i++) {
829 if (!isset($this->_cell_lengths[$i])) {
830 $this->_cell_lengths[$i] = 0;
832 $this->_cell_lengths[$i] = max($this->_cell_lengths[$i],
833 $this->_strlen($row[$i]));
839 * Calculates the maximum height for all columns of a row.
841 * @param integer $row_number The row number.
842 * @param array $row The row data.
846 function _calculateRowHeight($row_number, $row)
848 if (!isset($this->_row_heights[$row_number])) {
849 $this->_row_heights[$row_number] = 1;
852 // Do not process horizontal rule rows.
853 if ($row === CONSOLE_TABLE_HORIZONTAL_RULE) {
857 for ($i = 0, $c = count($row); $i < $c; ++$i) {
858 $lines = preg_split('/\r?\n|\r/', $row[$i]);
859 $this->_row_heights[$row_number] = max($this->_row_heights[$row_number],
865 * Returns the character length of a string.
867 * @param string $str A multibyte or singlebyte string.
869 * @return integer The string length.
871 function _strlen($str)
875 // Strip ANSI color codes if requested.
876 if ($this->_ansiColor) {
877 $str = $this->_ansiColor->strip($str);
880 // Cache expensive function_exists() calls.
881 if (!isset($mbstring)) {
882 $mbstring = function_exists('mb_strwidth');
886 return mb_strwidth($str, $this->_charset);
893 * Returns part of a string.
895 * @param string $string The string to be converted.
896 * @param integer $start The part's start position, zero based.
897 * @param integer $length The part's length.
899 * @return string The string's part.
901 function _substr($string, $start, $length = null)
905 // Cache expensive function_exists() calls.
906 if (!isset($mbstring)) {
907 $mbstring = function_exists('mb_substr');
910 if (is_null($length)) {
911 $length = $this->_strlen($string);
914 $ret = @mb_substr($string, $start, $length, $this->_charset);
919 return substr($string, $start, $length);
923 * Returns a string padded to a certain length with another string.
925 * This method behaves exactly like str_pad but is multibyte safe.
927 * @param string $input The string to be padded.
928 * @param integer $length The length of the resulting string.
929 * @param string $pad The string to pad the input string with. Must
930 * be in the same charset like the input string.
931 * @param const $type The padding type. One of STR_PAD_LEFT,
932 * STR_PAD_RIGHT, or STR_PAD_BOTH.
934 * @return string The padded string.
936 function _strpad($input, $length, $pad = ' ', $type = STR_PAD_RIGHT)
938 $mb_length = $this->_strlen($input);
939 $sb_length = strlen($input);
940 $pad_length = $this->_strlen($pad);
942 /* Return if we already have the length. */
943 if ($mb_length >= $length) {
947 /* Shortcut for single byte strings. */
948 if ($mb_length == $sb_length && $pad_length == strlen($pad)) {
949 return str_pad($input, $length, $pad, $type);
954 $left = $length - $mb_length;
955 $output = $this->_substr(str_repeat($pad, ceil($left / $pad_length)),
956 0, $left, $this->_charset) . $input;
959 $left = floor(($length - $mb_length) / 2);
960 $right = ceil(($length - $mb_length) / 2);
961 $output = $this->_substr(str_repeat($pad, ceil($left / $pad_length)),
962 0, $left, $this->_charset) .
964 $this->_substr(str_repeat($pad, ceil($right / $pad_length)),
965 0, $right, $this->_charset);
968 $right = $length - $mb_length;
970 $this->_substr(str_repeat($pad, ceil($right / $pad_length)),
971 0, $right, $this->_charset);