You are here

public function AddressService::addressArrayToGeoString in Geocoder 8.2

Same name and namespace in other branches
  1. 8.3 modules/geocoder_address/src/AddressService.php \Drupal\geocoder_address\AddressService::addressArrayToGeoString()

Convert an address array into a string address suitable for geocoding.

Expects an array structured like the Address module as the input values.

Parameters

array $values: An array keyed by any combination of the following:

  • given_name
  • additional_name
  • family_name
  • organization
  • address_line1
  • address_line2
  • postal_code
  • sorting_code
  • dependent_locality
  • locality
  • administrative_area
  • country_code
  • langcode.

Return value

string The string representation of the address suitable for submission to a geocoder service.

File

modules/geocoder_address/src/AddressService.php, line 118

Class

AddressService
Class AddressService.

Namespace

Drupal\geocoder_address

Code

public function addressArrayToGeoString(array $values) {

  // Make sure the address_array has all values populated.
  // @var \Drupal\address\Element\Address::applyDefaults()
  $values = ElementAddress::applyDefaults($values);

  // Without a country code this won't work.
  if (empty($values['country_code'])) {
    return '';
  }

  // Use the Address formatter to create a string ordered appropriately
  // for the country in the address.
  // @var CommerceGuys\Addressing\Address
  $address = new AddressingAddress();
  $address = $address
    ->withCountryCode($values['country_code'])
    ->withPostalCode($values['postal_code'])
    ->withAdministrativeArea($values['administrative_area'])
    ->withDependentLocality($values['dependent_locality'])
    ->withLocality($values['locality'])
    ->withAddressLine1($values['address_line1'])
    ->withAddressLine2($values['address_line2']);
  $countrycode = isset($values['country_code']) ? $values['country_code'] : NULL;
  $langcode = !empty($values['langcode']) ? $values['langcode'] : 'en';

  // Get the formatted address.
  // @var CommerceGuys\Addressing\Formatter\PostalLabelFormatter
  $formatter = $this
    ->getFormatter($langcode, $countrycode, 'postal');
  $address_string = $formatter
    ->format($address);

  // Clean up the returned multiline address to turn it into a single line of
  // text.
  $address_string = str_replace("\n", ' ', $address_string);
  $address_string = str_replace("<br>", ' ', $address_string);
  $address_string = strip_tags($address_string);
  $address_string .= isset($countrycode) ? ' ' . $countrycode : '';

  // Add Country code suffix, if defined.
  return $address_string;
}