devel_wizard-2.x-dev/tests/src/Traits/TaxonomyVocabularyCreationTrait.php
tests/src/Traits/TaxonomyVocabularyCreationTrait.php
<?php
namespace Drupal\Tests\devel_wizard\Traits;
use Drupal\Core\Entity\EntityInterface;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Tests\RandomGeneratorTrait;
/**
* Provides methods to create taxonomy vocabularies with default settings.
*
* This trait is meant to be used only by test classes.
*/
trait TaxonomyVocabularyCreationTrait {
use RandomGeneratorTrait;
/**
* @param array $settings
* (optional) An associative array of settings for the taxonomy vocabulary
* entity.
* Override the defaults by specifying the key and value in the array, for
* example:
* @code
* $this->createTaxonomyVocabulary('devel_wizard_vocabulary', [
* 'name' => t('Hello, world!'),
* ]);
* @endcode
* The following defaults are provided:
* - vid: Random string.
* - name: Random string.
* - description: Random string.
* - weight: The weight.
*
* @return \Drupal\Core\Entity\EntityInterface|\Drupal\block_content\Entity\BlockContentType
* The block content type entity.
* @throws \Drupal\Core\Entity\EntityStorageException
*/
protected function createTaxonomyVocabulary(array $settings = []): EntityInterface {
// Find a non-existent random id.
if (!isset($settings['vid'])) {
do {
$vid = strtolower($this->randomMachineName(8));
} while (Vocabulary::load($vid));
}
else {
$vid = $settings['vid'];
}
$settings += [
'vid' => $vid,
'name' => $this->randomMachineName(8),
'description' => $this->randomString(16),
'weight' => 1,
];
foreach (['vid', 'name', 'description', 'weight'] as $key) {
$values[$key] = $settings[$key];
// Remove extra values that do not belong in the settings array.
unset($settings[$key]);
}
$taxonomyVocabulary = Vocabulary::create($values);
$taxonomyVocabulary->save();
return $taxonomyVocabulary;
}
}
