Apache Zeta Components Manual :: File Source for table.php
Source for file table.php
Documentation is available at table.php
* File containing the ezcConsoleTable class.
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* @version //autogentag//
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* Creating tables to be printed to the console.
* Every ezcConsoleTable object can be accessed as if it was a multidimensional,
* numerically indexed array. The first dimension represents the rows of the
* table, so $table[0] gives you access to the first row of the table, which is
* represented by a {@link ezcConsoleTableRow} object. You can access its
* properties directly, using e.g. $table[0]->format. The second dimension gives
* you direct access to the cells of your table, like $table[0][0] accesses the
* first cell in the first row of your table. You can access its properties
* diretly here, too. This works like e.g. $table[0][0]->format. Table row and
* cell objects are created on the fly, when you access them for the first time.
* You can also create them as if you simply create new array elements. E.g.
* $table[] creates a new row in the table.
* // Initialize the console output handler
* $out = new ezcConsoleOutput();
* // Define a new format "headline"
* $out->formats->headline->color = 'red';
* $out->formats->headline->style = array( 'bold' );
* // Define a new format "sum"
* $out->formats->sum->color = 'blue';
* $out->formats->sum->style = array( 'negative' );
* $table = new ezcConsoleTable( $out, 60 );
* // Create first row and in it the first cell
* $table[0][0]->content = 'Headline 1';
* // Create 3 more cells in row 0
* for ( $i = 2; $i < 5; $i++ )
* $table[0][]->content = "Headline $i";
* $data = array( 1, 2, 3, 4 );
* // Create some more data in the table...
* foreach ( $data as $value )
* // Create a new row each time and set it's contents to the actual value
* $table[][0]->content = $value;
* // Set another border format for our headline row
* $table[0]->borderFormat = 'headline';
* // Set the content format for all cells of the 3rd row to "sum"
* $table[2]->format = 'sum';
* @property ezcConsoleTableOptions $options
* Contains the options for this class.
* Automatically wrap text to fit into a column.
* @see ezcConsoleTable::$options
* Do not wrap text. Columns will be extended to fit the largest text.
* ATTENTION: This is risky!
* @see ezcConsoleTable::$options
* Text will be cut to fit into a column.
* @see ezcConsoleTable::$options
* Align text in the default direction.
const ALIGN_DEFAULT = -
1;
* Align text in cells to the right.
const ALIGN_LEFT =
STR_PAD_RIGHT;
* Align text in cells to the left.
const ALIGN_RIGHT =
STR_PAD_LEFT;
* Align text in cells to the center.
const ALIGN_CENTER =
STR_PAD_BOTH;
* The width given by settings must be used even if the data allows it smaller.
* The width given by settings is a maximum value, if data allows it, the table gets smaller.
* Container to hold the properties
* @var array(string=>mixed)
* The ezcConsoleOutput object to use.
* Collection of the rows that are contained in the table.
* @var array(ezcConsoleTableRow)
* Tool object for multi-byte encoding safe string operations.
* @var ezcConsoleStringTool
* @param ezcConsoleOutput $outHandler Output handler to utilize
* @param int $width Overall width of the table (chars).
* @param array $options Options
* @see ezcConsoleTable::$options
* @throws ezcBaseValueException On an invalid setting.
public function __construct( ezcConsoleOutput $outHandler, $width, $options =
array() )
$this->stringTool =
new ezcConsoleStringTool();
$this->__set( 'width', $width );
* This method allows you to change the options of the table.
* @param ezcConsoleTableOptions $options The options to set.
* @throws ezcBaseSettingNotFoundException
* If you tried to set a non-existent option value.
* @throws ezcBaseSettingValueException
* If the value is not valid for the desired option.
* @throws ezcBaseValueException
* If you submit neither an array nor an instance of
* ezcConsoleTableOptions.
* Returns the current options.
* Returns the options currently set for this table.
* @return ezcConsoleTableOptions The current options.
* Returns the table in an array.
* Returns the entire table as an array of printable lines. Each element of
* the array represents a physical line of the drawn table, including all
* borders and stuff, so you can simply print the table using
* echo implode( "\n" , $table->getTable() ):
* which is basically what {@link ezcConsoleTable::outputTable()} does.
* @return array An array representation of the table.
return $this->generateTable();
* Prints the complete table to the console.
echo
implode( PHP_EOL, $this->generateTable() );
* Returns the table in a string.
return implode( PHP_EOL, $this->generateTable() );
* Returns if the given offset exists.
* This method is part of the ArrayAccess interface to allow access to the
* data of this object as if it was an array.
* @param int $offset The offset to check.
* @return bool True when the offset exists, otherwise false.
* @throws ezcBaseValueException
* If a non numeric row ID is requested.
if ( !is_int( $offset ) ||
$offset <
0 )
return isset
( $this->rows[$offset] );
// From here only interface method implementations follow, which are not intended for direct usage
* Returns the element with the given offset.
* This method is part of the ArrayAccess interface to allow access to the
* data of this object as if it was an array. In case of the
* ezcConsoleTable class this method always returns a valid row object
* since it creates them on the fly, if a given item does not exist.
* @param int $offset The offset to check.
* @return ezcConsoleTableCell
* @throws ezcBaseValueException
* If a non numeric row ID is requested.
$offset =
( $offset ===
null ) ?
count( $this->rows ) :
$offset;
if ( !is_int( $offset ) ||
$offset <
0 )
if ( !isset
( $this->rows[$offset] ) )
return $this->rows[$offset];
* Set the element with the given offset.
* This method is part of the ArrayAccess interface to allow access to the
* data of this object as if it was an array.
* @param int $offset The offset to assign an item to.
* @param ezcConsoleTableRow $value The row to assign.
* @throws ezcBaseValueException
* If a non numeric row ID is requested.
* @throws ezcBaseValueException
* If the provided value is not of type {@link ezcConsoleTableRow}.
$offset =
count( $this );
if ( !is_int( $offset ) ||
$offset <
0 )
$this->rows[$offset] =
$value;
* Unset the element with the given offset.
* This method is part of the ArrayAccess interface to allow access to the
* data of this object as if it was an array.
* @param int $offset The offset to unset the value for.
* @throws ezcBaseValueException
* If a non numeric row ID is requested.
if ( !is_int( $offset ) ||
$offset <
0 )
if ( isset
( $this->rows[$offset] ) )
unset
( $this->rows[$offset] );
* Returns the number of cells in the row.
* This method is part of the Countable interface to allow the usage of
* PHP's count() function to check how many cells this row has.
* @return int Number of cells in this row.
return count( $keys ) >
0 ?
( end( $keys ) +
1 ) :
0;
* Returns the currently selected cell.
* This method is part of the Iterator interface to allow access to the
* cells of this row by iterating over it like an array (e.g. using
* @return ezcConsoleTableCell The currently selected cell.
* Returns the key of the currently selected cell.
* This method is part of the Iterator interface to allow access to the
* cells of this row by iterating over it like an array (e.g. using
* @return int The key of the currently selected cell.
* Returns the next cell and selects it or false on the last cell.
* This method is part of the Iterator interface to allow access to the
* cells of this row by iterating over it like an array (e.g. using
* @return mixed ezcConsoleTableCell if the next cell exists, or false.
* Selects the very first cell and returns it.
* This method is part of the Iterator interface to allow access to the
* cells of this row by iterating over it like an array (e.g. using
* @return ezcConsoleTableCell The very first cell of this row.
* Returns if the current cell is valid.
* This method is part of the Iterator interface to allow access to the
* cells of this row by iterating over it like an array (e.g. using
* @return ezcConsoleTableCell The very first cell of this row.
* @param string $key Name of the property.
* @return mixed Value of the property or null.
* @throws ezcBasePropertyNotFoundException
* If the the desired property is not found.
public function __get( $key )
* @param string $key Name of the property.
* @param mixed $val The value for the property.
* @throws ezcBasePropertyNotFoundException
* If a the value for the property options is not an instance of
* @throws ezcBaseValueException
* If a the value for a property is out of range.
public function __set( $key, $val )
* @param string $key Name of the property.
* @return bool True is the property is set, otherwise false.
public function __isset( $key )
* Generate the complete table as an array.
* @return array(string) The table.
private function generateTable()
$colWidth =
$this->getColWidths();
if ( $this->options->lineVertical !==
null )
$table[] =
$this->generateBorder(
( isset
( $this[0] ) ?
$this[0]->borderFormat :
'default' )
// Rows submitted by the user
for ( $i =
0; $i <
count( $this->rows ); $i++
)
foreach ( $this->breakRows( $this->rows[$i], $colWidth ) as $brkRow =>
$brkCells )
$table[] =
$this->generateRow( $brkCells, $colWidth, $this->rows[$i] );
$afterBorderFormat = isset
( $this->rows[$i +
1] ) &&
$this->rows[$i +
1]->borderFormat !=
'default' ?
$this->rows[$i +
1]->borderFormat :
$this->rows[$i]->borderFormat;
if ( $this->options->lineVertical !==
null )
$table[] =
$this->generateBorder( $colWidth, $afterBorderFormat );
// Empty tables need closing border
if ( $this->options->lineVertical !==
null &&
count( $this->rows ) ==
null )
$table[] =
$this->generateBorder( $colWidth, 'default' );
* Generate top/bottom borders of rows.
* @param array(int) $colWidth Array of column width.
* @param string $format Format name.
* @return string The Border string.
private function generateBorder( $colWidth, $format )
foreach ( $colWidth as $col =>
$width )
$border .=
( $this->options->lineHorizontal !==
null ?
$this->properties['options']->corner :
'' )
$border .=
( $this->options->lineHorizontal !==
null ?
$this->properties['options']->corner :
'' );
return $this->formatText( $border, $format );
* Generate a single physical row.
* This method generates the string for a single physical table row.
* @param array(string) $cells Cells of the row.
* @param array(int) $colWidth Calculated columns widths.
* @param ezcConsoleTableRow $row The row to generate.
* @return string The row.
private function generateRow( $cells, $colWidth, $row )
for ( $cell =
0; $cell <
count( $colWidth ); $cell++
)
$align =
$this->determineAlign( $row, $cell );
$format =
$this->determineFormat( $row, $cell );
$borderFormat =
$this->determineBorderFormat( $row );
$data = isset
( $cells[$cell] ) ?
$cells[$cell] :
'';
$rowData .=
$this->formatText(
$rowData .=
$this->properties['options']->colPadding;
$rowData .=
$this->formatText(
$this->stringTool->strPad( $data, $colWidth[$cell], ' ', $align ),
$rowData .=
$this->properties['options']->colPadding;
$rowData .=
$this->formatText( $this->properties['options']->lineHorizontal, $row->borderFormat );
* Determine the alignment of a cell.
* Walks the inheritance path upwards to determine the alignment of a
* cell. Checks first, if the cell has it's own alignment (apart from
* ezcConsoleTable::ALIGN_DEFAULT). If not, checks the row for an
* alignment setting and uses the default alignment if not found.
* @param ezcConsoleTableRow $row The row this cell belongs to.
* @param int $cellId Index of the desired cell.
* @return int An alignement constant (ezcConsoleTable::ALIGN_*).
private function determineAlign( $row, $cellId =
0 )
* Determine the format of a cells content.
* Walks the inheritance path upwards to determine the format of a
* cells content. Checks first, if the cell has it's own format (apart
* from 'default'). If not, checks the row for a format setting and
* uses the default format if not found.
* @param ezcConsoleTableRow $row The row this cell belongs to.
* @param int $cellId Index of the desired cell.
* @return string A format name.
private function determineFormat( $row, $cellId )
return ( $row[$cellId]->format !=
'default'
:
( $row->format !==
'default'
:
$this->properties['options']->defaultFormat ) );
* Determine the format of a rows border.
* Walks the inheritance path upwards to determine the format of a
* rows border. Checks first, if the row has it's own format (apart
* from 'default'). If not, uses the default format.
* @param ezcConsoleTableRow $row The row this cell belongs to.
* @return string A format name.
private function determineBorderFormat( $row )
return $row->borderFormat !==
'default'
:
$this->properties['options']->defaultBorderFormat;
* Returns auto broken rows from an array of cells.
* The data provided by a user may not fit into a cell calculated by the
* class. In this case, the data can be automatically wrapped. The table
* row then spans over multiple physical console lines.
* @param array(string) $cells Array of cells in one row.
* @param array(int) $colWidth Columns widths array.
* @return array(string) Physical rows generated out of this row.
private function breakRows( $cells, $colWidth )
// Iterate through cells of the row
foreach ( $colWidth as $cell =>
$width )
$data =
$cells[$cell]->content;
// Physical row id, start with 0 for each row
// Split into multiple physical rows if manual breaks exist
$dataLines =
explode( "\n", $data );
foreach ( $dataLines as $dataLine )
// Does the physical row fit?
if ( iconv_strlen( $dataLine, 'UTF-8' ) >
( $colWidth[$cell] ) )
$this->stringTool->wordwrap( $dataLine, $colWidth[$cell], "\n", true )
foreach ( $subLines as $lineNo =>
$line )
$rows[$row++
][$cell] =
$line;
$rows[$row++
][$cell] =
iconv_substr( $dataLine, 0, $colWidth[$cell], 'UTF-8' );
$rows[$row++
][$cell] =
$dataLine;
$rows[$row++
][$cell] =
$dataLine;
* Determine width of each single column.
private function getColWidths()
// Determine number of columns:
foreach ( $this->rows as $row )
$colCount =
max( sizeof( $row ), $colCount );
return array( $this->width );
// Subtract border and padding chars from global width
$globalWidth =
$this->width
// Per column: 2 * border padding + 1 border
// Width of a column if each is made equal
$colNormWidth =
round( $globalWidth /
$colCount );
// Determine the longest data for each column
foreach ( $this->rows as $row =>
$cells )
foreach ( $cells as $col =>
$cell )
foreach ( explode( PHP_EOL, $cell->content ) as $contentRow )
$colMaxWidth[$col] = isset
( $colMaxWidth[$col] ) ?
max( $colMaxWidth[$col], $contentLength ) :
$contentLength;
$colWidthOverflow =
array();
foreach ( $colMaxWidth as $col =>
$maxWidth )
// Does the largest data of the column fit into the average size
// + what we have in spare from earlier columns?
if ( $maxWidth <=
( $colNormWidth +
$spareWidth ) )
// We fit in, make the column as large as necessary
$colWidth[$col] =
$maxWidth;
$spareWidth +=
( $colNormWidth -
$maxWidth );
// Does not fit, use maximal possible width
$colWidth[$col] =
$colNormWidth +
$spareWidth;
// Store overflow for second processing step
$colWidthOverflow[$col] =
$maxWidth -
$colWidth[$col];
// Do we have spare to give to the columns again?
// Second processing step
if ( count( $colWidthOverflow ) >
0 )
$overflowSum =
array_sum( $colWidthOverflow );
foreach ( $colWidthOverflow as $col =>
$overflow );
$colWidth[$col] +=
floor( $overflow /
$overflowSum *
$spareWidth );
foreach ( $colWidth as $col =>
$width )
$colWidth[$col] +=
floor( $width /
$widthSum *
$spareWidth );
// Finally sanitize values from rounding issues, if necessary
$colWidth[count( $colWidth ) -
1] -=
$colSum -
$globalWidth;
* Returns the given $text formatted with $format.
* In case $useFormats is set to false in the output handler, the text is
* returned as given, without any formatting.
private function formatText( $text, $format )