protected validatePostalCode ( string $postalCode, array $subdivisions, |
||
$postalCode | string | The postal code. |
$subdivisions | array | An array of found valid subdivisions. |
$addressFormat | The address format. | |
$constraint | The constraint. |
protected function validatePostalCode($postalCode, array $subdivisions, AddressFormat $addressFormat, $constraint)
{
if (empty($postalCode) || !in_array(AddressField::POSTAL_CODE, $constraint->fields)) {
// Nothing to validate.
return;
}
// Resolve the available patterns.
$fullPattern = $addressFormat->getPostalCodePattern();
$startPattern = null;
foreach ($subdivisions as $subdivision) {
$pattern = $subdivision->getPostalCodePattern();
if (empty($pattern)) {
continue;
}
if ($subdivision->getPostalCodePatternType() == PatternType::FULL) {
$fullPattern = $pattern;
} else {
$startPattern = $pattern;
}
}
if ($fullPattern) {
// The pattern must match the provided value completely.
preg_match('/' . $fullPattern . '/i', $postalCode, $matches);
if (!isset($matches[0]) || $matches[0] != $postalCode) {
$this->addViolation(AddressField::POSTAL_CODE, $constraint->invalidMessage, $postalCode, $addressFormat);
return;
}
}
if ($startPattern) {
// The pattern must match the start of the provided value.
preg_match('/' . $startPattern . '/i', $postalCode, $matches);
if (!isset($matches[0]) || strpos($postalCode, $matches[0]) !== 0) {
$this->addViolation(AddressField::POSTAL_CODE, $constraint->invalidMessage, $postalCode, $addressFormat);
return;
}
}
}