Skip to content

Commit

Permalink
[Fix] Str::Mask() for consecutively repeating chars (#42295) (#42956)
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)

Co-authored-by: Remy Bos <27890746+sjokkateer@users.noreply.github.com>
  • Loading branch information
BrandonSurowiec and sjokkateer authored Jun 27, 2022
1 parent 0131fd5 commit b32193b
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*n@email.com', Str::mask('maan@email.com', '*', 2, 1));
$this->assertSame('ma***email.com', Str::mask('maan@email.com', '*', 2, 3));
$this->assertSame('ma************', Str::mask('maan@email.com', '*', 2));

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

$this->assertSame('*aria@email.com', Str::mask('maria@email.com', '*', 0, 1));
$this->assertSame('maria@email.co*', Str::mask('maria@email.com', '*', -1, 1));
$this->assertSame('maria@email.co*', Str::mask('maria@email.com', '*', -1));
$this->assertSame('***************', Str::mask('maria@email.com', '*', -15));
$this->assertSame('***************', Str::mask('maria@email.com', '*', 0));
}

public function testMatch()
Expand Down

0 comments on commit b32193b

Please sign in to comment.