Skip to content

Instantly share code, notes, and snippets.

@dinos80152
Last active August 29, 2015 14:28
Show Gist options
  • Save dinos80152/917deb13e47a09a8fe68 to your computer and use it in GitHub Desktop.
Save dinos80152/917deb13e47a09a8fe68 to your computer and use it in GitHub Desktop.
A little bit functional
<?php
namespace App\Validators;
class MobileValidator
{
public function validate($attribute, $number, $countries)
{
try {
$number = (int)$number;
foreach ($countries as $country) {
$func_name = 'is' . ucfirst($country) . 'Mobile';
$bool = call_user_func([$this, $func_name], $number);
if ($bool) {
return $number;
}
}
return false;
} catch (MethodNotFoundException $e) {
throw new Exception($e);
}
}
private function isTWMobile($number)
{
$is_mobile_func = $this->isMobileFunc(9, 9);
return $is_mobile_func($number);
}
private function isHKMobile($number)
{
$mobile_prefix_numbers = [5, 6, 9];
$is_mobile_func = $this->isMobileFunc(8, $mobile_prefix_numbers);
return $is_mobile_func($number);
}
private function isMacauMobile($number)
{
$is_mobile_func = $this->isMobileFunc(8, 6);
return $is_mobile_func($number);
}
private function isMobileFunc($number_length, $number_prefix)
{
if (is_array($number_prefix)) {
$is_prefix_func = $this->isPrefixByArrayFunc($number_prefix);
} else {
$is_prefix_func = $this->isPrefixByIntFunc($number_prefix);
}
return function($number) use ($number_length, $is_prefix_func) {
if (strlen($number) === $number_length && $is_prefix_func($number)) {
return true;
} else {
return false;
}
};
}
private function isPrefixByArrayFunc($number_prefix)
{
return function($number) use ($number_prefix) {
return in_array(substr($number, 0, 1), $number_prefix);
};
}
private function isPrefixByIntFunc($number_prefix)
{
return function($number) use ($number_prefix) {
return (int)substr($number, 0, 1) === $number_prefix;
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment