You are here

function taxonomy_machine_name_uniquify in Taxonomy Machine Name 8

Same name and namespace in other branches
  1. 7 taxonomy_machine_name.module \taxonomy_machine_name_uniquify()

Check and alter machine name to generate a unique value.

Parameters

string $machine_name: Machine name to uniquify.

\Drupal\taxonomy\Entity\Term $term: Taxonomy term of reference.

1 call to taxonomy_machine_name_uniquify()
taxonomy_machine_name_taxonomy_term_presave in ./taxonomy_machine_name.module
Implements hook_ENTITY_TYPE_presave().

File

./taxonomy_machine_name.module, line 235
This is the Taxonomy Machine Name module.

Code

function taxonomy_machine_name_uniquify(&$machine_name, Term $term) {

  /** @var \Drupal\taxonomy\Entity\Term $existing */
  $existing = taxonomy_term_machine_name_load($machine_name, $term
    ->bundle());
  if (!$existing || $existing
    ->id() == $term
    ->id()) {
    return;
  }

  // If the machine name already exists, generate a new, variant.
  $original_machine_name = $machine_name;
  $i = 0;
  do {

    // Append an incrementing numeric suffix until we find a unique value.
    $unique_suffix = '_' . $i;
    $machine_name = Unicode::truncate($original_machine_name, 255 - mb_strlen($unique_suffix)) . $unique_suffix;
    $i++;
  } while (taxonomy_term_machine_name_load($machine_name, $term
    ->bundle()));
}