function ContentImportTest::testPreImportEvent

Tests that the pre-import event allows skipping certain entities.

File

core/tests/Drupal/FunctionalTests/DefaultContent/ContentImportTest.php, line 334

Class

ContentImportTest
@covers \Drupal\Core\DefaultContent\Importer[[api-linebreak]] @group DefaultContent @group Recipe @group #slow

Namespace

Drupal\FunctionalTests\DefaultContent

Code

public function testPreImportEvent() : void {
  $invalid_uuid_detected = FALSE;
  $listener = function (PreImportEvent $event) use (&$invalid_uuid_detected) : void {
    $event->skip('3434bd5a-d2cd-4f26-bf79-a7f6b951a21b', 'Decided not to!');
    try {
      $event->skip('not-a-thing');
    } catch (\InvalidArgumentException) {
      $invalid_uuid_detected = TRUE;
    }
  };
  \Drupal::service(EventDispatcherInterface::class)->addListener(PreImportEvent::class, $listener);
  $finder = new Finder($this->contentDir);
  $this->assertSame('menu_link_content', $finder->data['3434bd5a-d2cd-4f26-bf79-a7f6b951a21b']['_meta']['entity_type']);
  /** @var \Drupal\Core\DefaultContent\Importer $importer */
  $importer = \Drupal::service(Importer::class);
  $logger = new TestLogger();
  $importer->setLogger($logger);
  $importer->importContent($finder, Existing::Error);
  // The entity we skipped should not be here, and the reason why should have
  // been logged.
  $menu_link = \Drupal::service(EntityRepositoryInterface::class)->loadEntityByUuid('menu_link_content', '3434bd5a-d2cd-4f26-bf79-a7f6b951a21b');
  $this->assertNull($menu_link);
  $this->assertTrue($logger->hasInfo([
    'message' => 'Skipped importing @entity_type @uuid because: %reason',
    'context' => [
      '@entity_type' => 'menu_link_content',
      '@uuid' => '3434bd5a-d2cd-4f26-bf79-a7f6b951a21b',
      '%reason' => 'Decided not to!',
    ],
  ]));
  // We should have caught an exception for trying to skip an invalid UUID.
  $this->assertTrue($invalid_uuid_detected);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.