View source
<?php
namespace Drupal\content_synchronizer\Service;
use Drupal\content_synchronizer\Processors\Entity\EntityProcessorBase;
use Drupal\Core\Entity\Entity;
use Drupal\content_synchronizer\Processors\ImportProcessor;
class EntityPublisher {
const SERVICE_NAME = 'content_synchronizer.entity_publisher';
public function saveEntity(Entity $entity, $gid = NULL, $existingEntity = NULL, array $dataToImport = []) {
$entityDataToImport = array_key_exists('translations', $dataToImport) ? $dataToImport['translations'][$entity
->language()
->getId()] : $dataToImport;
\Drupal::moduleHandler()
->alter(EntityProcessorBase::IMPORT_HOOK, $entity, $existingEntity, $entityDataToImport);
$this
->saveEntityWithRevision($entity, $gid, $existingEntity);
}
protected function saveEntityWithRevision(Entity $entity, $gid, Entity $existingEntity = NULL) {
if ($entity
->id()) {
$entityMethods = get_class_methods($entity);
if (in_array('setRevisionCreationTime', $entityMethods) && in_array('setNewRevision', $entityMethods)) {
try {
$revision = clone $entity;
$revision
->setNewRevision(TRUE);
$revision->revision_log = '[Content Synchronizer] ' . ImportProcessor::getCurrentImportProcessor()
->getImport()
->label();
$revision
->setRevisionCreationTime(time());
if ($this
->haveToSave($revision, $existingEntity)) {
$revision
->save();
}
} catch (\Exception $e) {
$this
->saveEntityWithUnpublishedStatus($entity, $gid, $existingEntity);
}
}
else {
$this
->saveEntityWithUnpublishedStatus($entity, $gid, $existingEntity);
}
}
else {
$this
->saveEntityWithUnpublishedStatus($entity, $gid, $existingEntity);
}
}
protected function saveEntityWithUnpublishedStatus(Entity $entity, $gid, Entity $existingEntity = NULL) {
if ($this
->isPublishable($entity)) {
if (!$entity
->id()) {
if (ImportProcessor::getCurrentImportProcessor()
->getCreationType() == ImportProcessor::PUBLICATION_UNPUBLISH) {
$entity
->setPublished(FALSE);
}
else {
$entity
->setPublished(TRUE);
}
}
}
$this
->defaultSave($entity, $existingEntity);
}
protected function defaultSave(Entity $entity, Entity $existingEntity = NULL) {
if ($this
->haveToSave($entity, $existingEntity)) {
if (is_null($entity
->uuid())) {
$entity->uuid = \Drupal::service('uuid')
->generate();
}
$entity
->save();
}
}
protected function isPublishable(Entity $entity) {
return method_exists($entity, 'setPublished');
}
protected function haveToSave(Entity $entity, Entity $existingEntity = NULL) {
$haveToSave = TRUE;
if ($entity
->id()) {
switch (ImportProcessor::getCurrentImportProcessor()
->getUpdateType()) {
case ImportProcessor::UPDATE_IF_RECENT:
if ($existingEntity) {
if (method_exists($entity, 'getChangedTime')) {
$haveToSave = $entity
->getChangedTime() > $existingEntity
->getChangedTime();
}
else {
$haveToSave = TRUE;
}
}
else {
$haveToSave = TRUE;
}
break;
case ImportProcessor::UPDATE_NO_UPDATE:
$haveToSave = FALSE;
break;
case ImportProcessor::UPDATE_SYSTEMATIC:
default:
$haveToSave = TRUE;
}
}
return $haveToSave;
}
}