You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

55 lines
1.6 KiB

<?php
use Sirprize\PostalCodeValidator\Validator;
use Sirprize\PostalCodeValidator\ValidationException;
class Postalcodechecker extends Validator {
public function isValid(string $countryCode, string $postalCode, bool $ignoreSpaces = false): bool
{
if(!isset($this->formats[$countryCode]))
{
throw new ValidationException(sprintf('Invalid country code: "%s"', $countryCode));
}
foreach($this->formats[$countryCode] as $format)
{
#echo $postalCode . ' - ' . $this->getCustomFormatPattern($format)."\n";
if(preg_match($this->getCustomFormatPattern($format, $ignoreSpaces, $countryCode), $postalCode))
{
return true;
}
}
if(!count($this->formats[$countryCode]))
{
return true;
}
return false;
}
protected function getCustomFormatPattern($format, $ignoreSpaces = false, $countryCode)
{
$rgx = '[a-zA-Z0-9]';
/*
* Compliance to Redmine Ticket https://redmine.wylog.com/issues/36388
* 1. For country "France", it should only accept digits.
* 2. For other countries other than France, any characters must be accepted
*/
if (in_array($countryCode, ["FR", "FX"]))
{
$rgx = '\d';
}
$pattern = str_replace('#', $rgx, $format);
$pattern = str_replace('@', '[a-zA-Z0-9]', $pattern);
$pattern = str_replace('*', '[a-zA-Z0-9]', $pattern);
if ($ignoreSpaces)
{
$pattern = str_replace(' ', ' ?', $pattern);
}
return '/^' . $pattern . '$/';
}
}