You are here

public function RelationAPITest::testEndpointsFieldValidation in Relation 8.2

Tests endpoints field validation.

File

src/Tests/RelationAPITest.php, line 323

Class

RelationAPITest
Test general API for Relation.

Namespace

Drupal\relation\Tests

Code

public function testEndpointsFieldValidation() {
  \Drupal::entityTypeManager()
    ->getStorage('relation_type')
    ->create([
    'id' => 'test_relation_type',
    'label' => 'Test relation type',
    'source_bundles' => [
      'node:article',
    ],
  ])
    ->save();
  $relation = \Drupal::entityTypeManager()
    ->getStorage('relation')
    ->create([
    'relation_type' => 'test_relation_type',
  ]);
  $relation
    ->save();

  // Create relation with article node type.
  $relation->endpoints = [
    [
      'target_type' => 'node',
      'target_id' => $this->node1
        ->id(),
    ],
  ];
  $violations = $relation->endpoints
    ->validate();
  $this
    ->assertEqual(count($violations), 0, 'Allowed source bundle passed validation.');

  // Create relation with page node type.
  $relation->endpoints = [
    [
      'target_type' => 'node',
      'target_id' => $this->node3
        ->id(),
    ],
  ];
  $violations = $relation->endpoints
    ->validate();
  $this
    ->assertEqual(count($violations), 1);
  $this
    ->assertEqual($violations[0]
    ->getMessage(), t('Referenced entity %label does not belong to one of the supported bundles (%bundles).', [
    '%label' => $this->node3
      ->label(),
    '%bundles' => 'article',
  ]), 'Not allowed source bundle failed validation.');

  // Test endpoints with unsupported entity type.
  $vocabulary = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_vocabulary')
    ->create([
    'vid' => 'test_vocabulary',
    'name' => $this
      ->randomMachineName(),
  ]);
  $vocabulary
    ->save();
  $term = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->create([
    'name' => $this
      ->randomMachineName(),
    'vid' => $vocabulary
      ->id(),
  ]);
  $term
    ->save();
  $relation->endpoints = [
    [
      'target_type' => 'taxonomy_term',
      'target_id' => $term
        ->id(),
    ],
  ];
  $violations = $relation->endpoints
    ->validate();
  $this
    ->assertEqual(count($violations), 1);
  $this
    ->assertEqual($violations[0]
    ->getMessage(), t('No bundle is allowed for (%type)', [
    '%type' => 'taxonomy_term',
  ]), 'Not allowed entity failed validation.');
}