Browse Source

Fixed Shell TableHelper when there is a fullwidth character

Yasuo Harada 9 years ago
parent
commit
752c4d52ad
2 changed files with 27 additions and 3 deletions
  1. 3 3
      src/Shell/Helper/TableHelper.php
  2. 24 0
      tests/TestCase/Shell/Helper/TableHelperTest.php

+ 3 - 3
src/Shell/Helper/TableHelper.php

@@ -32,7 +32,7 @@ class TableHelper extends Helper
         'rowSeparator' => false,
         'headerStyle' => 'info',
     ];
-    
+
     /**
      * Calculate the column widths
      *
@@ -44,7 +44,7 @@ class TableHelper extends Helper
         $widths = [];
         foreach ($rows as $line) {
             foreach ($line as $k => $v) {
-                $columnLength = mb_strlen($line[$k]);
+                $columnLength = mb_strwidth($line[$k]);
                 if ($columnLength > (isset($widths[$k]) ? $widths[$k] : 0)) {
                     $widths[$k] = $columnLength;
                 }
@@ -86,7 +86,7 @@ class TableHelper extends Helper
 
         $out = '';
         foreach ($row as $i => $column) {
-            $pad = $widths[$i] - mb_strlen($column);
+            $pad = $widths[$i] - mb_strwidth($column);
             if (!empty($options['style'])) {
                 $column = $this->_addStyle($column, $options['style']);
             }

+ 24 - 0
tests/TestCase/Shell/Helper/TableHelperTest.php

@@ -88,6 +88,30 @@ class TableHelperTest extends TestCase
     }
 
     /**
+     * Test output with multi-byte characters
+     *
+     * @return void
+     */
+    public function testOutputFullwidth()
+    {
+        $data = [
+            ['Header 1', 'Head', 'Long Header'],
+            ['short', '竜頭蛇尾', 'short'],
+            ['Longer thing', 'longerish', 'Longest Value'],
+        ];
+        $this->helper->output($data);
+        $expected = [
+            '+--------------+-----------+---------------+',
+            '| <info>Header 1</info>     | <info>Head</info>      | <info>Long Header</info>   |',
+            '+--------------+-----------+---------------+',
+            '| short        | 竜頭蛇尾  | short         |',
+            '| Longer thing | longerish | Longest Value |',
+            '+--------------+-----------+---------------+',
+        ];
+        $this->assertEquals($expected, $this->stub->messages());
+    }
+
+    /**
      * Test output without headers
      *
      * @return void