public function ImporterBase::add in CSV Importer 8
Add content.
Parameters
mixed $content: CSV content.
array $context: The batch context array.
Return value
array Prepared data.
Overrides ImporterInterface::add
File
- src/
Plugin/ ImporterBase.php, line 125
Class
- ImporterBase
- Provides a base class for ImporterBase plugins.
Namespace
Drupal\csv_importer\PluginCode
public function add($content, array &$context) {
if (!$content) {
return NULL;
}
$entity_type = $this->configuration['entity_type'];
$entity_type_bundle = $this->configuration['entity_type_bundle'];
$entity_definition = $this->entityTypeManager
->getDefinition($entity_type);
$added = 0;
$updated = 0;
if ($entity_definition
->hasKey('bundle') && $entity_type_bundle) {
$content[$entity_definition
->getKey('bundle')] = $this->configuration['entity_type_bundle'];
}
foreach ($content as $key => $item) {
if (is_string($item) && file_exists($item)) {
$created = file_save_data(file_get_contents($item), $this->config
->get('system.file')
->get('default_scheme') . '://' . basename($item), FileSystemInterface::EXISTS_REPLACE);
$content[$key] = $created
->id();
}
}
/** @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage $entity_storage */
$entity_storage = $this->entityTypeManager
->getStorage($this->configuration['entity_type']);
try {
if (isset($content[$entity_definition
->getKeys()['id']]) && ($entity = $entity_storage
->load($content[$entity_definition
->getKeys()['id']]))) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
foreach ($content as $id => $set) {
$entity
->set($id, $set);
}
if ($entity
->save()) {
$context['results']['updated'][] = $entity
->id();
}
}
else {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $this->entityTypeManager
->getStorage($this->configuration['entity_type'])
->create($content);
if ($entity
->save()) {
$context['results']['added'][] = $entity
->id();
}
}
} catch (\Exception $e) {
}
}