CsvImporter.php in Hierarchical Taxonomy Import 8
File
src/Importer/CsvImporter.php
View source
<?php
namespace Drupal\hierarchical_taxonomy_importer\Importer;
use Drupal\hierarchical_taxonomy_importer\Base\ImporterBase;
use Drupal\Core\Entity\EntityTypeManager;
class CsvImporter extends ImporterBase {
protected $entity_manager;
protected $counter;
public function __construct(EntityTypeManager $entity_manager) {
parent::__construct();
$this->entity_manager = $entity_manager;
$this->counter = 0;
}
private function setCounter($counter) {
$this->counter = $counter;
}
private function getCounter($counter) {
return $this->counter;
}
public function getNestedTid($vid, $data, $parent = 0) {
$term = $data[0];
if (count($data) == 1 && empty($data[1])) {
$parent_new = $this->entity_manager
->getStorage('taxonomy_term')
->create([
'name' => $data[0],
'vid' => $vid,
]);
$parent_new
->save();
$this->counter++;
kint($parent_new);
}
if (!empty($data[$this->counter]) && !empty($data[$this->counter + 1])) {
$parent_term = $this->entity_manager
->getStorage('taxonomy_term')
->loadByProperties([
'name' => $data[$this->counter + 1],
'vid' => $vid,
]);
$parent_new = $this->entity_manager
->getStorage('taxonomy_term')
->create([
'name' => $term,
'parent' => array_keys($parent_term)[0],
'vid' => $vid,
]);
$parent_new
->save();
$parent = array_keys($parent_term)[0];
$this->counter++;
$parent = $this
->getNestedTid($vid, $data, $parent, $this->counter);
}
else {
return $data[$count];
}
}
public function importTaxonomies($vid, $data, $reset) {
if (empty($vid)) {
throw new \Exception("Vocabulary ID is invalid or null");
}
$this
->getNestedTid($vid, $data, $parent = 0, $reset);
}
}