You are here

protected function CountryAwareInOperatorBase::getAvailableCountries in Address 8

Gets the list of available countries for the current entity field.

Parameters

\Drupal\Core\Entity\EntityTypeInterface $entity_type: The entity type, defaults to the current type for this filter.

string $field_name: The field name, defaults to the current field name for this filter.

Return value

array An array of available country codes, including the full list when unrestricted.

2 calls to CountryAwareInOperatorBase::getAvailableCountries()
AdministrativeArea::getAdministrativeAreaCountries in src/Plugin/views/filter/AdministrativeArea.php
Gets a list of countries that have administrative areas.
Country::getValueOptions in src/Plugin/views/filter/Country.php
Child classes should be used to override this function and set the 'value options', unless 'options callback' is defined as a valid function or static public method to generate these values.

File

src/Plugin/views/filter/CountryAwareInOperatorBase.php, line 107

Class

CountryAwareInOperatorBase
Abstract base class for country-aware InOperator views filters.

Namespace

Drupal\address\Plugin\views\filter

Code

protected function getAvailableCountries(EntityTypeInterface $entity_type = NULL, $field_name = NULL) {
  if (!isset($entity_type)) {
    $entity_type_id = $this
      ->getEntityType();
    $entity_type = $this->entityTypeManager
      ->getDefinition($entity_type_id);
  }
  if (!isset($field_name)) {
    $field_name = $this
      ->getFieldName();
  }
  $bundles = $this
    ->getBundles($entity_type, $field_name);
  $storage = $this->entityTypeManager
    ->getStorage($entity_type
    ->id());
  $countries_by_bundle = [];
  foreach ($bundles as $bundle) {
    $values = [];
    if ($bundle_key = $entity_type
      ->getKey('bundle')) {
      $values[$bundle_key] = $bundle;
    }

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $storage
      ->create($values);
    if ($entity
      ->hasField($field_name)) {
      $countries_by_bundle[$bundle] = $entity
        ->get($field_name)
        ->appendItem()
        ->getAvailableCountries();
    }
  }

  // Create the unified list, valid across bundles.
  // Start by filtering out lists that are empty cause no restrictions apply.
  $countries = [];
  $countries_by_bundle = array_filter($countries_by_bundle);
  if (count($countries_by_bundle) === 1) {
    $countries = reset($countries_by_bundle);
  }
  elseif (count($countries_by_bundle) > 1) {

    // Leave only the country codes that are common to all lists.
    $countries = array_pop($countries_by_bundle);
    foreach ($countries_by_bundle as $list) {
      $countries = array_intersect_key($countries, $list);
    }
  }
  $available_countries = $this->countryRepository
    ->getList();
  if (!empty($countries)) {
    $available_countries = array_intersect_key($available_countries, $countries);
  }
  return $available_countries;
}