You are here

protected function AddressDefaultFormatter::getValues in Address 8

Gets the address values used for rendering.

Parameters

\Drupal\address\AddressInterface $address: The address.

\CommerceGuys\Addressing\AddressFormat\AddressFormat $address_format: The address format.

Return value

array The values, keyed by address field.

1 call to AddressDefaultFormatter::getValues()
AddressDefaultFormatter::viewElement in src/Plugin/Field/FieldFormatter/AddressDefaultFormatter.php
Builds a renderable array for a single address item.

File

src/Plugin/Field/FieldFormatter/AddressDefaultFormatter.php, line 254

Class

AddressDefaultFormatter
Plugin implementation of the 'address_default' formatter.

Namespace

Drupal\address\Plugin\Field\FieldFormatter

Code

protected function getValues(AddressInterface $address, AddressFormat $address_format) {
  $values = [];
  foreach (AddressField::getAll() as $field) {
    $getter = 'get' . ucfirst($field);
    $values[$field] = $address
      ->{$getter}();
  }
  $original_values = [];
  $subdivision_fields = $address_format
    ->getUsedSubdivisionFields();
  $parents = [];
  foreach ($subdivision_fields as $index => $field) {
    if (empty($values[$field])) {

      // This level is empty, so there can be no sublevels.
      break;
    }
    $parents[] = $index ? $original_values[$subdivision_fields[$index - 1]] : $address
      ->getCountryCode();
    $subdivision = $this->subdivisionRepository
      ->get($values[$field], $parents);
    if (!$subdivision) {
      break;
    }

    // Remember the original value so that it can be used for $parents.
    $original_values[$field] = $values[$field];

    // Replace the value with the expected code.
    $use_local_name = Locale::matchCandidates($address
      ->getLocale(), $subdivision
      ->getLocale());
    $values[$field] = $use_local_name ? $subdivision
      ->getLocalCode() : $subdivision
      ->getCode();
    if (!$subdivision
      ->hasChildren()) {

      // The current subdivision has no children, stop.
      break;
    }
  }
  return $values;
}