Skip to content

Commit

Permalink
Merge pull request wp-cli#11 from goldenapples/thanj/table-output
Browse files Browse the repository at this point in the history
Add isPiped() method to \cli\Table
  • Loading branch information
jlogsdon committed Sep 15, 2012
2 parents b9946d1 + 90e2f7c commit 6bc4bfd
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions lib/cli/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ class Table {
protected $_width = array();
protected $_rows = array();

/**
* Checks whether the output of the current script is a TTY or a pipe / redirect
*
* Returns true if STDOUT output is being redirected to a pipe or a file; false is
* output is being sent directly to the terminal.
*
* @return bool
*/
protected function isPiped() {
return ( function_exists( 'posix_isatty' ) && !posix_isatty( STDOUT ) );
}

/**
* Initializes the `Table` class.
*
Expand Down Expand Up @@ -73,6 +85,11 @@ protected function checkRow(array $row) {
/**
* Output the table to `STDOUT` using `cli\line()`.
*
* If STDOUT is a pipe or redirected to a file, should output simple
* tab-separated text. Otherwise, renders table with ASCII table borders
*
* @uses cli\Table::isPiped() Determine what format to output
*
* @see cli\Table::renderRow()
*/
public function display() {
Expand All @@ -81,6 +98,14 @@ public function display() {
$borderStr .= '-' . str_repeat('-', $this->_width[$column]) . '-+';
}

if ( $this->isPiped() ) {
\cli\line($this->renderPipedRow($this->_headers));
foreach ($this->_rows as $row) {
\cli\line($this->renderPipedRow($row));
}
return;
}

\cli\line($borderStr);
\cli\line($this->renderRow($this->_headers));
\cli\line($borderStr);
Expand All @@ -106,6 +131,16 @@ protected function renderRow(array $row) {
return $render;
}

/**
* Renders a row for piped output.
*
* @param array $row The table row.
* @return string The formatted table row.
*/
protected function renderPipedRow(array $row) {
return implode( "\t", array_values( $row ) );
}

/**
* Sort the table by a column. Must be called before `cli\Table::display()`.
*
Expand Down

0 comments on commit 6bc4bfd

Please sign in to comment.