View source
<?php
namespace Drupal\node_export;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\node\Entity\Node;
class NodeImport {
protected static function unload(array $nodeArray) {
$fieldValues = [];
$contentType = $nodeArray['type'][0]['target_id'];
if (self::contentTypeExists($contentType)) {
$bundleFields = \Drupal::service('entity_field.manager')
->getFieldDefinitions('node', $contentType);
foreach ($nodeArray as $fields => $value) {
if (!array_key_exists($fields, $bundleFields)) {
return FALSE;
}
$fieldValues[$fields] = $value;
}
$fieldValues['type'] = $contentType;
}
return $fieldValues;
}
protected static function contentTypeExists($contentType) {
$contentTypes = \Drupal::service('entity_type.manager')
->getStorage('node_type')
->loadMultiple();
return array_key_exists($contentType, $contentTypes);
}
public static function import(array $nodeArray) {
$fieldValues = self::unload($nodeArray);
if (!$fieldValues) {
return FALSE;
}
$config = \Drupal::config('node_export.settings');
$operation = $config
->get('node_export_import');
$id = $fieldValues['nid'][0]['value'];
unset($fieldValues['nid']);
unset($fieldValues['vid']);
unset($fieldValues['uuid']);
switch ($operation) {
case 'new':
$newNode = Node::create($fieldValues);
break;
case 'replace':
$newNode = Node::load($id);
if ($newNode) {
foreach ($fieldValues as $field => $values) {
$newNode
->set($field, $values);
}
$newNode
->setNewRevision(TRUE);
$newNode
->setRevisionCreationTime(\Drupal::time()
->getRequestTime());
$newNode
->setRevisionUserId($fieldValues['uid'][0]['target_id']);
}
else {
$newNode = Node::create($fieldValues);
}
break;
case 'skip':
if (Node::load($id)) {
return $id;
}
$newNode = Node::create($fieldValues);
break;
}
try {
$newNode
->save();
$id = $newNode
->id();
} catch (EntityStorageException $e) {
\Drupal::logger('node_export')
->error($e
->getMessage());
}
return $id;
}
public static function nodeImport(array $nodeArray, array &$context) {
$message = 'Importing Nodes...';
$context['message'] = $message;
$id = NodeImport::import($nodeArray);
if ($id) {
$context['results']['imported'][] = $id;
}
else {
$context['results']['not_imported'][] = $id;
}
}
public static function nodeImportFinishedCallback($success, array $results, array $operations) {
if ($success) {
$message = '';
if (array_key_exists('imported', $results) && count($results['imported']) > 0) {
$message .= \Drupal::translation()
->formatPlural(count($results['imported']), 'One node imported.', '@count nodes imported.');
}
if (array_key_exists('not_imported', $results) && count($results['not_imported']) > 0) {
$message .= "\n" . \Drupal::translation()
->formatPlural(count($results['not_imported']), 'One node could not be imported.', '@count nodes could not be imported.');
}
}
else {
$message = $this
->t('Finished with an error.');
}
\Drupal::messenger()
->addStatus($message);
}
}