2023-09-12 08:13:10 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Rules;
|
|
|
|
|
|
|
|
use Illuminate\Contracts\Validation\Rule;
|
|
|
|
use Illuminate\Support\Str;
|
|
|
|
|
|
|
|
class ValidPhoneInputRule implements Rule
|
|
|
|
{
|
2023-09-23 09:42:22 +00:00
|
|
|
|
2023-10-01 07:43:14 +00:00
|
|
|
public ?int $reason = 0;
|
2023-09-23 09:42:22 +00:00
|
|
|
|
2023-09-12 08:13:10 +00:00
|
|
|
public function passes($attribute, $value)
|
|
|
|
{
|
2023-10-03 15:50:46 +00:00
|
|
|
if (!is_string($value) || !$value) {
|
2023-09-12 08:13:10 +00:00
|
|
|
return false;
|
|
|
|
}
|
2023-09-20 10:14:08 +00:00
|
|
|
try {
|
2023-10-03 15:50:46 +00:00
|
|
|
if(ctype_alpha(substr($value, 0, 2))){ // First 2 will be country code
|
|
|
|
$value = substr($value, 2);
|
|
|
|
}
|
2023-09-20 10:14:08 +00:00
|
|
|
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
|
2023-09-23 09:42:22 +00:00
|
|
|
$phone = $phoneUtil->parse($value);
|
|
|
|
$this->reason = $phoneUtil->isPossibleNumberWithReason($phone);
|
|
|
|
return $this->reason === \libphonenumber\ValidationResult::IS_POSSIBLE;
|
2023-09-20 10:14:08 +00:00
|
|
|
} catch (\Exception $e) {
|
|
|
|
return false;
|
|
|
|
}
|
2023-09-12 08:13:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public function message()
|
|
|
|
{
|
2023-09-23 09:42:22 +00:00
|
|
|
return match ($this->reason) {
|
|
|
|
\libphonenumber\ValidationResult::IS_POSSIBLE => 'The :attribute is not valid for an unknown reason.',
|
|
|
|
\libphonenumber\ValidationResult::INVALID_COUNTRY_CODE => 'The :attribute does not have a valid country code.',
|
|
|
|
\libphonenumber\ValidationResult::TOO_SHORT => 'The :attribute is too short.',
|
|
|
|
\libphonenumber\ValidationResult::TOO_LONG => 'The :attribute is too long.',
|
|
|
|
\libphonenumber\ValidationResult::IS_POSSIBLE_LOCAL_ONLY => 'The :attribute is not a valid phone number (local number).',
|
|
|
|
\libphonenumber\ValidationResult::INVALID_LENGTH => 'The :attribute does not have a valid length.',
|
|
|
|
default => 'The :attribute is not a valid phone number.',
|
|
|
|
};
|
2023-09-12 08:13:10 +00:00
|
|
|
}
|
2023-09-23 09:42:22 +00:00
|
|
|
}
|