Skip to content

Commit

Permalink
[Fix] Str::Mask() for consecutively repeating chars (laravel#42295)
Browse files Browse the repository at this point in the history
- Add some additional test cases to verify behaviour for
  more than 2 repeating characters.
- Add some cases for testing the masking from the start of
  the string, before the start of the string and end of string.

(cherry picked from commit a917528)
  • Loading branch information
sjokkateer authored and BrandonSurowiec committed Jun 26, 2022
1 parent e630199 commit 08eb155
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
14 changes: 11 additions & 3 deletions src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -437,10 +437,18 @@ public static function mask($string, $character, $index, $length = null, $encodi
return $string;
}

$start = mb_substr($string, 0, mb_strpos($string, $segment, 0, $encoding), $encoding);
$end = mb_substr($string, mb_strpos($string, $segment, 0, $encoding) + mb_strlen($segment, $encoding));
$strlen = mb_strlen($string, $encoding);
$startIndex = $index;

return $start.str_repeat(mb_substr($character, 0, 1, $encoding), mb_strlen($segment, $encoding)).$end;
if ($index < 0) {
$startIndex = $index < -$strlen ? 0 : $strlen + $index;
}

$start = mb_substr($string, 0, $startIndex, $encoding);
$segmentLen = mb_strlen($segment, $encoding);
$end = mb_substr($string, $startIndex + $segmentLen);

return $start.str_repeat(mb_substr($character, 0, 1, $encoding), $segmentLen).$end;
}

/**
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,19 @@ public function testMask()

$this->assertSame('这是一***', Str::mask('这是一段中文', '*', 3));
$this->assertSame('**一段中文', Str::mask('这是一段中文', '*', 0, 2));

$this->assertSame('ma*[email protected]', Str::mask('[email protected]', '*', 2, 1));
$this->assertSame('ma***email.com', Str::mask('[email protected]', '*', 2, 3));
$this->assertSame('ma************', Str::mask('[email protected]', '*', 2));

$this->assertSame('mari*@email.com', Str::mask('[email protected]', '*', 4, 1));
$this->assertSame('tamar*@email.com', Str::mask('[email protected]', '*', 5, 1));

$this->assertSame('*[email protected]', Str::mask('[email protected]', '*', 0, 1));
$this->assertSame('[email protected]*', Str::mask('[email protected]', '*', -1, 1));
$this->assertSame('[email protected]*', Str::mask('[email protected]', '*', -1));
$this->assertSame('***************', Str::mask('[email protected]', '*', -15));
$this->assertSame('***************', Str::mask('[email protected]', '*', 0));
}

public function testMatch()
Expand Down

0 comments on commit 08eb155

Please sign in to comment.