You are here

function EntityTestBase::createTaxonomyTerm in Translation Management Tool 8

Creates a taxonomy term of a given vocabulary.

It uses $this->field_names to populate content of attached fields. You can access fields values using $this->field_names['taxonomy_term'][$vocabulary->id(].

Parameters

object $vocabulary: Vocabulary object for which the term should be created.

Return value

object Newly created node object.

File

src/Tests/EntityTestBase.php, line 204

Class

EntityTestBase
Utility test case class with helper methods to create entities and their fields with populated translatable content. Extend this class if you create tests in which you need Drupal entities and/or fields.

Namespace

Drupal\tmgmt\Tests

Code

function createTaxonomyTerm(VocabularyInterface $vocabulary) {
  $term = Term::create(array(
    'name' => $this
      ->randomMachineName(),
    'description' => $this
      ->randomMachineName(),
    'vid' => $vocabulary
      ->id(),
    'langcode' => 'en',
  ));
  foreach ($this->field_names['taxonomy_term'][$vocabulary
    ->id()] as $field_name) {
    $field_definition = $term
      ->getFieldDefinition($field_name);
    $cardinality = $field_definition
      ->getFieldStorageDefinition()
      ->getCardinality() == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED ? 1 : $field_definition
      ->getCardinality();
    $field_lang = $field_definition
      ->isTranslatable() ? 'en' : LanguageInterface::LANGCODE_DEFAULT;

    // Create two deltas for each field.
    for ($delta = 0; $delta <= $cardinality; $delta++) {
      $term
        ->getTranslation($field_lang)
        ->get($field_name)
        ->get($delta)->value = $this
        ->randomMachineName(20);
      if ($field_definition
        ->getType() == 'text_with_summary') {
        $term
          ->getTranslation($field_lang)
          ->get($field_name)
          ->get($delta)->summary = $this
          ->randomMachineName(10);
      }
    }
  }
  $term
    ->save();
  return $term;
}