You are here

class Formatter in Telephone Formatter 8

Formatter service.

@package Drupal\telephone_formatter

Hierarchy

Expanded class hierarchy of Formatter

1 file declares its use of Formatter
FormatterTest.php in tests/src/Unit/FormatterTest.php
1 string reference to 'Formatter'
telephone_formatter.services.yml in ./telephone_formatter.services.yml
telephone_formatter.services.yml
1 service uses Formatter
telephone_formatter.formatter in ./telephone_formatter.services.yml
Drupal\telephone_formatter\Formatter

File

src/Formatter.php, line 13

Namespace

Drupal\telephone_formatter
View source
class Formatter implements FormatterInterface {

  /**
   * Phone utils from libphonenumber lib.
   *
   * @var \libphonenumber\PhoneNumberUtil
   */
  protected $phoneUtils;

  /**
   * Language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Validator constructor.
   */
  public function __construct(LanguageManagerInterface $languageManager) {
    $this->languageManager = $languageManager;
    $this->phoneUtils = PhoneNumberUtil::getInstance();
  }

  /**
   * {@inheritdoc}
   */
  public function format($input, $format, $region = NULL) {

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

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

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

}

Members

Namesort descending Modifiers Type Description Overrides
Formatter::$languageManager protected property Language manager.
Formatter::$phoneUtils protected property Phone utils from libphonenumber lib.
Formatter::format public function Formats telephone number into massaged one based on predefined format. Overrides FormatterInterface::format
Formatter::__construct public function Validator constructor.