You are here

public function EntityReferenceFieldNormalizerTest::testNormalize in JSON:API 8.2

@covers ::normalize @dataProvider normalizeProvider

File

tests/src/Kernel/Normalizer/EntityReferenceFieldNormalizerTest.php, line 148

Class

EntityReferenceFieldNormalizerTest
@coversDefaultClass \Drupal\jsonapi\Normalizer\EntityReferenceFieldNormalizer @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);

  // Normalize.
  $actual = $this->normalizer
    ->normalize($this->referencer->{$field_name}, 'api_json', [
    'account' => $this->account,
    'resource_object' => ResourceObject::createFromEntity($this->referencingResourceType, $this->referencer),
  ]);

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