Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Symfony/Component/Console/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

3.1.0
-----

* added truncate method to FormatterHelper

2.8.0
-----

Expand Down
24 changes: 24 additions & 0 deletions src/Symfony/Component/Console/Helper/FormatterHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ public function formatBlock($messages, $style, $large = false)
return implode("\n", $messages);
}

/**
* Truncates a message to the given length.
*
* @param string $message
* @param int $length
* @param string $suffix
*
* @return string
*/
public function truncate($message, $length, $suffix = '...')
{
$computedLength = $length - $this->strlen($suffix);

if ($computedLength > $this->strlen($message)) {
return $message;
}

if (false === $encoding = mb_detect_encoding($message, null, true)) {
return substr($message, 0, $length).$suffix;
}

return mb_substr($message, 0, $length, $encoding).$suffix;
}

/**
* {@inheritdoc}
*/
Expand Down
36 changes: 36 additions & 0 deletions src/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,40 @@ public function testFormatBlockLGEscaping()
'::formatBlock() escapes \'<\' chars'
);
}

public function testTruncatingWithShorterLengthThanMessageWithSuffix()
{
$formatter = new FormatterHelper();
$message = 'testing truncate';

$this->assertSame('test...', $formatter->truncate($message, 4));
$this->assertSame('testing truncat...', $formatter->truncate($message, 15));
$this->assertSame('testing truncate...', $formatter->truncate($message, 16));
$this->assertSame('zażółć gęślą...', $formatter->truncate('zażółć gęślą jaźń', 12));
}

public function testTruncatingMessageWithCustomSuffix()
{
$formatter = new FormatterHelper();
$message = 'testing truncate';

$this->assertSame('test!', $formatter->truncate($message, 4, '!'));
}

public function testTruncatingWithLongerLengthThanMessageWithSuffix()
{
$formatter = new FormatterHelper();
$message = 'test';

$this->assertSame($message, $formatter->truncate($message, 10));
}

public function testTruncatingWithNegativeLength()
{
$formatter = new FormatterHelper();
$message = 'testing truncate';

$this->assertSame('testing tru...', $formatter->truncate($message, -5));
$this->assertSame('...', $formatter->truncate($message, -100));
}
}