diff --git a/src/Shell/Helper/TableHelper.php b/src/Shell/Helper/TableHelper.php index d6140ba175d..60132ae0854 100644 --- a/src/Shell/Helper/TableHelper.php +++ b/src/Shell/Helper/TableHelper.php @@ -43,8 +43,8 @@ protected function _calculateWidths($rows) { $widths = []; foreach ($rows as $line) { - foreach ($line as $k => $v) { - $columnLength = mb_strwidth($line[$k]); + foreach (array_values($line) as $k => $v) { + $columnLength = mb_strwidth($v); if ($columnLength >= (isset($widths[$k]) ? $widths[$k] : 0)) { $widths[$k] = $columnLength; } @@ -85,7 +85,7 @@ protected function _render(array $row, $widths, $options = []) } $out = ''; - foreach ($row as $i => $column) { + foreach (array_values($row) as $i => $column) { $pad = $widths[$i] - mb_strwidth($column); if (!empty($options['style'])) { $column = $this->_addStyle($column, $options['style']); @@ -99,6 +99,9 @@ protected function _render(array $row, $widths, $options = []) /** * Output a table. * + * Data will be output based on the order of the values + * in the array. The keys will not be used to align data. + * * @param array $rows The data to render out. * @return void */ diff --git a/tests/TestCase/Shell/Helper/TableHelperTest.php b/tests/TestCase/Shell/Helper/TableHelperTest.php index 120c9b8c9e2..3b30feb3330 100644 --- a/tests/TestCase/Shell/Helper/TableHelperTest.php +++ b/tests/TestCase/Shell/Helper/TableHelperTest.php @@ -58,7 +58,7 @@ public function setUp() * * @return void */ - public function testDefaultOutput() + public function testOutputDefaultOutput() { $data = [ ['Header 1', 'Header', 'Long Header'], @@ -77,10 +77,40 @@ public function testDefaultOutput() $this->assertEquals($expected, $this->stub->messages()); } + /** + * Test output with inconsistent keys. + * + * When outputting entities or other structured data, + * headers shouldn't need to have the same keys as it is + * annoying to use. + * + * @return void + */ + public function testOutputInconsistentKeys() + { + $data = [ + ['Header 1', 'Header', 'Long Header'], + ['a' => 'short', 'b' => 'Longish thing', 'c' => 'short'], + ['c' => 'Longer thing', 'a' => 'short', 'b' => 'Longest Value'], + ]; + $this->helper->output($data); + $expected = [ + '+--------------+---------------+---------------+', + '| Header 1 | Header | Long Header |', + '+--------------+---------------+---------------+', + '| short | Longish thing | short |', + '| Longer thing | short | Longest Value |', + '+--------------+---------------+---------------+', + ]; + $this->assertEquals($expected, $this->stub->messages()); + } + /** * Test that output works when data contains just empty strings. + * + * @return void */ - public function testEmptyStrings() + public function testOutputEmptyStrings() { $data = [ ['Header 1', 'Header', 'Empty'],