Skip to content

Commit c52f972

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

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

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

+26-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,29 @@ private function applyCurrentStyle(string $text, string $current, int $width, in
282282

283283
return implode("\n", $lines);
284284
}
285+
286+
private function addLineBreaks(string $text, int $width): string
287+
{
288+
$result = '';
289+
$line = '';
290+
$encoding = mb_detect_encoding($text, null, true);
291+
for ($i = 0; $i < mb_strlen($text, $encoding); ++$i) {
292+
$char = mb_substr($text, $i, 1, $encoding);
293+
if ('' === $line && ' ' === $char && ' ' !== mb_substr($text, $i + 1, 1, $encoding)) {
294+
continue;
295+
}
296+
$line .= $char;
297+
if ("\n" === $char) {
298+
$result .= $line;
299+
$line = '';
300+
} elseif ($width === mb_strlen($line)) {
301+
$result .= $line."\n";
302+
$line = '';
303+
}
304+
}
305+
306+
$result .= $line;
307+
308+
return $result;
309+
}
285310
}

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

+2
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,8 @@ 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));
386+
$this->assertSame("Â rèälly l\nöng tîtlè \nthät cöüld\nnèêd múltî\nplê\nlínès", $formatter->formatAndWrap("Â rèälly löng tîtlè thät cöüld nèêd múltîplê\n línès", 10));
385387
$this->assertSame('', $formatter->formatAndWrap(null, 5));
386388
}
387389
}

0 commit comments

Comments
 (0)