From 4cdb87fc8ac4f749d7e3ef42c77f509825ecbf7f Mon Sep 17 00:00:00 2001 From: Nathaniel Catchpole Date: Fri, 28 Apr 2017 16:54:55 -0400 Subject: [PATCH] Issue #2872793 by peaton, rakesh.gectcr, phenaproxima, heddn, vasi: Create Entity Exists Process Plugin --- .../Plugin/migrate/process/EntityExists.php | 82 +++++++++++++++++++ .../src/Kernel/Plugin/EntityExistsTest.php | 61 ++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 core/modules/migrate/src/Plugin/migrate/process/EntityExists.php create mode 100644 core/modules/migrate/tests/src/Kernel/Plugin/EntityExistsTest.php diff --git a/core/modules/migrate/src/Plugin/migrate/process/EntityExists.php b/core/modules/migrate/src/Plugin/migrate/process/EntityExists.php new file mode 100644 index 000000000000..72f2ec39afe4 --- /dev/null +++ b/core/modules/migrate/src/Plugin/migrate/process/EntityExists.php @@ -0,0 +1,82 @@ +storage = $storage; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('entity_type.manager')->getStorage($configuration['entity_type']) + ); + } + + /** + * {@inheritdoc} + */ + public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) { + if (is_array($value)) { + $value = reset($value); + } + + $entity = $this->storage->load($value); + if ($entity instanceof EntityInterface) { + return $entity->id(); + } + return FALSE; + } + +} diff --git a/core/modules/migrate/tests/src/Kernel/Plugin/EntityExistsTest.php b/core/modules/migrate/tests/src/Kernel/Plugin/EntityExistsTest.php new file mode 100644 index 000000000000..dcd070c33758 --- /dev/null +++ b/core/modules/migrate/tests/src/Kernel/Plugin/EntityExistsTest.php @@ -0,0 +1,61 @@ +installSchema('system', ['sequences']); + $this->installEntitySchema('user'); + } + + /** + * Test the EntityExists plugin. + */ + public function testEntityExists() { + $user = User::create([ + 'name' => $this->randomString(), + ]); + $user->save(); + $uid = $user->id(); + + $plugin = \Drupal::service('plugin.manager.migrate.process') + ->createInstance('entity_exists', [ + 'entity_type' => 'user', + ]); + $executable = $this->prophesize(MigrateExecutableInterface::class)->reveal(); + $row = new Row(); + + // Ensure that the entity ID is returned if it really exists. + $value = $plugin->transform($uid, $executable, $row, 'buffalo'); + $this->assertSame($uid, $value); + + // Ensure that the plugin returns FALSE if the entity doesn't exist. + $value = $plugin->transform(420, $executable, $row, 'buffalo'); + $this->assertFalse($value); + + // Make sure the plugin can gracefully handle an array as input. + $value = $plugin->transform([$uid, 420], $executable, $row, 'buffalo'); + $this->assertSame($uid, $value); + } + +}