Subdivision.php in Address 8
File
src/Plugin/views/field/Subdivision.php
View source
<?php
namespace Drupal\address\Plugin\views\field;
use CommerceGuys\Addressing\Locale;
use CommerceGuys\Addressing\Subdivision\SubdivisionRepositoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Symfony\Component\DependencyInjection\ContainerInterface;
class Subdivision extends FieldPluginBase {
protected $subdivisionRepository;
public function __construct(array $configuration, $plugin_id, $plugin_definition, SubdivisionRepositoryInterface $subdivision_repository) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->subdivisionRepository = $subdivision_repository;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('address.subdivision_repository'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['display_name'] = [
'default' => TRUE,
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['display_name'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Display the subdivision name instead of the subdivision code'),
'#default_value' => !empty($this->options['display_name']),
];
parent::buildOptionsForm($form, $form_state);
}
public function render(ResultRow $values) {
$value = $this
->getValue($values);
if (empty($value) || empty($this->options['display_name'])) {
return $this
->sanitizeValue($value);
}
$entity = $this
->getEntity($values);
$address = $entity->{$this->definition['field_name']}
->first();
switch ($this->definition['property']) {
case 'administrative_area':
$code = $address
->getAdministrativeArea();
$parents = [
$address
->getCountryCode(),
];
break;
case 'locality':
$code = $address
->getLocality();
$parents = [
$address
->getCountryCode(),
$address
->getAdministrativeArea(),
];
break;
case 'dependent_locality':
$code = $address
->getDependentLocality();
$parents = [
$address
->getCountryCode(),
$address
->getAdministrativeArea(),
$address
->getLocality(),
];
break;
}
$subdivision = $this->subdivisionRepository
->get($code, $parents);
if ($subdivision) {
$use_local_name = Locale::matchCandidates($address
->getLocale(), $subdivision
->getLocale());
$value = $use_local_name ? $subdivision
->getLocalName() : $subdivision
->getName();
}
return $this
->sanitizeValue($value);
}
}