View source
<?php
namespace Drupal\address\Plugin\views\sort;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\views\Plugin\views\sort\SortPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use CommerceGuys\Addressing\Country\CountryRepositoryInterface;
class Country extends SortPluginBase {
const COUNTRY_NAME = 'name';
const COUNTRY_CODE = 'code';
protected $countryRepository;
protected $langcode;
public function __construct(array $configuration, $plugin_id, $plugin_definition, CountryRepositoryInterface $country_repository, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->countryRepository = $country_repository;
$this->langcode = $language_manager
->getCurrentLanguage()
->getId();
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('address.country_repository'), $container
->get('language_manager'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['sort_by'] = [
'default' => self::COUNTRY_NAME,
];
return $options;
}
public function query() {
if ($this->options['sort_by'] === self::COUNTRY_NAME) {
$this
->ensureMyTable();
$country_list = $this->countryRepository
->getList($this->langcode);
$field_name = $this->tableAlias . '.' . $this->realField;
$when = [];
$i = 0;
foreach (array_keys($country_list) as $country_code) {
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();
}
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['sort_by'] = [
'#type' => 'radios',
'#title' => $this
->t('Sort by'),
'#options' => [
self::COUNTRY_NAME => $this
->t('Country name'),
self::COUNTRY_CODE => $this
->t('Country code'),
],
'#default_value' => $this->options['sort_by'],
'#weight' => -0.5,
];
}
}