File tree Expand file tree Collapse file tree 3 files changed +96
-0
lines changed Expand file tree Collapse file tree 3 files changed +96
-0
lines changed Original file line number Diff line number Diff line change 11
11
],
12
12
"require" : {
13
13
"php" : " ^8.1" ,
14
+ "giggsey/libphonenumber-for-php" : " ^8.13" ,
14
15
"laravel/framework" : " ^9.0|^10.0"
15
16
},
16
17
"require-dev" : {
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace DescomMarket \Common \Parsers ;
4
+
5
+ use Exception ;
6
+ use libphonenumber \PhoneNumberFormat ;
7
+ use libphonenumber \PhoneNumberUtil ;
8
+
9
+ final class MobileNumberParser
10
+ {
11
+ private static $ defaultRegion = 'ES ' ;
12
+
13
+ public static function parse (string $ mobile ): ?string
14
+ {
15
+ $ phoneUtil = PhoneNumberUtil::getInstance ();
16
+
17
+ try {
18
+ $ phoneNumber = $ phoneUtil ->parse ($ mobile , static ::$ defaultRegion );
19
+
20
+ $ mobileE164 = $ phoneUtil ->format ($ phoneNumber , PhoneNumberFormat::E164 );
21
+
22
+ if (method_exists (static ::class, 'validate ' . static ::$ defaultRegion )) {
23
+ $ validateMethod = 'validate ' . static ::$ defaultRegion ;
24
+
25
+ if (! static ::$ validateMethod ($ mobileE164 )) {
26
+ return null ;
27
+ }
28
+ }
29
+
30
+ return $ mobileE164 ;
31
+ } catch (Exception $ e ) {
32
+ return null ;
33
+ }
34
+ }
35
+
36
+ private static function validateES (string $ mobileE164 ): bool
37
+ {
38
+ $ length = strlen ($ mobileE164 );
39
+
40
+ if ($ length !== 12 ) {
41
+ return false ;
42
+ }
43
+
44
+ $ prefix = substr ($ mobileE164 , 0 , 4 );
45
+
46
+ if ($ prefix !== '+346 ' && $ prefix !== '+347 ' ) {
47
+ return false ;
48
+ }
49
+
50
+ return true ;
51
+ }
52
+ }
Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace DescomMarket \Common \Tests \Feature \Parsers ;
4
+
5
+ use DescomMarket \Common \Parsers \MobileNumberParser ;
6
+ use DescomMarket \Common \Tests \TestCase ;
7
+
8
+ class MobileNumberParserTest extends TestCase
9
+ {
10
+ public function testParseValid ()
11
+ {
12
+ $ test = collect ([
13
+ '666666666 ' => '+34666666666 ' ,
14
+ '766666666 ' => '+34766666666 ' ,
15
+ '666 666 666 ' => '+34666666666 ' ,
16
+ '34666-666-666 ' => '+34666666666 ' ,
17
+ '+34666 666-666 ' => '+34666666666 ' ,
18
+ '0034666-666 666 ' => '+34666666666 ' ,
19
+ ]);
20
+
21
+ $ test ->each (function ($ expected , $ mobile ) {
22
+ $ parsedMobile = MobileNumberParser::parse ($ mobile );
23
+
24
+ $ this ->assertEquals ($ expected , $ parsedMobile );
25
+ });
26
+ }
27
+
28
+ public function testParseInvalid ()
29
+ {
30
+ $ test = collect ([
31
+ 'aa ' ,
32
+ '61234567 ' ,
33
+ '6123456789 ' ,
34
+ '812345678 ' ,
35
+ ]);
36
+
37
+ $ test ->each (function ($ mobile ) {
38
+ $ parsedMobile = MobileNumberParser::parse ($ mobile );
39
+
40
+ $ this ->assertNull ($ parsedMobile );
41
+ });
42
+ }
43
+ }
You can’t perform that action at this time.
0 commit comments