| 1234567891011121314151617181920212223242526272829303132333435 |
- <?php
-
- namespace App\Support;
-
- /**
- * Turns Malaysian phone numbers as people type them ("012-345 6789", "+60 12 345 6789")
- * into the digits-only form WhatsApp links need ("60123456789").
- */
- final class MalaysianPhone
- {
- public static function normalize(?string $phone): ?string
- {
- $digits = preg_replace('/\D/', '', (string) $phone) ?? '';
-
- if (str_starts_with($digits, '0')) {
- // Local form: 012-345 6789.
- $digits = '6'.$digits;
- } elseif (str_starts_with($digits, '1') && strlen($digits) >= 9 && strlen($digits) <= 10) {
- // Mobile number typed without the leading 0: 12-345 6789.
- $digits = '60'.$digits;
- }
-
- // Anything else must already carry Malaysia's country code (60). Other countries are refused.
-
- return preg_match('/^60[1-9][0-9]{7,9}$/', $digits) === 1 ? $digits : null;
- }
-
- /**
- * A WhatsApp chat link, optionally with a message already typed in.
- */
- public static function whatsappLink(string $number, ?string $text = null): string
- {
- return 'https://wa.me/'.$number.($text !== null ? '?text='.rawurlencode($text) : '');
- }
- }
|