Skip to content

Commit

Permalink
Improve tests and add compatibility with utf-8
Browse files Browse the repository at this point in the history
  • Loading branch information
wallacemaxters committed Jun 9, 2024
1 parent 728f337 commit 4b903c4
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 11 deletions.
11 changes: 9 additions & 2 deletions src/Masker.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public function mask(?string $value, string $mask): string
$format = $this->convertToInternalFormat($mask);

try {
return sprintf($format, ...str_split($value));
return sprintf($format, ...$this->split($value));
} catch (ArgumentCountError) {

if ($this->enableExceptions) {
Expand Down Expand Up @@ -54,11 +54,18 @@ public function unmaskAsArray(?string $value, string $mask): ?array
return null;
}

protected function convertToInternalFormat(string $mask)
protected function convertToInternalFormat(string $mask): string
{
return strtr($mask, [
$this->numberPlaceholder => '%1d',
$this->characterPlaceholder => '%1s'
]);
}

protected function split(string $value): array
{
preg_match_all('/./u', $value, $matches);

return $matches[0] ?? [];
}
}
26 changes: 17 additions & 9 deletions tests/MaskerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Tests;

use Exception;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Throwable;
use WallaceMaxters\Masker\Masker;
Expand All @@ -11,19 +12,27 @@

class MaskerTest extends TestCase
{
public function testMask()
#[DataProvider('maskDataProvider')]
public function testMask(?string $value, string $expected, string $mask)
{
$masker = new Masker();

foreach ([
['31995451199', '(31) 99545-1199', '(00) 00000-0000'],
$this->assertEquals(
$expected,
$masker->mask($value, $mask),
"Ao usar o valor $value é esperado que a máscara $mask retorne $expected"
);
}

public static function maskDataProvider()
{
return [
['value' => '31995451199', 'expected' => '(31) 99545-1199', 'mask' => '(00) 00000-0000'],
['31995451199', '31995451199', '(00) 000000000000000000000'],
['31150150', '31.150-150', '00.000-000'],
[null, '', '(00) 0000-0000']
] as [$value, $expected, $mask]) {

$this->assertEquals($expected, $masker->mask($value, $mask), "Ao usar o valor $value é esperado que a máscara $mask retorne $expected");
}
'with null' => [null, '', '(00) 0000-0000'],
'Peão da Casa' => ['PeãodaCasaPrópria', 'Peão da Casa', 'mask'=> 'AAAA AA AAAA'],
];
}

public function testUmask()
Expand Down Expand Up @@ -76,7 +85,6 @@ public function testMaskException()
enableExceptions: true
);


try {
$masker->mask('ABC', 'A-AA-00000');
throw new Exception('Unexpected');
Expand Down

0 comments on commit 4b903c4

Please sign in to comment.