Skip to content

Commit d7ccbb0

Browse files
committed
tableformatter: correctly pad multibyte strings
1 parent 7f73f3c commit d7ccbb0

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/TableFormatter.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ public function format($columns, $texts, $colors = array())
198198
} else {
199199
$val = '';
200200
}
201-
$chunk = sprintf('%-' . $width . 's', $val);
201+
$chunk = $this->pad($val, $width);
202202
if (isset($colors[$col]) && $colors[$col]) {
203203
$chunk = $this->colors->wrap($chunk, $colors[$col]);
204204
}
@@ -215,6 +215,22 @@ public function format($columns, $texts, $colors = array())
215215

216216
}
217217

218+
/**
219+
* Pad the given string to the correct length
220+
*
221+
* @param string $string
222+
* @param int $len
223+
* @return string
224+
*/
225+
protected function pad($string, $len)
226+
{
227+
$strlen = $this->strlen($string);
228+
if ($strlen > $len) return $string;
229+
230+
$pad = $len - $strlen;
231+
return $string . str_pad('', $pad, ' ');
232+
}
233+
218234
/**
219235
* Measures char length in UTF-8 when possible
220236
*

tests/TableFormatterTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,15 @@ public function test_wrap()
9595

9696
}
9797

98+
public function test_lenght()
99+
{
100+
$text = "this is häppy ☺";
101+
$expect = "this is häppy ☺ |test";
102+
103+
$tf = new TableFormatter();
104+
$tf->setBorder('|');
105+
$result = $tf->format([20, '*'], [$text, 'test']);
106+
107+
$this->assertEquals($expect, trim($result));
108+
}
98109
}

0 commit comments

Comments
 (0)