Skip to content

Commit

Permalink
Fixed string_shuffle function for unicode characters.
Browse files Browse the repository at this point in the history
  • Loading branch information
smuuf committed Jul 13, 2019
1 parent 64a1d5a commit 10ad8d6
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/extensions/psl/StringExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,20 @@
class StringExtension extends Extension {

public static function string_shuffle(StringValue $str): StringValue {
return new StringValue(str_shuffle((string) $str->value));

// str_shuffle() doesn't work with unicode, so let's do this ourselves.
$original = $str->value;
$length = mb_strlen($original);
$indices = range(0, $length - 1);
shuffle($indices);
$result = "";

while (($i = array_pop($indices)) !== null) {
$result .= mb_substr($original, $i, 1);
}

return new StringValue($result);

}

public static function string_length(StringValue $str): NumberValue {
Expand Down
7 changes: 7 additions & 0 deletions tests/unit/value.string.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,13 @@ Assert::same(2, get_val($fns['string_number_of']->invoke([$string, new StringVal
Assert::same(0, get_val($fns['string_number_of']->invoke([$string, new StringValue("xoxoxo")])));
Assert::same(0, get_val($fns['string_number_of']->invoke([$string, new NumberValue(1)])));

//
// Test shuffle.
//

Assert::same(17, mb_strlen(get_val($fns['string_shuffle']->invoke([$string]))));
Assert::same(17, mb_strlen(get_val($fns['string_shuffle']->invoke([$unicode]))));

//
// Test length.
//
Expand Down

0 comments on commit 10ad8d6

Please sign in to comment.