You are here

public function LinkCollectionNormalizerTest::testLinkAccess in Drupal 9

Tests the link collection normalizer.

@dataProvider linkAccessTestData

File

core/modules/jsonapi/tests/src/Kernel/Normalizer/LinkCollectionNormalizerTest.php, line 111

Class

LinkCollectionNormalizerTest
@coversDefaultClass \Drupal\jsonapi\Normalizer\LinkCollectionNormalizer @group jsonapi

Namespace

Drupal\Tests\jsonapi\Kernel\Normalizer

Code

public function testLinkAccess($current_user_id, $edit_form_uid, $expected_link_keys, $expected_cache_contexts) {

  // Get the current user and an edit-form URL.
  foreach ($this->testUsers as $user) {
    $uid = (int) $user
      ->id();
    if ($uid === $current_user_id) {
      $current_user = $user;
    }
    if ($uid === $edit_form_uid) {
      $edit_form_url = $user
        ->toUrl('edit-form');
    }
  }
  assert(isset($current_user));
  assert(isset($edit_form_url));

  // Create a link collection to normalize.
  $mock_resource_object = $this
    ->createMock(ResourceObject::class);
  $link_collection = new LinkCollection([
    'edit-form' => new Link(new CacheableMetadata(), $edit_form_url, 'edit-form', [
      'title' => 'Edit',
    ]),
  ]);
  $link_collection = $link_collection
    ->withContext($mock_resource_object);

  // Normalize the collection.
  $actual_normalization = $this
    ->getNormalizer($current_user)
    ->normalize($link_collection);

  // Check that it returned the expected value object.
  $this
    ->assertInstanceOf(CacheableNormalization::class, $actual_normalization);

  // Get the raw normalized data.
  $actual_data = $actual_normalization
    ->getNormalization();
  $this
    ->assertIsArray($actual_data);

  // Check that the expected links are present and unexpected links are
  // absent.
  $actual_link_keys = array_keys($actual_data);
  sort($expected_link_keys);
  sort($actual_link_keys);
  $this
    ->assertSame($expected_link_keys, $actual_link_keys);

  // Check that the expected cache contexts were added.
  $actual_cache_contexts = $actual_normalization
    ->getCacheContexts();
  sort($expected_cache_contexts);
  sort($actual_cache_contexts);
  $this
    ->assertSame($expected_cache_contexts, $actual_cache_contexts);

  // If the edit-form link was present, check that it has the correct href.
  if (isset($actual_data['edit-form'])) {
    $this
      ->assertSame($actual_data['edit-form'], [
      'href' => $edit_form_url
        ->setAbsolute()
        ->toString(),
      'meta' => [
        'title' => 'Edit',
      ],
    ]);
  }
}