You are here

public function RelationshipNormalizerTest::testNormalize in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/jsonapi/tests/src/Kernel/Normalizer/RelationshipNormalizerTest.php \Drupal\Tests\jsonapi\Kernel\Normalizer\RelationshipNormalizerTest::testNormalize()

@covers ::normalize @dataProvider normalizeProvider

File

core/modules/jsonapi/tests/src/Kernel/Normalizer/RelationshipNormalizerTest.php, line 149

Class

RelationshipNormalizerTest
@coversDefaultClass \Drupal\jsonapi\Normalizer\RelationshipNormalizer @group jsonapi

Namespace

Drupal\Tests\jsonapi\Kernel\Normalizer

Code

public function testNormalize($entity_property_names, $field_name, $expected) {

  // Links cannot be generated in the test provider because the container
  // has not yet been set.
  $expected['links'] = [
    'self' => [
      'href' => Url::fromUri('base:/jsonapi/node/referencer/' . static::$referencerId . "/relationships/{$field_name}", [
        'query' => [
          'resourceVersion' => 'id:1',
        ],
      ])
        ->setAbsolute()
        ->toString(),
    ],
    'related' => [
      'href' => Url::fromUri('base:/jsonapi/node/referencer/' . static::$referencerId . "/{$field_name}", [
        'query' => [
          'resourceVersion' => 'id:1',
        ],
      ])
        ->setAbsolute()
        ->toString(),
    ],
  ];

  // Set up different field values.
  $this->referencer->{$field_name} = array_map(function ($entity_property_name) {
    $value = [
      'target_id' => $this->{$entity_property_name === 'image1a' ? 'image1' : $entity_property_name}
        ->id(),
    ];
    switch ($entity_property_name) {
      case 'image1':
        $value['alt'] = 'Cute llama';
        $value['title'] = 'My spirit animal';
        break;
      case 'image1a':
        $value['alt'] = 'Ugly llama';
        $value['title'] = 'My alter ego';
        break;
      case 'image2':
        $value['alt'] = 'Adorable llama';
        $value['title'] = 'My spirit animal 😍';
        break;
    }
    return $value;
  }, $entity_property_names);
  $resource_object = ResourceObject::createFromEntity($this->referencingResourceType, $this->referencer);
  $relationship = Relationship::createFromEntityReferenceField($resource_object, $resource_object
    ->getField($field_name));

  // Normalize.
  $actual = $this->normalizer
    ->normalize($relationship, 'api_json');

  // Assert.
  assert($actual instanceof CacheableNormalization);
  $this
    ->assertEquals($expected, $actual
    ->getNormalization());
}