Created
November 2, 2012 17:35
-
-
Save jubianchi/4002978 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace PMSIpilot\Bundle\StambiaTestBundle\Console\Helper; | |
use Symfony\Component\Console\Helper\Helper; | |
class TableFormatterHelper extends Helper | |
{ | |
/** | |
* @return string | |
*/ | |
public function getName() | |
{ | |
return 'table'; | |
} | |
public function formatTable(array $rows) | |
{ | |
$columnsLength = $this->computeColumnsLength($rows); | |
$separator = '+'; | |
foreach(current($rows) as $column => $cell) { | |
$separator .= str_repeat('-', $columnsLength[$column] + 2) . '+'; | |
} | |
$separator .= PHP_EOL; | |
$table = $this->formatHeader(array_shift($rows), $separator, $columnsLength); | |
foreach($rows as $row) { | |
$table .= $this->formatRow($row, $columnsLength) . PHP_EOL . $separator; | |
} | |
return $table; | |
} | |
protected function formatHeader(array $row, $separator, $columnsLength) { | |
return $separator . $this->formatRow($row, $columnsLength, 'comment') . PHP_EOL . $separator; | |
} | |
protected function formatRow(array $cells, $columnsLength, $style = null) { | |
$row = '| '; | |
foreach($cells as $column => $cell) { | |
$length = $columnsLength[$column]; | |
if(null !== $style) { | |
$cell = sprintf('<%1$s>%2$' . $length . 's</%1$s>', $style, $cell); | |
} | |
$row .= sprintf('%'. $length .'s', $cell) . ' | '; | |
} | |
return $row; | |
} | |
protected function computeColumnsLength(array $rows) { | |
$lengths = array(); | |
foreach($rows as $row) { | |
foreach($row as $column => $cell) { | |
if(true === isset($lengths[$column])) { | |
$lengths[$column] = strlen($cell) > $lengths[$column] ? strlen($cell) : $lengths[$column]; | |
} else { | |
$lengths[$column] = strlen($cell); | |
} | |
} | |
} | |
return $lengths; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment