cforge-2.0.x-dev/modules/cforge_import/src/DefaultContentDeleteSubscriber.php
modules/cforge_import/src/DefaultContentDeleteSubscriber.php
<?php
namespace Drupal\cforge_import;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\migrate\Event\MigrateImportEvent;
use Drupal\Core\Entity\EntityTypeManager;
/**
* Before importing, delete a module's default content
* @todo this is not used anywhere.
*/
class DefaultContentDeleteSubscriber implements EventSubscriberInterface {
/**
* @var \Drupal\Core\Entity\ContentEntityStorageInterface
*/
private $entityStorage;
private $bundle;
private $bundleKey;
/**
* @param EntityTypeManager $entity_type_manager
* @param string $entity_type
* @param string $bundle
*/
function __construct(EntityTypeManager $entity_type_manager, $entity_type, $bundle = NULL) {
$this->entityStorage = $entity_type_manager->getStorage($entity_type);
if ($bundle) {
$this->bundle = $bundle;
$this->bundleKey = $this->entityStorage->getEntityType()->getKey('bundle');
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() : array {
return [
//Drupal\migrate\Event\MigrateEvents::PRE_IMPORT
'migrate.pre_import' => [['migratePreImport']],
];
}
/**
* @param Drupal\migrate\Event\MigrateImportEvent $event
*/
public function migratePreImport(MigrateImportEvent $event) {
if ($this->bundleKey) {
$entities = $this->entityStorage->loadByProperties([$this->bundleKey => $this->bundle]);
\Drupal::messenger()->addStatus("Deleting $this->bundle ".\print_r(array_keys($entities), 1));
}
else {
$entities = $this->entityStorage->loadMultiple();
}
foreach ($entities as $entity) {
$entity->delete();
}
}
}
