Skip to content

Commit ec4b7af

Browse files
committed
[Console] Fix linewraps in OutputFormatter
1 parent 2f1ba4c commit ec4b7af

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/Symfony/Component/Console/Formatter/OutputFormatter.php

+23-1
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ private function applyCurrentStyle(string $text, string $current, int $width, in
258258
}
259259

260260
preg_match('~(\\n)$~', $text, $matches);
261-
$text = $prefix.preg_replace('~([^\\n]{'.$width.'})\\ *~', "\$1\n", $text);
261+
$text = $prefix.$this->addLineBreaks($text, $width);
262262
$text = rtrim($text, "\n").($matches[1] ?? '');
263263

264264
if (!$currentLineLength && '' !== $current && "\n" !== substr($current, -1)) {
@@ -282,4 +282,26 @@ private function applyCurrentStyle(string $text, string $current, int $width, in
282282

283283
return implode("\n", $lines);
284284
}
285+
286+
private function addLineBreaks($string, $charsPerLine) {
287+
$result = '';
288+
289+
if (\function_exists('mb_detect_encoding') && false !== $encoding = mb_detect_encoding($string, null, true)) {
290+
for ($i = 0; $i < mb_strlen($string, $encoding); $i += $charsPerLine) {
291+
if(' ' === mb_substr($string, $i, 1, $encoding)) {
292+
++$i;
293+
}
294+
$result .= mb_substr($string, $i, $charsPerLine, $encoding)."\n";
295+
}
296+
} else {
297+
for ($i = 0; $i < \strlen($string); $i += $charsPerLine) {
298+
if(' ' === substr($string, $i, 1)) {
299+
++$i;
300+
}
301+
$result .= substr($string, $i, $charsPerLine)."\n";
302+
}
303+
}
304+
305+
return $result;
306+
}
285307
}

src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php

+1
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,7 @@ public function testFormatAndWrap()
382382
$this->assertSame("pre\nfoo\nbar\nbaz\npos\nt", $formatter->formatAndWrap('pre <error>foo bar baz</error> post', 3));
383383
$this->assertSame("pre \nfoo \nbar \nbaz \npost", $formatter->formatAndWrap('pre <error>foo bar baz</error> post', 4));
384384
$this->assertSame("pre f\noo ba\nr baz\npost", $formatter->formatAndWrap('pre <error>foo bar baz</error> post', 5));
385+
$this->assertSame("Â rèälly l\nöng tîtlè \nthät cöüld\nnèêd múltî\nplê línès", $formatter->formatAndWrap('Â rèälly löng tîtlè thät cöüld nèêd múltîplê línès', 10));
385386
$this->assertSame('', $formatter->formatAndWrap(null, 5));
386387
}
387388
}

0 commit comments

Comments
 (0)