RealisticDummyContentTermReferenceField.php in Realistic Dummy Content 3.x
File
api/src/includes/RealisticDummyContentTermReferenceField.php
View source
<?php
namespace Drupal\realistic_dummy_content_api\includes;
use Drupal\realistic_dummy_content_api\traits\RealisticDummyContentDrupalTrait;
use Drupal\realistic_dummy_content_api\Framework\Framework;
class RealisticDummyContentTermReferenceField extends RealisticDummyContentField {
use RealisticDummyContentDrupalTrait;
public function implementValueFromFile($file) : array {
try {
$termname = $file
->value();
if ($termname) {
$return = Framework::instance()
->formatProperty('tid', $this
->getTid($termname));
return $return;
}
return [];
} catch (\Exception $e) {
Framework::instance()
->debug('Problem with taxonomy term: ' . $e
->getMessage());
return [];
}
}
public function getTid($name) {
$vocabularies = $this
->getAllVocabularies();
$field_info = $this
->fieldInfoField($this
->getName());
$candidate_existing_terms = [];
foreach ($field_info['settings']['allowed_values'] as $setting) {
$vocabulary_name = $setting['vocabulary'];
foreach ($vocabularies as $vocabulary) {
if ($this
->vocabularyMachineName($vocabulary) == $vocabulary_name) {
$candidate_existing_terms = array_merge($candidate_existing_terms, $this
->taxonomyLoadTree($vocabulary));
break 2;
}
}
}
foreach ($candidate_existing_terms as $candidate_existing_term) {
$candidate_name = $this
->termName($candidate_existing_term);
if ($candidate_name == $name) {
return $this
->termId($candidate_existing_term);
}
}
if (!isset($vocabulary)) {
throw new \Exception('Expecting the taxonomy term reference to reference at least one vocabulary');
}
$term = $this
->newVocabularyTerm($vocabulary, $name);
return $this
->termId($term);
}
}