Skip to content

Commit 40b886d

Browse files
safe_strpad() should pad the string according to display needs
Because `safe_strlen()` gives us the string length for output, we need the true length to determine how much we should pad the string
1 parent 1770752 commit 40b886d

2 files changed

Lines changed: 17 additions & 10 deletions

File tree

lib/cli/cli.php

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,17 +195,20 @@ function safe_substr( $str, $start, $length = false ) {
195195
}
196196

197197
/**
198-
* An encoding-safe way of padding string length
198+
* An encoding-safe way of padding string length for display
199199
*
200200
* @param string $string The string to pad
201201
* @param int $length The length to pad it to
202202
* @return string
203203
*/
204204
function safe_str_pad( $string, $length ) {
205-
$real_length = safe_strlen($string);
206-
$show_length = Colors::length($string);
207-
$diff = strlen( $string ) - safe_strlen( $string );
208-
$length += $real_length - $show_length + $diff;
209-
210-
return str_pad($string, $length);
205+
if ( function_exists( 'mb_strwidth' ) ) {
206+
$real_length = mb_strwidth( $string, mb_detect_encoding( $string ) );
207+
} else {
208+
$real_length = safe_strlen( $string );
209+
}
210+
$show_length = Colors::length( $string );
211+
$diff = strlen( $string ) - $real_length;
212+
$length += $diff;
213+
return str_pad( $string, $length );
211214
}

tests/test-cli.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,13 @@ function test_encoded_string_length() {
2020
$this->assertEquals( \cli\Colors::length( 'óra' ), 3 );
2121
$this->assertEquals( \cli\Colors::length( '日本語' ), 3 );
2222

23-
$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( 'hello', 6 ) ), 6 );
24-
$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( 'óra', 6 ) ), 6 );
25-
$this->assertEquals( \cli\safe_strlen( \cli\Colors::pad( '日本語', 6 ) ), 6 );
23+
}
24+
25+
function test_encoded_string_pad() {
26+
27+
$this->assertEquals( 6, strlen( \cli\Colors::pad( 'hello', 6 ) ) );
28+
$this->assertEquals( 7, strlen( \cli\Colors::pad( 'óra', 6 ) ) ); // special characters take one byte
29+
$this->assertEquals( 9, strlen( \cli\Colors::pad( '日本語', 6 ) ) ); // each character takes two bytes
2630

2731
}
2832

0 commit comments

Comments
 (0)