You are here

public function Country::query in Address 8

Called to add the sort to a query.

Overrides SortPluginBase::query

File

src/Plugin/views/sort/Country.php, line 93

Class

Country
Sort handler for sorting by either country code or name.

Namespace

Drupal\address\Plugin\views\sort

Code

public function query() {
  if ($this->options['sort_by'] === self::COUNTRY_NAME) {
    $this
      ->ensureMyTable();

    // Map country codes to a sorting key using WHEN ... THEN clauses.
    $country_list = $this->countryRepository
      ->getList($this->langcode);
    $field_name = $this->tableAlias . '.' . $this->realField;
    $when = [];
    $i = 0;
    foreach (array_keys($country_list) as $country_code) {

      // Use only the country codes which are in the expected format.
      if (strlen($country_code) == 2) {
        $when[] = "WHEN {$field_name} = '{$country_code}' THEN " . $i++;
      }
    }
    $this->query
      ->addField(NULL, 'CASE ' . implode(' ', $when) . ' END', 'address_sort_country_name');
    $this->query
      ->addOrderBy(NULL, NULL, $this->options['order'], 'address_sort_country_name');
  }
  else {
    parent::query();
  }
}