Version 1
[yaffs-website] / web / core / modules / migrate_drupal / src / Tests / StubTestTrait.php
1 <?php
2
3 namespace Drupal\migrate_drupal\Tests;
4
5 use Drupal\migrate\Row;
6
7 /**
8  * Provides common functionality for testing stubbing.
9  */
10 trait StubTestTrait {
11
12   /**
13    * Test that creating a stub of the given entity type results in a valid
14    * entity.
15    *
16    * @param string $entity_type_id
17    *   The entity type we are stubbing.
18    */
19   protected function performStubTest($entity_type_id) {
20     $entity_id = $this->createStub($entity_type_id);
21     $this->assertTrue($entity_id, 'Stub successfully created');
22     if ($entity_id) {
23       $violations = $this->validateStub($entity_type_id, $entity_id);
24       if (!$this->assertIdentical(count($violations), 0, 'Stub is a valid entity')) {
25         foreach ($violations as $violation) {
26           $this->fail((string) $violation->getMessage());
27         }
28       }
29     }
30   }
31
32   /**
33    * Create a stub of the given entity type.
34    *
35    * @param string $entity_type_id
36    *   The entity type we are stubbing.
37    *
38    * @return int
39    *   ID of the created entity.
40    */
41   protected function createStub($entity_type_id) {
42     // Create a dummy migration to pass to the destination plugin.
43     $definition = [
44       'migration_tags' => ['Stub test'],
45       'source' => ['plugin' => 'empty'],
46       'process' => [],
47       'destination' => ['plugin' => 'entity:' . $entity_type_id],
48     ];
49     $migration = \Drupal::service('plugin.manager.migration')->createStubMigration($definition);
50     $destination_plugin = $migration->getDestinationPlugin(TRUE);
51     $stub_row = new Row([], [], TRUE);
52     $destination_ids = $destination_plugin->import($stub_row);
53     return reset($destination_ids);
54   }
55
56   /**
57    * Perform validation on a stub entity.
58    *
59    * @param string $entity_type_id
60    *   The entity type we are stubbing.
61    * @param string $entity_id
62    *   ID of the stubbed entity to validate.
63    *
64    * @return \Drupal\Core\Entity\EntityConstraintViolationListInterface
65    *   List of constraint violations identified.
66    */
67   protected function validateStub($entity_type_id, $entity_id) {
68     $controller = \Drupal::entityManager()->getStorage($entity_type_id);
69     /** @var \Drupal\Core\Entity\ContentEntityInterface $stub_entity */
70     $stub_entity = $controller->load($entity_id);
71     return $stub_entity->validate();
72   }
73
74 }