You are here

class UcAddressesUcCountryFieldHandler in Ubercart Addresses 7

Same name and namespace in other branches
  1. 6.2 handlers/ubercart.handlers.inc \UcAddressesUcCountryFieldHandler

Class for the Ubercart country field.

Hierarchy

Expanded class hierarchy of UcAddressesUcCountryFieldHandler

2 string references to 'UcAddressesUcCountryFieldHandler'
uc_addresses_uc_addresses_fields in ./uc_addresses.uc_addresses_fields.inc
Implements hook_uc_addresses_fields().
uc_addresses_uc_addresses_field_handlers in ./uc_addresses.uc_addresses_fields.inc
Implements hook_uc_addresses_field_handlers().

File

handlers/ubercart.handlers.inc, line 255
Field handlers for Ubercart core address fields: first_name, last_name, company, etc.

View source
class UcAddressesUcCountryFieldHandler extends UcAddressesUcFieldHandler {

  /**
   * An array of all loaded countries.
   *
   * @var array $countries
   * @access private
   * @static
   */
  private static $countries;

  /**
   * Implements UcAddressesFieldHandler::getFormField().
   */
  public function getFormField($form, $form_values) {
    $address = $this
      ->getAddress();
    $fieldName = $this
      ->getFieldName();
    $fieldValue = $address
      ->getField($fieldName);
    $default = isset($form_values[$fieldName]) ? $form_values[$fieldName] : $fieldValue;
    $result = db_select('uc_countries')
      ->condition('version', 0, '>')
      ->fields('uc_countries')
      ->orderBy('country_name', 'ASC')
      ->execute();
    $countries = array();
    foreach ($result as $country) {

      // Create option.
      $countries[$country->country_id] = t($country->country_name);

      // Save for later use.
      self::$countries[$country->country_id] = $country;
    }
    if (count($countries) == 0) {
      $countries[] = t('No countries found.');
    }
    else {

      // Sort countries list in natural order.
      natcasesort($countries);
    }
    if (empty($form['#key_prefix'])) {
      if ($address instanceof UcAddressesAddress) {

        // When no key prefix is set, use the address ID as part of the zone wrapper ID.
        $zone_wrapper_id = 'uc-address' . $address
          ->getId() . '-zone-wrapper';
      }
      else {

        // When no instance of UcAddressesAddress is given, we have no unique
        // value to create a wrapper for.
        $zone_wrapper_id = 'uc-address-zone-wrapper';
      }
    }
    else {

      // When a key prefix is set, make this part of the zone wrapper ID.
      $zone_wrapper_id = 'uc-store-address-' . str_replace('_', '-', $form['#key_prefix']) . '-zone-wrapper';
    }
    return array(
      $fieldName => array(
        '#type' => 'select',
        '#title' => $this
          ->getFieldTitle(),
        '#options' => $countries,
        '#required' => $this
          ->isFieldRequired(),
        '#default_value' => empty($default) ? uc_store_default_country() : $default,
        '#ajax' => array(
          'callback' => 'uc_store_update_address_field_zones',
          'wrapper' => $zone_wrapper_id,
          'progress' => array(
            'type' => 'throbber',
          ),
        ),
        '#element_validate' => array(
          'uc_addresses_validate_address_field_country',
        ),
        '#key_prefix' => empty($form['#key_prefix']) ? '' : $form['#key_prefix'],
      ),
    );
  }

  /**
   * Overrides UcAddressesFieldHandler::getDefaultValue().
   */
  public function getDefaultValue() {
    return uc_store_default_country();
  }

  /**
   * Overrides UcAddressesFieldHandler::getMappingTargets().
   *
   * The country field has some extra mapping targets.
   */
  public function getMappingTargets() {
    $targets = parent::getMappingTargets();

    // Formats ending on "if" have no use for Feeds.
    unset($targets['country:country_name_if']);
    unset($targets['country:country_code2_if']);
    unset($targets['country:country_code3_if']);

    // Specify clearer names and descriptions.
    $targets['country:country_name']['name'] = t('Country name (@language)', array(
      '@language' => 'English',
    ));
    $targets['country:country_code2']['name'] = t('Country code 2');
    $targets['country:country_code3']['name'] = t('Country code 3');
    $targets['country']['description'] = t('Country ID as known to Ubercart');
    $targets['country:country_name']['description'] = t('The name of the country in English.');

    // Add support for countries in native language.
    $targets['country:country_name:current'] = array(
      'name' => t('Country name (current language)'),
      'description' => t('Name of the country in the current language. Country names are expected to be in the language that is active when importing addresses. For example, if are you viewing the site in Dutch when importing addresses, country names should be in Dutch. If you then switch the site to French, country names are expected to be in French.'),
    );
    $languages = language_list();
    foreach ($languages as $key => $language) {
      if ($key == 'en') {

        // English is already handled.
        continue;
      }
      $targets['country:country_name:' . $key] = array(
        'name' => t('Country name (@language)', array(
          '@language' => $language->name,
        )),
        'description' => t('The name of the country in @language-native', array(
          '@language-native' => $language->native,
        )),
      );
    }
    return $targets;
  }

  /**
   * Overrides UcAddressesFieldHandler::mapValue().
   *
   * The country field has some extra mapping targets.
   */
  public function mapValue($value, $format = '') {
    if (strpos($format, 'country_name:') === 0) {

      // Country is specified in native or current language.
      $explode = explode(':', $format);
      $langcode = $explode[1];
      if ($langcode == 'current') {

        // Country is expected to be specified in the current language.
        global $language;
        $langcode = $language->language;
      }

      // Look through complete country list and find one that matches.
      $countries = $this
        ->getAllCountries();
      foreach ($countries as $country) {
        $translated_country = t($country->country_name, array(), array(
          'langcode' => $langcode,
        ));
        if ($value == $translated_country) {

          // Country in native language found!
          return parent::mapValue($country->country_id, $format);
        }
      }

      // No country found. Report error.
      $message = t('Country %name not found.', array(
        '%name' => $value,
      ));
      if (user_access('administer store')) {
        $message .= ' ' . t('Check if the country is spelled correctly and if it is installed in the store.');
      }
      else {
        $message .= ' ' . t('Check if the country is spelled correctly or contact the site administrator.');
      }
      throw new UcAddressesException($message);
    }
    switch ($format) {
      case 'country_code2':
      case 'country_code2_if':
        $format = 'country_iso_code_2';
        break;
      case 'country_code3':
      case 'country_code3_if':
        $format = 'country_iso_code_3';
        break;
    }
    switch ($format) {
      case 'country_name':
      case 'country_iso_code_2':
      case 'country_iso_code_3':

        // Lookup country data.
        $country_id = db_select('uc_countries', 'uc_countries')
          ->condition($format, $value)
          ->fields('uc_countries', array(
          'country_id',
        ))
          ->execute()
          ->fetchField();
        if ($country_id) {
          $value = $country_id;
        }
        else {
          $message = t('Country @name not found.', array(
            '@name' => $value,
          ));
          if (user_access('administer store')) {
            $message .= ' ' . t('Check if the country is spelled correctly and if it is enabled in the store.');
          }
          else {
            $message .= ' ' . t('Check if the country is spelled correctly or contact the site administrator.');
          }
          throw new UcAddressesException($message);
        }
        break;
    }
    parent::mapValue($value, $format);
  }

  /**
   * Implements UcAddressesFieldHandler::getOutputFormats().
   */
  public function getOutputFormats() {
    return array(
      'country_name' => t('Name of the country'),
      'country_code2' => t('2 digit country abbreviation'),
      'country_code3' => t('3 digit country abbreviation'),
      'country_name_if' => $this
        ->getCountryDescriptionMessage(t('Name of the country')),
      'country_code2_if' => $this
        ->getCountryDescriptionMessage(t('2 digit country abbreviation')),
      'country_code3_if' => $this
        ->getCountryDescriptionMessage(t('3 digit country abbreviation')),
    );
  }

  /**
   * Used in getOutputFormats() to output a description for the country format.
   *
   * @param string $country_description
   *   First part of the country description.
   *
   * @access private
   * @return string
   *   Description message for getOutputFormats().
   *
   * @see getOutputFormats()
   */
  private function getCountryDescriptionMessage($country_description) {
    return t('!country_description, display only for addresses whose country is different than the default store country.', array(
      '!country_description' => $country_description,
    ));
  }

  /**
   * Overrides UcAddressesFieldHandler::outputValue().
   *
   * The country field can be outputted in different formats.
   */
  public function outputValue($value = '', $format = '') {
    if ($value === '') {
      $value = $this
        ->getAddress()
        ->getField($this
        ->getFieldName());
    }
    $country = $this
      ->getCountry($value);
    if (!$country) {
      return t('Unknown');
    }

    // Return country only if the country is not equal to the store's default country.
    if (preg_match('/\\_if$/', $format)) {
      if (uc_store_default_country() == $country->country_id) {
        return '';
      }
    }
    switch ($format) {
      case 'country_name':
      case 'country_name_if':
        return t($country->country_name);
      case 'country_code2':
      case 'country_code2_if':
        return $country->country_iso_code_2;
      case 'country_code3':
      case 'country_code3_if':
        return $country->country_iso_code_3;
    }

    // If no format is specified, return country name.
    return t($country->country_name);
  }

  /**
   * Returns country data.
   *
   * @param int $country_id
   *   The country to get.
   *
   * @return object
   *   Data of country if the country is found.
   *   NULL otherwise.
   */
  private function getCountry($country_id) {
    if (isset(self::$countries[$country_id])) {
      return self::$countries[$country_id];
    }
    $result = db_select('uc_countries')
      ->fields('uc_countries')
      ->condition('country_id', $country_id)
      ->execute();
    $country = $result
      ->fetch();
    if ($country) {
      self::$countries[$country->country_id] = $country;
      return $country;
    }
    return NULL;
  }

  /**
   * Returns all countries installed for Ubercart.
   *
   * @return array
   *   List of installed countries in Ubercart.
   */
  private function getAllCountries() {
    static $all_loaded = FALSE;
    if ($all_loaded) {
      return self::$countries;
    }
    $countries = db_select('uc_countries')
      ->fields('uc_countries')
      ->execute()
      ->fetchAll();

    // Index countries.
    foreach ($countries as $country) {
      self::$countries[$country->country_id] = $country;
    }
    $all_loaded = TRUE;
    return self::$countries;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
UcAddressesFieldHandler::$address private property Address object.
UcAddressesFieldHandler::$context private property The context in which this field is used.
UcAddressesFieldHandler::$definition private property The declared field definition.
UcAddressesFieldHandler::$name private property Name of this field.
UcAddressesFieldHandler::checkContext public function Checks if the field passes the context. 1
UcAddressesFieldHandler::getAddress final public function Returns the address attached to this field.
UcAddressesFieldHandler::getContext final public function Returns the context in which this field is used.
UcAddressesFieldHandler::getFieldName final public function Returns the field name.
UcAddressesFieldHandler::getProperty final public function Returns a property from the field definition.
UcAddressesFieldHandler::getTokenInfo public function Returns supported tokens. 1
UcAddressesFieldHandler::init protected function Can be used by subclasses to do some initialization upon construction of the object. 2
UcAddressesFieldHandler::setValue public function Sets value in the address object.
UcAddressesFieldHandler::validateValue public function Check a fields' value. 2
UcAddressesFieldHandler::__construct final public function UcAddressesFormField object constructor.
UcAddressesUcCountryFieldHandler::$countries private static property An array of all loaded countries.
UcAddressesUcCountryFieldHandler::getAllCountries private function Returns all countries installed for Ubercart.
UcAddressesUcCountryFieldHandler::getCountry private function Returns country data.
UcAddressesUcCountryFieldHandler::getCountryDescriptionMessage private function Used in getOutputFormats() to output a description for the country format.
UcAddressesUcCountryFieldHandler::getDefaultValue public function Overrides UcAddressesFieldHandler::getDefaultValue(). Overrides UcAddressesFieldHandler::getDefaultValue
UcAddressesUcCountryFieldHandler::getFormField public function Implements UcAddressesFieldHandler::getFormField(). Overrides UcAddressesFieldHandler::getFormField
UcAddressesUcCountryFieldHandler::getMappingTargets public function Overrides UcAddressesFieldHandler::getMappingTargets(). Overrides UcAddressesFieldHandler::getMappingTargets
UcAddressesUcCountryFieldHandler::getOutputFormats public function Implements UcAddressesFieldHandler::getOutputFormats(). Overrides UcAddressesFieldHandler::getOutputFormats
UcAddressesUcCountryFieldHandler::mapValue public function Overrides UcAddressesFieldHandler::mapValue(). Overrides UcAddressesFieldHandler::mapValue
UcAddressesUcCountryFieldHandler::outputValue public function Overrides UcAddressesFieldHandler::outputValue(). Overrides UcAddressesFieldHandler::outputValue
UcAddressesUcFieldHandler::getFieldTitle public function Overrides UcAddressesFieldHandler::getFieldTitle(). Overrides UcAddressesFieldHandler::getFieldTitle
UcAddressesUcFieldHandler::isFieldEnabled public function Implements UcAddressesFieldHandler::isFieldEnabled(). Overrides UcAddressesFieldHandler::isFieldEnabled
UcAddressesUcFieldHandler::isFieldRequired public function Implements UcAddressesFieldHandler::isFieldRequired(). Overrides UcAddressesFieldHandler::isFieldRequired