You are here

telephone_formatter.module in Telephone Formatter 7

File

telephone_formatter.module
View source
<?php

use libphonenumber\PhoneNumberFormat;
use libphonenumber\PhoneNumberUtil;

/**
 * Implements hook_field_formatter_info().
 */
function telephone_formatter_field_formatter_info() {
  return array(
    'telephone_formatter' => array(
      'label' => t('Formatted telephone'),
      'field types' => array(
        'telephone',
      ),
      'settings' => array(
        'format' => PhoneNumberFormat::INTERNATIONAL,
        'link' => TRUE,
        'default_country' => NULL,
      ),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function telephone_formatter_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $elements['format'] = array(
    '#type' => 'select',
    '#title' => t('Format'),
    '#description' => t('List of available formats'),
    '#default_value' => $settings['format'],
    '#options' => _telephone_formatter_get_available_formats(),
  );
  $elements['link'] = array(
    '#type' => 'checkbox',
    '#title' => t('Link'),
    '#description' => t('Format as link'),
    '#default_value' => $settings['link'],
  );
  $elements['default_country'] = array(
    '#type' => 'select',
    '#title' => t('Default country'),
    '#description' => t('If field allows internal telephone numbers you can choose which country this number belongs to by default. It is highly advised to enable telephone validation for this field to ensure that telephone number is valid and can be parsed and reformatted.'),
    '#default_value' => $settings['default_country'],
    '#options' => array(
      NULL => t('- Do not use default country -'),
    ) + _telephone_formatter_get_country_codes(),
  );
  return $elements;
}

/**
 * Implements hook_field_formatter_settings_summary().
 */
function telephone_formatter_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = array();
  $formats = _telephone_formatter_get_available_formats();
  $summary[] = t('Format: @format', array(
    '@format' => $formats[$settings['format']],
  ));
  $summary[] = t('Link: @link', array(
    '@link' => $settings['link'] ? t('Yes') : t('No'),
  ));
  if ($default_country = $settings['default_country']) {
    $summary[] = t('Default country: @default_country', array(
      '@default_country' => $default_country,
    ));
  }
  return implode('<br>', $summary);
}

/**
 * Implements hook_field_formatter_view().
 */
function telephone_formatter_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];
  foreach ($items as $delta => $item) {
    try {
      if ($settings['link']) {
        $element[$delta] = array(
          '#markup' => _telephone_formatter_view_link_value($item, $settings),
        );
      }
      else {
        $element[$delta] = array(
          '#markup' => _telephone_formatter_view_formatted_value($item, $settings),
        );
      }
    } catch (\Exception $e) {

      // Fallback to the raw value, in case the provided number could not be formatted.
      $element[$delta] = array(
        '#markup' => $item['value'],
      );
    }
  }
  return $element;
}

/**
 * Generate RFC3966 formatted telephone link for one field item.
 *
 * @param $item
 *   Field item.
 * @param $settings
 *   Field formatter settings.
 *
 * @return string
 */
function _telephone_formatter_view_link_value($item, $settings) {
  $formatted_value = _telephone_formatter_get_formatted_value($item['value'], $settings['format'], $settings['default_country']);
  $uri = _telephone_formatter_get_formatted_value($formatted_value, PhoneNumberFormat::RFC3966, $settings['default_country']);
  $value = l($formatted_value, $uri, array(
    'external' => TRUE,
  ));
  return $value;
}

/**
 * Generates formatted telephone number for one field item.
 *
 * @param $item
 *   Field item.
 * @param $settings
 *   Field formatter settings.
 *
 * @return string
 */
function _telephone_formatter_view_formatted_value($item, $settings) {
  return _telephone_formatter_get_formatted_value($item['value'], $settings['format'], $settings['default_country']);
}

/**
 * Formats telephone number into formatted one based on predefined format.
 *
 * @param $input
 *   Input phone number.
 * @param $format
 *   Format option.
 * @param null $region
 *   Country code.
 *
 * @return string
 *   Returns the preformatted telephone number.
 */
function _telephone_formatter_get_formatted_value($input, $format, $region = NULL) {
  $phone_util = PhoneNumberUtil::getInstance();

  // Parse to object.
  $number = $phone_util
    ->parse($input, $region);

  // Ensure number is valid.
  if (!$phone_util
    ->isValidNumber($number)) {
    throw new \InvalidArgumentException('Number is invalid.');
  }

  // Format phone number.
  $value = $phone_util
    ->format($number, $format);
  return $value;
}

/**
 * Get list of all available PhoneNumberFormats.
 *
 * @return array
 *   Returns list of all PhoneNumberFormats provided by the libphonenumber
 *   library.
 */
function _telephone_formatter_get_available_formats() {
  return array(
    PhoneNumberFormat::INTERNATIONAL => t('International'),
    PhoneNumberFormat::E164 => t('E164'),
    PhoneNumberFormat::NATIONAL => t('National'),
    PhoneNumberFormat::RFC3966 => t('RFC3966'),
  );
}

/**
 * Get list of all available countries with codes.
 *
 * @return array
 *   Returns list of all countries from iso.inc file cross referenced with
 *   available country codes.
 */
function _telephone_formatter_get_country_codes() {
  include_once DRUPAL_ROOT . '/includes/iso.inc';
  $phone_util = PhoneNumberUtil::getInstance();
  $regions = array();
  foreach (_country_get_predefined_list() as $region => $name) {
    $region_meta = $phone_util
      ->getMetadataForRegion($region);
    if (is_object($region_meta)) {
      $regions[$region] = $name . ' - +' . $region_meta
        ->getCountryCode() . ' ' . $region_meta
        ->getLeadingDigits();
    }
  }
  return $regions;
}

Functions

Namesort descending Description
telephone_formatter_field_formatter_info Implements hook_field_formatter_info().
telephone_formatter_field_formatter_settings_form Implements hook_field_formatter_settings_form().
telephone_formatter_field_formatter_settings_summary Implements hook_field_formatter_settings_summary().
telephone_formatter_field_formatter_view Implements hook_field_formatter_view().
_telephone_formatter_get_available_formats Get list of all available PhoneNumberFormats.
_telephone_formatter_get_country_codes Get list of all available countries with codes.
_telephone_formatter_get_formatted_value Formats telephone number into formatted one based on predefined format.
_telephone_formatter_view_formatted_value Generates formatted telephone number for one field item.
_telephone_formatter_view_link_value Generate RFC3966 formatted telephone link for one field item.