You are here

protected function AddressPlainFormatter::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 AddressPlainFormatter::getValues()
AddressPlainFormatter::viewElement in src/Plugin/Field/FieldFormatter/AddressPlainFormatter.php
Builds a renderable array for a single address item.

File

src/Plugin/Field/FieldFormatter/AddressPlainFormatter.php, line 173

Class

AddressPlainFormatter
Plugin implementation of the 'address_plain' 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) {
    $value = $values[$field];

    // The template needs access to both the subdivision code and name.
    $values[$field] = [
      'code' => $value,
      'name' => '',
    ];
    if (empty($value)) {

      // 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($value, $parents);
    if (!$subdivision) {
      break;
    }

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

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

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