TaxonomyTestTrait.php 1.7 KB
Newer Older
1 2 3 4 5 6 7
<?php

namespace Drupal\taxonomy\Tests;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Language\LanguageInterface;
use Drupal\taxonomy\Entity\Vocabulary;
8
use Drupal\taxonomy\Entity\Term;
9 10 11 12 13 14 15 16 17 18 19

/**
 * Provides common helper methods for Taxonomy module tests.
 */
trait TaxonomyTestTrait {

  /**
   * Returns a new vocabulary with random properties.
   */
  function createVocabulary() {
    // Create a vocabulary.
20
    $vocabulary = Vocabulary::create([
21 22 23 24 25
      'name' => $this->randomMachineName(),
      'description' => $this->randomMachineName(),
      'vid' => Unicode::strtolower($this->randomMachineName()),
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
      'weight' => mt_rand(0, 10),
26
    ]);
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    $vocabulary->save();
    return $vocabulary;
  }

  /**
   * Returns a new term with random properties in vocabulary $vid.
   *
   * @param \Drupal\taxonomy\Entity\Vocabulary $vocabulary
   *   The vocabulary object.
   * @param array $values
   *   (optional) An array of values to set, keyed by property name. If the
   *   entity type has bundles, the bundle key has to be specified.
   *
   * @return \Drupal\taxonomy\Entity\Term
   *   The new taxonomy term object.
   */
  function createTerm(Vocabulary $vocabulary, $values = array()) {
    $filter_formats = filter_formats();
    $format = array_pop($filter_formats);
46
    $term = Term::create($values + [
47
      'name' => $this->randomMachineName(),
48
      'description' => [
49 50 51
        'value' => $this->randomMachineName(),
        // Use the first available text format.
        'format' => $format->id(),
52
      ],
53 54
      'vid' => $vocabulary->id(),
      'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
55
    ]);
56 57 58
    $term->save();
    return $term;
  }
59

60
}