Skip to content

Commit

Permalink
Add parser mobile (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
cesargb authored Oct 3, 2023
1 parent 5245252 commit 8336f87
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
],
"require": {
"php": "^8.1",
"giggsey/libphonenumber-for-php": "^8.13",
"laravel/framework": "^9.0|^10.0"
},
"require-dev": {
Expand Down
52 changes: 52 additions & 0 deletions src/Parsers/MobileNumberParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

namespace DescomMarket\Common\Parsers;

use Exception;
use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

final class MobileNumberParser
{
private static $defaultRegion = 'ES';

public static function parse(string $mobile): ?string
{
$phoneUtil = PhoneNumberUtil::getInstance();

try {
$phoneNumber = $phoneUtil->parse($mobile, static::$defaultRegion);

$mobileE164 = $phoneUtil->format($phoneNumber, PhoneNumberFormat::E164);

if (method_exists(static::class, 'validate' . static::$defaultRegion)) {
$validateMethod = 'validate' . static::$defaultRegion;

if (! static::$validateMethod($mobileE164)) {
return null;
}
}

return $mobileE164;
} catch (Exception $e) {
return null;
}
}

private static function validateES(string $mobileE164): bool
{
$length = strlen($mobileE164);

if ($length !== 12) {
return false;
}

$prefix = substr($mobileE164, 0, 4);

if ($prefix !== '+346' && $prefix !== '+347') {
return false;
}

return true;
}
}
43 changes: 43 additions & 0 deletions tests/Feature/Parsers/MobileNumberParserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace DescomMarket\Common\Tests\Feature\Parsers;

use DescomMarket\Common\Parsers\MobileNumberParser;
use DescomMarket\Common\Tests\TestCase;

class MobileNumberParserTest extends TestCase
{
public function testParseValid()
{
$test = collect([
'666666666' => '+34666666666',
'766666666' => '+34766666666',
'666 666 666' => '+34666666666',
'34666-666-666' => '+34666666666',
'+34666 666-666' => '+34666666666',
'0034666-666 666' => '+34666666666',
]);

$test->each(function ($expected, $mobile) {
$parsedMobile = MobileNumberParser::parse($mobile);

$this->assertEquals($expected, $parsedMobile);
});
}

public function testParseInvalid()
{
$test = collect([
'aa',
'61234567',
'6123456789',
'812345678',
]);

$test->each(function ($mobile) {
$parsedMobile = MobileNumberParser::parse($mobile);

$this->assertNull($parsedMobile);
});
}
}

0 comments on commit 8336f87

Please sign in to comment.