[Console] added the possibility to insert a table separator anywhere in a table output

This commit is contained in:
Fabien Potencier 2014-03-03 13:41:09 +01:00
parent 39c495f814
commit 14caaec5f6
3 changed files with 73 additions and 2 deletions

View File

@ -158,8 +158,18 @@ class Table
return $this;
}
public function addRow(array $row)
public function addRow($row)
{
if ($row instanceof TableSeparator) {
$this->rows[] = $row;
return;
}
if (!is_array($row)) {
throw new InvalidArgumentException('A row must be an array or a TableSeparator instance.');
}
$this->rows[] = array_values($row);
$keys = array_keys($this->rows);
@ -217,7 +227,11 @@ class Table
$this->renderRowSeparator();
}
foreach ($this->rows as $row) {
$this->renderRow($row, $this->style->getCellRowFormat());
if ($row instanceof TableSeparator) {
$this->renderRowSeparator();
} else {
$this->renderRow($row, $this->style->getCellRowFormat());
}
}
if (!empty($this->rows)) {
$this->renderRowSeparator();
@ -337,6 +351,10 @@ class Table
$lengths = array($this->getCellWidth($this->headers, $column));
foreach ($this->rows as $row) {
if ($row instanceof TableSeparator) {
continue;
}
$lengths[] = $this->getCellWidth($row, $column);
}

View File

@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Helper;
/**
* Marks a row as being a separator.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TableSeparator
{
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Console\Tests\Helper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\TableStyle;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Output\StreamOutput;
class TableTest extends \PHPUnit_Framework_TestCase
@ -306,6 +307,37 @@ TABLE;
. Bar .
.......
TABLE;
$this->assertEquals($expected, $this->getOutputContent($output));
}
public function testRowSeparator()
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('Foo'))
->setRows(array(
array('Bar1'),
new TableSeparator(),
array('Bar2'),
new TableSeparator(),
array('Bar3'),
));
$table->render();
$expected =
<<<TABLE
+------+
| Foo |
+------+
| Bar1 |
+------+
| Bar2 |
+------+
| Bar3 |
+------+
TABLE;
$this->assertEquals($expected, $this->getOutputContent($output));