Console_Table
[ class tree: Console_Table ] [ index: Console_Table ] [ all elements ]

Source for file Table.php

Documentation is available at Table.php

  1. <?php
  2. // +-----------------------------------------------------------------------+
  3. // | Copyright (c) 2002-2003 Richard Heyes                                 |
  4. // | All rights reserved.                                                  |
  5. // |                                                                       |
  6. // | Redistribution and use in source and binary forms, with or without    |
  7. // | modification, are permitted provided that the following conditions    |
  8. // | are met:                                                              |
  9. // |                                                                       |
  10. // | o Redistributions of source code must retain the above copyright      |
  11. // |   notice, this list of conditions and the following disclaimer.       |
  12. // | o Redistributions in binary form must reproduce the above copyright   |
  13. // |   notice, this list of conditions and the following disclaimer in the |
  14. // |   documentation and/or other materials provided with the distribution.|
  15. // | o The names of the authors may not be used to endorse or promote      |
  16. // |   products derived from this software without specific prior written  |
  17. // |   permission.                                                         |
  18. // |                                                                       |
  19. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
  20. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
  21. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
  22. // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
  23. // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
  24. // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
  25. // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
  26. // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
  27. // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
  28. // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
  29. // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
  30. // |                                                                       |
  31. // +-----------------------------------------------------------------------+
  32. // | Author: Richard Heyes <richard@phpguru.org>                           |
  33. // |         Jan Schneider <jan@horde.org>                                 |
  34. // +-----------------------------------------------------------------------+
  35. //
  36. // $Id: Table.php,v 1.16 2006/03/13 12:11:59 yunosh Exp $
  37. //
  38. // Utility for printing tables from cmdline scripts
  39. //
  40.  
  41. define('CONSOLE_TABLE_HORIZONTAL_RULE'1);
  42. define('CONSOLE_TABLE_ALIGN_LEFT'-1);
  43. define('CONSOLE_TABLE_ALIGN_CENTER'0);
  44. define('CONSOLE_TABLE_ALIGN_RIGHT'1);
  45.  
  46. class Console_Table
  47. {
  48.     /**
  49.      * The table headers.
  50.      *
  51.      * @var array 
  52.      */
  53.     var $_headers = array();
  54.  
  55.     /**
  56.      * The data of the table.
  57.      *
  58.      * @var array 
  59.      */
  60.     var $_data = array();
  61.  
  62.     /**
  63.      * The max number of columns in a row.
  64.      *
  65.      * @var integer 
  66.      */
  67.     var $_max_cols = 0;
  68.  
  69.     /**
  70.      * The max number of rows in the table.
  71.      *
  72.      * @var integer 
  73.      */
  74.     var $_max_rows = 0;
  75.  
  76.     /**
  77.      * Lengths of the columns, calculated when rows are added to the table.
  78.      *
  79.      * @var array 
  80.      */
  81.     var $_cell_lengths = array();
  82.  
  83.     /**
  84.      * Heights of the rows.
  85.      *
  86.      * @var array 
  87.      */
  88.     var $_row_heights = array();
  89.  
  90.     /**
  91.      * How many spaces to use to pad the table.
  92.      *
  93.      * @var integer 
  94.      */
  95.     var $_padding = 1;
  96.  
  97.     /**
  98.      * Column filters.
  99.      *
  100.      * @var array 
  101.      */
  102.     var $_filters = array();
  103.  
  104.     /**
  105.      * Columns to calculate totals for.
  106.      *
  107.      * @var array 
  108.      */
  109.     var $_calculateTotals;
  110.  
  111.     /**
  112.      * Alignment of the columns.
  113.      *
  114.      * @var array 
  115.      */
  116.     var $_col_align = array();
  117.  
  118.     /**
  119.      * Default alignment of columns.
  120.      *
  121.      * @var integer 
  122.      */
  123.     var $_defaultAlign;
  124.  
  125.     /**
  126.      * Charset of the data.
  127.      *
  128.      * @var string 
  129.      */
  130.     var $_charset 'utf-8';
  131.  
  132.     /**
  133.      * Constructor.
  134.      *
  135.      * @param integer $align  Default alignment
  136.      */
  137.     function Console_Table($align = CONSOLE_TABLE_ALIGN_LEFT)
  138.     {
  139.         $this->_defaultAlign $align;
  140.     }
  141.  
  142.     /**
  143.      * Converts an array to a table. Must be
  144.      *
  145.      * @static
  146.      *
  147.      * @param array $headers         Headers for the table.
  148.      * @param array $data            A two dimensional array with the table
  149.      *                                data.
  150.      * @param boolean $returnObject  Whether to return the Console_Table object
  151.      *                                instead of the rendered table.
  152.      *
  153.      * @return Console_Table|string A Console_Table object or the generated
  154.      *                                table.
  155.      */
  156.     function fromArray($headers$data$returnObject = false)
  157.     {
  158.         if (!is_array($headers|| !is_array($data)) {
  159.             return false;
  160.         }
  161.  
  162.         $table &new Console_Table();
  163.         $table->setHeaders($headers);
  164.  
  165.         foreach ($data as $row{
  166.             $table->addRow($row);
  167.         }
  168.  
  169.         return $returnObject $table $table->getTable();
  170.     }
  171.  
  172.     /**
  173.      * Adds a filter to a column.
  174.      *
  175.      * Filters are standard PHP callbacks which are run on the data before
  176.      * table generation is performed. Filters are applied in the order they
  177.      * are added. The callback function must accept a single argument, which
  178.      * is a single table cell.
  179.      *
  180.      * @param integer $col     Column to apply filter to.
  181.      * @param mixed $callback  PHP callback to apply.
  182.      */
  183.     function addFilter($col&$callback)
  184.     {
  185.         $this->_filters[= array($col&$callback);
  186.     }
  187.  
  188.     /**
  189.      * Sets the charset of the provided table data.
  190.      *
  191.      * @string $charset  A charset supported by the mbstring PHP extension.
  192.      */
  193.     function setCharset($charset)
  194.     {
  195.         $this->_charset strtolower($charset);
  196.     }
  197.  
  198.     /**
  199.      * Sets the alignment for the columns.
  200.      *
  201.      * @param integer $col_id  The column number.
  202.      * @param integer $align   Alignment to set for this column. One of
  203.      *                          CONSOLE_TABLE_ALIGN_LEFT
  204.      *                          CONSOLE_TABLE_ALIGN_CENTER
  205.      *                          CONSOLE_TABLE_ALIGN_RIGHT.
  206.      */
  207.     function setAlign($col_id$align = CONSOLE_TABLE_ALIGN_LEFT)
  208.     {
  209.         switch ($align{
  210.             case CONSOLE_TABLE_ALIGN_CENTER:
  211.                 $pad = STR_PAD_BOTH;
  212.                 break;
  213.             case CONSOLE_TABLE_ALIGN_RIGHT:
  214.                 $pad = STR_PAD_LEFT;
  215.                 break;
  216.             default:
  217.                 $pad = STR_PAD_RIGHT;
  218.                 break;
  219.         }
  220.         $this->_col_align[$col_id$pad;
  221.     }
  222.  
  223.     /**
  224.      * Specifies which columns are to have totals calculated for them and
  225.      * added as a new row at the bottom.
  226.      *
  227.      * @param array $cols  Array of column numbers (starting with 0).
  228.      */
  229.     function calculateTotalsFor($cols)
  230.     {
  231.         $this->_calculateTotals $cols;
  232.     }
  233.  
  234.     /**
  235.      * Sets the headers for the columns.
  236.      *
  237.      * @param array $headers  The column headers.
  238.      */
  239.     function setHeaders($headers)
  240.     {
  241.         $this->_headers array_values($headers);
  242.         $this->_updateRowsCols($headers);
  243.     }
  244.  
  245.     /**
  246.      * Adds a row to the table.
  247.      *
  248.      * @param array $row       The row data to add.
  249.      * @param boolean $append  Whether to append or prepend the row.
  250.     */
  251.     function addRow($row$append = true)
  252.     {
  253.         if ($append{
  254.             $this->_data[array_values($row);
  255.         else {
  256.             array_unshift($this->_dataarray_values($row));
  257.         }
  258.  
  259.         $this->_updateRowsCols($row);
  260.     }
  261.  
  262.     /**
  263.      * Inserts a row after a given row number in the table.
  264.      *
  265.      * If $row_id is not given it will prepend the row.
  266.      *
  267.      * @param array $row       The data to insert.
  268.      * @param integer $row_id  Row number to insert before.
  269.      */
  270.     function insertRow($row$row_id = 0)
  271.     {
  272.         array_splice($this->_data$row_id0array($row));
  273.  
  274.         $this->_updateRowsCols($row);
  275.     }
  276.  
  277.     /**
  278.      * Adds a column to the table.
  279.      *
  280.      * @param array $col_data  The data of the column.
  281.      * @param integer $col_id  The column index to populate.
  282.      * @param integer $row_id  If starting row is not zero, specify it here.
  283.      */
  284.     function addCol($col_data$col_id = 0$row_id = 0)
  285.     {
  286.         foreach ($col_data as $col_cell{
  287.             $this->_data[$row_id++][$col_id$col_cell;
  288.         }
  289.  
  290.         $this->_updateRowsCols();
  291.         $this->_max_cols max($this->_max_cols$col_id + 1);
  292.     }
  293.  
  294.     /**
  295.      * Adds data to the table.
  296.      *
  297.      * @param array $data      A two dimensional array with the table data.
  298.      * @param integer $col_id  Starting column number.
  299.      * @param integer $row_id  Starting row number.
  300.      */
  301.     function addData($data$col_id = 0$row_id = 0)
  302.     {
  303.         foreach ($data as $row{
  304.             $starting_col $col_id;
  305.             foreach ($row as $cell{
  306.                 $this->_data[$row_id][$starting_col++$cell;
  307.             }
  308.             $this->_updateRowsCols();
  309.             $this->_max_cols max($this->_max_cols$starting_col);
  310.             $row_id++;
  311.         }
  312.     }
  313.  
  314.     /**
  315.      * Adds a horizontal seperator to the table.
  316.      */
  317.     function addSeparator()
  318.     {
  319.         $this->_data[CONSOLE_TABLE_HORIZONTAL_RULE;
  320.     }
  321.  
  322.     /*
  323.      * Returns the table in wonderful ASCII art.
  324.      *
  325.      * @return string  The generated table.
  326.      */
  327.     function getTable()
  328.     {
  329.         $this->_applyFilters();
  330.         $this->_calculateTotals();
  331.         $this->_validateTable();
  332.  
  333.         return $this->_buildTable();
  334.     }
  335.  
  336.     /**
  337.      * Calculates totals for columns.
  338.      */
  339.     function _calculateTotals()
  340.     {
  341.         if (!empty($this->_calculateTotals)) {
  342.             $this->addSeparator();
  343.  
  344.             $totals = array();
  345.             foreach ($this->_data as $row{
  346.                 if (is_array($row)) {
  347.                     foreach ($this->_calculateTotals as $columnID{
  348.                         $totals[$columnID+= $row[$columnID];
  349.                     }
  350.                 }
  351.             }
  352.  
  353.             $this->_data[$totals;
  354.             $this->_updateRowsCols();
  355.         }
  356.     }
  357.  
  358.     /**
  359.      * Applies any column filters to the data.
  360.      */
  361.     function _applyFilters()
  362.     {
  363.         if (!empty($this->_filters)) {
  364.             foreach ($this->_filters as $filter{
  365.                 $column   $filter[0];
  366.                 $callback $filter[1];
  367.  
  368.                 foreach ($this->_data as $row_id => $row_data{
  369.                     $this->_data[$row_id][$columncall_user_func($callback$row_data[$column]);
  370.                 }
  371.             }
  372.         }
  373.     }
  374.  
  375.     /**
  376.      * Ensures column and row counts are correct.
  377.      */
  378.     function _validateTable()
  379.     {
  380.         for ($i = 0; $i $this->_max_rows$i++{
  381.             for ($j = 0; $j $this->_max_cols$j++{
  382.                 if (!isset($this->_data[$i][$j]&&
  383.                     (!isset($this->_data[$i]||
  384.                      $this->_data[$i!= CONSOLE_TABLE_HORIZONTAL_RULE)) {
  385.                     $this->_data[$i][$j'';
  386.                 }
  387.  
  388.                 $this->_calculateRowHeight($i$this->_data[$i]);
  389.             }
  390.  
  391.             if ($this->_data[$i!= CONSOLE_TABLE_HORIZONTAL_RULE{
  392.                  ksort($this->_data[$i]);
  393.             }
  394.  
  395.         }
  396.  
  397.         $this->_splitMultilineRows();
  398.  
  399.         // Update cell lengths.
  400.         for ($i = 0; $i $this->_max_rows$i++{
  401.             $this->_calculateCellLengths($this->_data[$i]);
  402.         }
  403.  
  404.         ksort($this->_data);
  405.     }
  406.  
  407.     /**
  408.      * Splits multiline rows into many smaller one-line rows.
  409.      */
  410.     function _splitMultilineRows({
  411.  
  412.         $inserted = 0;
  413.         ksort($this->_data);
  414.         $new_data $this->_data;
  415.  
  416.         for ($i = 0; $i $this->_max_rows$i++{
  417.             // Process only rows that have many lines.
  418.             if (($height $this->_row_heights[$i]> 1{
  419.                 // Split column data into one-liners.
  420.                 $split = array();
  421.                 for ($j = 0; $j $this->_max_cols$j++{
  422.                     $split[$jpreg_split('/\r?\n|\r/'$this->_data[$i][$j]);
  423.                 }
  424.  
  425.                 $new_rows = array();
  426.                 // Construct new 'virtual' rows - insert empty strings for
  427.                 // columns that have less lines that the highest one.
  428.                 for ($i2 = 0; $i2 $height$i2++{
  429.                     for ($j = 0; $j $this->_max_cols$j++{
  430.                         $new_rows[$i2][$j!empty($split[$j][$i2]$split[$j][$i2'';
  431.                     }
  432.                 }
  433.  
  434.                 // Replace current row with smaller rows.  $inserted is used
  435.                 // to take account of bigger array because of already inserted
  436.                 // rows.
  437.                 array_splice($new_data$i $inserted1$new_rows);
  438.                 $inserted += count($new_rows- 1;
  439.             }
  440.         }
  441.  
  442.         // Has the data been modified?
  443.         if ($inserted > 0{
  444.             $this->_data $new_data;
  445.             $this->_updateRowsCols();
  446.         }
  447.     }
  448.  
  449.     /**
  450.      * Builds the table.
  451.      */
  452.     function _buildTable()
  453.     {
  454.         $return = array();
  455.         $rows   $this->_data;
  456.  
  457.         for ($i = 0; $i count($rows)$i++{
  458.             for ($j = 0; $j count($rows[$i])$j++{
  459.                 if ($rows[$i!= CONSOLE_TABLE_HORIZONTAL_RULE &&
  460.                     $this->_strlen($rows[$i][$j]$this->_cell_lengths[$j]{
  461.                     $rows[$i][$jstr_pad($rows[$i][$j],
  462.                                             $this->_cell_lengths[$j],
  463.                                             ' ',
  464.                                             $this->_col_align[$j]);
  465.                 }
  466.             }
  467.  
  468.             if ($rows[$i!= CONSOLE_TABLE_HORIZONTAL_RULE{
  469.                 $row_begin    '|' str_repeat(' '$this->_padding);
  470.                 $row_end      str_repeat(' '$this->_padding'|';
  471.                 $implode_char str_repeat(' '$this->_padding'|' .
  472.                     str_repeat(' '$this->_padding);
  473.                 $return[$row_begin implode($implode_char$rows[$i].
  474.                     $row_end;
  475.             else {
  476.                 $return[$this->_getSeparator();
  477.             }
  478.  
  479.         }
  480.  
  481.         $return $this->_getSeparator("\r\n" implode("\n"$return.
  482.             "\r\n" $this->_getSeparator("\r\n";
  483.  
  484.         if (!empty($this->_headers)) {
  485.             $return $this->_getHeaderLine(.  "\r\n" $return;
  486.         }
  487.  
  488.         return $return;
  489.     }
  490.  
  491.     /**
  492.      * Creates a horizontal separator for header separation and table
  493.      * start/end etc.
  494.      */
  495.     function _getSeparator()
  496.     {
  497.         foreach ($this->_cell_lengths as $cl{
  498.             $return[str_repeat('-'$cl);
  499.         }
  500.  
  501.         $row_begin    '+' str_repeat('-'$this->_padding);
  502.         $row_end      str_repeat('-'$this->_padding'+';
  503.         $implode_char str_repeat('-'$this->_padding'+' .
  504.             str_repeat('-'$this->_padding);
  505.  
  506.         return $row_begin implode($implode_char$return$row_end;
  507.     }
  508.  
  509.     /**
  510.      * Returns header line for the table.
  511.      */
  512.     function _getHeaderLine()
  513.     {
  514.         // Make sure column count is correct
  515.         for ($i = 0;  $i $this->_max_cols$i++{
  516.             if (!isset($this->_headers[$i])) {
  517.                 $this->_headers[$i'';
  518.             }
  519.         }
  520.  
  521.         for ($i = 0; $i count($this->_headers)$i++{
  522.             if ($this->_strlen($this->_headers[$i]$this->_cell_lengths[$i]{
  523.                 $this->_headers[$istr_pad($this->_headers[$i],
  524.                                               $this->_cell_lengths[$i],
  525.                                               ' ',
  526.                                               $this->_col_align[$i]);
  527.             }
  528.         }
  529.  
  530.         $row_begin    '|' str_repeat(' '$this->_padding);
  531.         $row_end      str_repeat(' '$this->_padding'|';
  532.         $implode_char str_repeat(' '$this->_padding'|' .
  533.             str_repeat(' '$this->_padding);
  534.  
  535.         $return[$this->_getSeparator();
  536.         $return[$row_begin implode($implode_char$this->_headers.
  537.             $row_end;
  538.  
  539.         return implode("\r\n"$return);
  540.     }
  541.  
  542.     /**
  543.      * Update max cols/rows.
  544.      */
  545.     function _updateRowsCols($rowdata = null)
  546.     {
  547.         // Update max cols
  548.         $this->_max_cols max($this->_max_colscount($rowdata));
  549.  
  550.         // Update max rows
  551.         ksort($this->_data);
  552.         $keys array_keys($this->_data);
  553.         $this->_max_rows end($keys+ 1;
  554.  
  555.         switch ($this->_defaultAlign{
  556.             case CONSOLE_TABLE_ALIGN_CENTER$pad = STR_PAD_BOTH; break;
  557.             case CONSOLE_TABLE_ALIGN_RIGHT:  $pad = STR_PAD_LEFT; break;
  558.             default:                         $pad = STR_PAD_RIGHT; break;
  559.         }
  560.  
  561.         // Set default column alignments
  562.         for ($i count($this->_col_align)$i $this->_max_cols$i++{
  563.             $this->_col_align[$i$pad;
  564.         }
  565.     }
  566.  
  567.     /**
  568.      * This function given a row of data will calculate the max length for
  569.      * each column and store it in the _cell_lengths array.
  570.      *
  571.      * @param array $row  The row data.
  572.      */
  573.     function _calculateCellLengths($row)
  574.     {
  575.         for ($i = 0; $i count($row)$i++{
  576.             if (!isset($this->_cell_lengths[$i])) {
  577.                 $this->_cell_lengths[$i= 0;
  578.             }
  579.             $this->_cell_lengths[$imax(isset($this->_headers[$i]$this->_strlen($this->_headers[$i]: 0,
  580.                                            $this->_cell_lengths[$i],
  581.                                            $this->_strlen($row[$i]));
  582.         }
  583.     }
  584.  
  585.     /**
  586.      * This function given a row of data will calculate the max height for all
  587.      * columns and store it in the _row_heights array.
  588.      *
  589.      * @param integer $row_number  The row number.
  590.      * @param array $row           The row data.
  591.      */
  592.     function _calculateRowHeight($row_number$row)
  593.     {
  594.         if (!isset($this->_row_heights[$row_number])) {
  595.             $this->_row_heights[$row_number= 1;
  596.         }
  597.  
  598.         // Do not process horizontal rule rows.
  599.         if ($row == CONSOLE_TABLE_HORIZONTAL_RULE{
  600.             return;
  601.         }
  602.  
  603.         for ($i = 0; $i count($row)$i++{
  604.             $lines preg_split('/\r?\n|\r/'$row[$i]);
  605.             $this->_row_heights[$row_numbermax($this->_row_heights[$row_number],
  606.                                                    count($lines));
  607.         }
  608.     }
  609.  
  610.     /**
  611.      * Returns the character length of a string.
  612.      *
  613.      * @param string $str  A multibyte or singlebyte string.
  614.      *
  615.      * @return integer  The string length.
  616.      */
  617.     function _strlen($str)
  618.     {
  619.         static $mbstring$utf8;
  620.  
  621.         // Cache expensive function_exists() calls.
  622.         if (!isset($mbstring)) {
  623.             $mbstring function_exists('mb_strlen');
  624.         }
  625.         if (!isset($utf8)) {
  626.             $utf8 function_exists('utf8_decode');
  627.         }
  628.  
  629.         if ($utf8 &&
  630.             ($this->_charset == strtolower('utf-8'||
  631.              $this->_charset == strtolower('utf8'))) {
  632.             return strlen(utf8_decode($str));
  633.         }
  634.         if ($mbstring{
  635.             return mb_strlen($str$this->_charset);
  636.         }
  637.  
  638.         return strlen($str);
  639.     }
  640.  
  641. }

Documentation generated on Mon, 11 Mar 2019 14:38:55 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.