You are here

public function CountryToCode::tamper in Tamper 8

Tamper data.

Performs the operations on the data to transform it.

Parameters

mixed $data: The data to tamper.

\Drupal\tamper\TamperableItemInterface $item: Item that can be tampered as part of a plugin's execution.

Return value

mixed The tampered data.

Throws

\Drupal\tamper\Exception\TamperException When the plugin can not tamper the given data.

\Drupal\tamper\Exception\SkipTamperDataException When the calling tamper process should be skipped for the given data.

\Drupal\tamper\Exception\SkipTamperItemException When the calling tamper process should be skipped for the given item.

Overrides TamperInterface::tamper

File

src/Plugin/Tamper/CountryToCode.php, line 33

Class

CountryToCode
Plugin implementation for converting country to ISO code.

Namespace

Drupal\tamper\Plugin\Tamper

Code

public function tamper($data, TamperableItemInterface $item = NULL) {
  if (!is_string($data)) {
    throw new TamperException('Input should be a string.');
  }

  /**
   * Holds the list of countries in an array.
   * @static
   */
  static $countries = [];
  if (empty($countries)) {
    $countries = $this->countryManager
      ->getList();
    foreach ($countries as $country_code => $country_name) {
      $countries[$country_code] = mb_strtolower((string) $country_name);
    }
    $countries = array_flip($countries);
  }

  // If it's already a valid country code, leave it alone.
  if (in_array($data, $countries)) {
    return $data;
  }

  // Trim whitespace, set to lowercase.
  $country = mb_strtolower(trim($data));
  if (isset($countries[$country])) {
    return $countries[$country];
  }
  else {
    throw new TamperException('Could not find country name ' . $country . ' in list of countries.');
  }
}