cforge-2.0.x-dev/src/EventSubscriber/AddressSubscriber.php
src/EventSubscriber/AddressSubscriber.php
<?php
namespace Drupal\cforge\EventSubscriber;
use Drupal\address\Event\AddressFormatEvent;
use Drupal\address\Event\AddressEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use CommerceGuys\Addressing\AddressFormat\DependentLocalityType;
/**
* Tweaks the address formats.
*/
class AddressSubscriber implements EventSubscriberInterface {
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents() : array {
$events = [];
// Otherwise this fails during installation.
if (class_exists('\Drupal\address\Event\AddressEvents')) {
$events[AddressEvents::ADDRESS_FORMAT] = [['rewriteAddress', -10]];
}
return $events;
}
/**
* Ensure every address format has %dependentLocality, sticking it on the end
* if necessary, that that field is required, and called neighbourhood
*/
public function rewriteAddress(AddressFormatEvent $event) {
$addressFormat = $event->getDefinition();
$addressFormat['dependent_locality_type'] = DependentLocalityType::NEIGHBORHOOD;
$addressFormat['required_fields'] = [];
$addressFormat['format'] = str_replace(["%givenName", "%familyName"], '', $addressFormat['format']);
// Redefine the format for France.
if ($addressFormat['country_code'] == 'FR') {
$addressFormat['format'] = "%addressLine1
%addressLine2
%dependentLocality
%postalCode %locality %administrativeArea";
$addressFormat['uppercase_fields'][] = 'postalCode';
$addressFormat['administrative_area_type'] = 'department';
}
// If the alt_login module uses the firstname/lastname, put them at the top.
if (\Drupal::moduleHandler()->moduleExists('alt_login')) {
$settings = \Drupal::config('alt_login.settings');
$str = implode($settings->get('aliases')).$settings->get('display');
if (str_contains($str, 'address')) {
$addressFormat['format'] = "%givenName %familyName\n".trim($addressFormat['format']);
$addressFormat['required_fields'] = ['givenName'];
}
}
$event->setDefinition($addressFormat);
}
}
