You are here

public function LanguageToCode::tamper in Custom Language field 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/LanguageToCode.php, line 44

Class

LanguageToCode
Plugin implementation for converting language name to language code.

Namespace

Drupal\languagefield\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 languages in an array.
   * @static
   */
  static $languages = [];
  if (empty($languages)) {
    $languages = $this->languageManager
      ->getStandardLanguageList() + CustomLanguageManager::getCustomLanguageList();
    foreach ($languages as $language_code => $language_name) {
      $languages[$language_code] = mb_strtolower((string) $language_name[0]);
    }
    $languages = array_flip($languages);
  }

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

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