public function AvataxLib::validateAddress in Drupal Commerce Connector for AvaTax 8
Validate the give address from Drupal upon AvaTax resolved address.
Parameters
array $address: The address item.
Return value
array Return formatted array of errors and suggestions.
Overrides AvataxLibInterface::validateAddress
File
- src/
AvataxLib.php, line 361
Class
- AvataxLib
- The AvaTax integration library.
Namespace
Drupal\commerce_avataxCode
public function validateAddress(array $address) {
$validation = [
'valid' => FALSE,
'errors' => [],
'suggestion' => [],
'fields' => [],
'original' => [],
];
$avatax_response = $this
->resolveAddress($address);
if (empty($avatax_response['address'])) {
// If we don't get validated address or error message,
// mark response as invalid.
return $validation;
}
$original_address = $avatax_response['address'];
$validation['original'] = self::formatDrupalAddress($original_address);
// We have some errors. We don't need the validated address object while
// it is going to be partial anyways.
if (!empty($avatax_response['messages'])) {
$error_fields_mapping = [
'Address.City' => 'locality',
'Address.Line0' => 'address_line1',
'Address.Line1' => 'address_line2',
'Address.PostalCode' => 'postal_code',
'Address.Region' => 'administrative_area',
];
$validation['errors'] = array_map(static function (array $message) use ($error_fields_mapping) {
return $error_fields_mapping[$message['refersTo']];
}, $avatax_response['messages']);
}
elseif (!empty($avatax_response['validatedAddresses'])) {
$validation['valid'] = TRUE;
// AvaTax always return one valid address.
$validatedAddress = end($avatax_response['validatedAddresses']);
unset($validatedAddress['addressType'], $validatedAddress['latitude'], $validatedAddress['longitude'], $validatedAddress['line_3']);
$suggestion = array_filter(array_diff($validatedAddress, $avatax_response['address']));
// Check if we required the full postal code in our suggestion. If the
// provided address had a full postal code, always return the suggestion.
if (!empty($suggestion['postalCode']) && strlen($original_address['postalCode']) === 5) {
$postal_code_match = $this->config
->get('address_validation.postal_code_match');
// If we do not need full match, remove suggestion for postal code.
if (!$postal_code_match && strpos($validatedAddress['postalCode'], $original_address['postalCode']) === 0) {
unset($suggestion['postalCode']);
}
}
if (!empty($suggestion)) {
$validation['fields'] = array_filter(self::formatDrupalAddress($suggestion));
$validation['suggestion'] = self::formatDrupalAddress($validatedAddress);
}
}
return $validation;
}