From 4b903c45e5d5bb2a788db3715e478afa43740cf2 Mon Sep 17 00:00:00 2001 From: wallacemaxters Date: Sun, 9 Jun 2024 00:22:52 -0300 Subject: [PATCH] Improve tests and add compatibility with utf-8 --- src/Masker.php | 11 +++++++++-- tests/MaskerTest.php | 26 +++++++++++++++++--------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/Masker.php b/src/Masker.php index b63cd2c..1b3c152 100644 --- a/src/Masker.php +++ b/src/Masker.php @@ -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) { @@ -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] ?? []; + } } diff --git a/tests/MaskerTest.php b/tests/MaskerTest.php index e32234b..db920a9 100644 --- a/tests/MaskerTest.php +++ b/tests/MaskerTest.php @@ -3,6 +3,7 @@ namespace Tests; use Exception; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Throwable; use WallaceMaxters\Masker\Masker; @@ -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() @@ -76,7 +85,6 @@ public function testMaskException() enableExceptions: true ); - try { $masker->mask('ABC', 'A-AA-00000'); throw new Exception('Unexpected');