JsonApiDocumentTopLevelNormalizerTest.php 27.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
<?php

namespace Drupal\Tests\jsonapi\Kernel\Normalizer;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\jsonapi\JsonApiResource\ErrorCollection;
12
use Drupal\jsonapi\JsonApiResource\LabelOnlyResourceObject;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
use Drupal\jsonapi\JsonApiResource\LinkCollection;
use Drupal\jsonapi\JsonApiResource\NullIncludedData;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\JsonApiResource\ResourceObjectData;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Tests\image\Kernel\ImageFieldCreationTrait;
use Drupal\Tests\jsonapi\Kernel\JsonapiKernelTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\RoleInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * @coversDefaultClass \Drupal\jsonapi\Normalizer\JsonApiDocumentTopLevelNormalizer
 * @group jsonapi
 *
 * @internal
 */
class JsonApiDocumentTopLevelNormalizerTest extends JsonapiKernelTestBase {

  use ImageFieldCreationTrait;

  /**
   * {@inheritdoc}
   */
45
  protected static $modules = [
46 47 48 49 50 51 52 53 54 55 56 57
    'jsonapi',
    'field',
    'node',
    'serialization',
    'system',
    'taxonomy',
    'text',
    'filter',
    'user',
    'file',
    'image',
    'jsonapi_test_normalizers_kernel',
58
    'jsonapi_test_resource_type_building',
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
  ];

  /**
   * A node to normalize.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $node;

  /**
   * A user to normalize.
   *
   * @var \Drupal\user\Entity\User
   */
  protected $user;

  /**
   * The include resolver.
   *
   * @var \Drupal\jsonapi\IncludeResolver
   */
  protected $includeResolver;

82 83 84 85 86 87 88
  /**
   * The JSON:API resource type repository under test.
   *
   * @var \Drupal\jsonapi\ResourceType\ResourceTypeRepository
   */
  protected $resourceTypeRepository;

89 90 91
  /**
   * {@inheritdoc}
   */
92
  protected function setUp(): void {
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    parent::setUp();
    // Add the entity schemas.
    $this->installEntitySchema('node');
    $this->installEntitySchema('user');
    $this->installEntitySchema('taxonomy_term');
    $this->installEntitySchema('file');
    // Add the additional table schemas.
    $this->installSchema('system', ['sequences']);
    $this->installSchema('node', ['node_access']);
    $this->installSchema('user', ['users_data']);
    $this->installSchema('file', ['file_usage']);
    $type = NodeType::create([
      'type' => 'article',
    ]);
    $type->save();
    $this->createEntityReferenceField(
      'node',
      'article',
      'field_tags',
      'Tags',
      'taxonomy_term',
      'default',
      ['target_bundles' => ['tags']],
      FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
    );
    $this->createTextField('node', 'article', 'body', 'Body');

    $this->createImageField('field_image', 'article');

    $this->user = User::create([
      'name' => 'user1',
      'mail' => 'user@localhost',
    ]);
    $this->user2 = User::create([
      'name' => 'user2',
      'mail' => 'user2@localhost',
    ]);

    $this->user->save();
    $this->user2->save();

    $this->vocabulary = Vocabulary::create(['name' => 'Tags', 'vid' => 'tags']);
    $this->vocabulary->save();

    $this->term1 = Term::create([
      'name' => 'term1',
      'vid' => $this->vocabulary->id(),
    ]);
    $this->term2 = Term::create([
      'name' => 'term2',
      'vid' => $this->vocabulary->id(),
    ]);

    $this->term1->save();
    $this->term2->save();

    $this->file = File::create([
      'uri' => 'public://example.png',
      'filename' => 'example.png',
    ]);
    $this->file->save();

    $this->node = Node::create([
      'title' => 'dummy_title',
      'type' => 'article',
      'uid' => 1,
      'body' => [
        'format' => 'plain_text',
        'value' => $this->randomStringValidate(42),
      ],
      'field_tags' => [
        ['target_id' => $this->term1->id()],
        ['target_id' => $this->term2->id()],
      ],
      'field_image' => [
        [
          'target_id' => $this->file->id(),
          'alt' => 'test alt',
          'title' => 'test title',
          'width' => 10,
          'height' => 11,
        ],
      ],
    ]);

    $this->node->save();

    $this->nodeType = NodeType::load('article');

    Role::create([
      'id' => RoleInterface::ANONYMOUS_ID,
      'permissions' => [
        'access content',
      ],
    ])->save();

    $this->includeResolver = $this->container->get('jsonapi.include_resolver');
190
    $this->resourceTypeRepository = $this->container->get('jsonapi.resource_type.repository');
191 192 193 194 195
  }

  /**
   * {@inheritdoc}
   */
196
  public function tearDown(): void {
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    if ($this->node) {
      $this->node->delete();
    }
    if ($this->term1) {
      $this->term1->delete();
    }
    if ($this->term2) {
      $this->term2->delete();
    }
    if ($this->vocabulary) {
      $this->vocabulary->delete();
    }
    if ($this->user) {
      $this->user->delete();
    }
    if ($this->user2) {
      $this->user2->delete();
    }
  }

  /**
   * @covers ::normalize
   */
  public function testNormalize() {
    list($request, $resource_type) = $this->generateProphecies('node', 'article');

    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $includes = $this->includeResolver->resolve($resource_object, 'uid,field_tags,field_image');

    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize(
        new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1), $includes, new LinkCollection([])),
        'api_json',
        [
          'resource_type' => $resource_type,
          'account' => NULL,
          'sparse_fieldset' => [
            'node--article' => [
              'title',
              'node_type',
              'uid',
              'field_tags',
              'field_image',
            ],
            'user--user' => [
243
              'display_name',
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
            ],
          ],
          'include' => [
            'uid',
            'field_tags',
            'field_image',
          ],
        ]
      );
    $normalized = $jsonapi_doc_object->getNormalization();

    // @see http://jsonapi.org/format/#document-jsonapi-object
    $this->assertEquals($normalized['jsonapi']['version'], '1.0');
    $this->assertEquals($normalized['jsonapi']['meta']['links']['self']['href'], 'http://jsonapi.org/format/1.0/');

    $this->assertSame($normalized['data']['attributes']['title'], 'dummy_title');
    $this->assertEquals($normalized['data']['id'], $this->node->uuid());
    $this->assertSame([
      'data' => [
        'type' => 'node_type--node_type',
        'id' => NodeType::load('article')->uuid(),
      ],
      'links' => [
        'related' => ['href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node->uuid() . '/node_type', ['query' => ['resourceVersion' => 'id:' . $this->node->getRevisionId()]])->setAbsolute()->toString(TRUE)->getGeneratedUrl()],
268
        'self' => ['href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node->uuid() . '/relationships/node_type', ['query' => ['resourceVersion' => 'id:' . $this->node->getRevisionId()]])->setAbsolute()->toString(TRUE)->getGeneratedUrl()],
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
      ],
    ], $normalized['data']['relationships']['node_type']);
    $this->assertTrue(!isset($normalized['data']['attributes']['created']));
    $this->assertEquals([
      'alt' => 'test alt',
      'title' => 'test title',
      'width' => 10,
      'height' => 11,
    ], $normalized['data']['relationships']['field_image']['data']['meta']);
    $this->assertSame('node--article', $normalized['data']['type']);
    $this->assertEquals([
      'data' => [
        'type' => 'user--user',
        'id' => $this->user->uuid(),
      ],
      'links' => [
        'self' => ['href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node->uuid() . '/relationships/uid', ['query' => ['resourceVersion' => 'id:' . $this->node->getRevisionId()]])->setAbsolute()->toString(TRUE)->getGeneratedUrl()],
        'related' => ['href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node->uuid() . '/uid', ['query' => ['resourceVersion' => 'id:' . $this->node->getRevisionId()]])->setAbsolute()->toString(TRUE)->getGeneratedUrl()],
      ],
    ], $normalized['data']['relationships']['uid']);
    $this->assertTrue(empty($normalized['meta']['omitted']));
    $this->assertSame($this->user->uuid(), $normalized['included'][0]['id']);
    $this->assertSame('user--user', $normalized['included'][0]['type']);
292
    $this->assertSame('user1', $normalized['included'][0]['attributes']['display_name']);
293 294 295 296 297 298 299 300
    $this->assertCount(1, $normalized['included'][0]['attributes']);
    $this->assertSame($this->term1->uuid(), $normalized['included'][1]['id']);
    $this->assertSame('taxonomy_term--tags', $normalized['included'][1]['type']);
    $this->assertSame($this->term1->label(), $normalized['included'][1]['attributes']['name']);
    $this->assertCount(12, $normalized['included'][1]['attributes']);
    $this->assertTrue(!isset($normalized['included'][1]['attributes']['created']));
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
301
    $this->assertSame(
302 303 304 305 306 307 308 309 310 311 312 313 314
      ['file:1', 'node:1', 'taxonomy_term:1', 'taxonomy_term:2', 'user:1'],
      $jsonapi_doc_object->getCacheTags()
    );
    $this->assertSame(
      Cache::PERMANENT,
      $jsonapi_doc_object->getCacheMaxAge()
    );
  }

  /**
   * @covers ::normalize
   */
  public function testNormalizeRelated() {
315
    $this->markTestIncomplete('This fails and should be fixed by https://www.drupal.org/project/drupal/issues/2922121');
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    list($request, $resource_type) = $this->generateProphecies('node', 'article', 'uid');
    $request->query = new ParameterBag([
      'fields' => [
        'user--user' => 'name,roles',
      ],
      'include' => 'roles',
    ]);
    $document_wrapper = $this->prophesize(JsonApiDocumentTopLevel::class);
    $author = $this->node->get('uid')->entity;
    $document_wrapper->getData()->willReturn($author);

    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize(
        $document_wrapper->reveal(),
        'api_json',
        [
          'resource_type' => $resource_type,
          'account' => NULL,
        ]
      );
    $normalized = $jsonapi_doc_object->getNormalization();
    $this->assertSame($normalized['data']['attributes']['name'], 'user1');
    $this->assertEquals($normalized['data']['id'], User::load(1)->uuid());
    $this->assertEquals($normalized['data']['type'], 'user--user');
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
    $this->assertSame(['user:1'], $jsonapi_doc_object->getCacheTags());
    $this->assertSame(Cache::PERMANENT, $jsonapi_doc_object->getCacheMaxAge());
  }

  /**
   * @covers ::normalize
   */
  public function testNormalizeUuid() {
    list($request, $resource_type) = $this->generateProphecies('node', 'article', 'uuid');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $include_param = 'uid,field_tags';
    $includes = $this->includeResolver->resolve($resource_object, $include_param);
    $document_wrapper = new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1), $includes, new LinkCollection([]));

    $request->query = new ParameterBag([
      'fields' => [
        'node--article' => 'title,node_type,uid,field_tags',
        'user--user' => 'name',
      ],
      'include' => $include_param,
    ]);

    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize(
        $document_wrapper,
        'api_json',
        [
          'resource_type' => $resource_type,
          'account' => NULL,
          'include' => [
            'uid',
            'field_tags',
          ],
        ]
      );
    $normalized = $jsonapi_doc_object->getNormalization();
    $this->assertStringMatchesFormat($this->node->uuid(), $normalized['data']['id']);
    $this->assertEquals($this->node->type->entity->uuid(), $normalized['data']['relationships']['node_type']['data']['id']);
    $this->assertEquals($this->user->uuid(), $normalized['data']['relationships']['uid']['data']['id']);
    $this->assertFalse(empty($normalized['included'][0]['id']));
    $this->assertTrue(empty($normalized['meta']['omitted']));
    $this->assertEquals($this->user->uuid(), $normalized['included'][0]['id']);
    $this->assertCount(1, $normalized['included'][0]['attributes']);
    $this->assertCount(12, $normalized['included'][1]['attributes']);
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
391
    $this->assertSame(
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
      ['node:1', 'taxonomy_term:1', 'taxonomy_term:2', 'user:1'],
      $jsonapi_doc_object->getCacheTags()
    );
  }

  /**
   * @covers ::normalize
   */
  public function testNormalizeException() {
    $normalized = $this
      ->container
      ->get('jsonapi.serializer')
      ->normalize(
        new JsonApiDocumentTopLevel(new ErrorCollection([new BadRequestHttpException('Lorem')]), new NullIncludedData(), new LinkCollection([])),
        'api_json',
        []
      )->getNormalization();
    $this->assertNotEmpty($normalized['errors']);
    $this->assertArrayNotHasKey('data', $normalized);
    $this->assertEquals(400, $normalized['errors'][0]['status']);
    $this->assertEquals('Lorem', $normalized['errors'][0]['detail']);
    $this->assertEquals([
      'info' => [
        'href' => 'http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1',
      ],
      'via' => ['href' => 'http://localhost/'],
    ], $normalized['errors'][0]['links']);
  }

421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
  /**
   * Test the message and exceptions thrown when we are requesting additional
   * field values for Label only resource.
   */
  public function testAliasFieldRouteException() {
    $this->assertSame('uid', $this->resourceTypeRepository->getByTypeName('node--article')->getPublicName('uid'));
    $this->assertSame('roles', $this->resourceTypeRepository->getByTypeName('user--user')->getPublicName('roles'));
    $resource_type_field_aliases = [
      'node--article' => [
        'uid' => 'author',
      ],
      'user--user' => [
        'roles' => 'user_roles',
      ],
    ];
    \Drupal::state()->set('jsonapi_test_resource_type_builder.resource_type_field_aliases', $resource_type_field_aliases);
    Cache::invalidateTags(['jsonapi_resource_types']);
    $this->assertSame('author', $this->resourceTypeRepository->getByTypeName('node--article')->getPublicName('uid'));
    $this->assertSame('user_roles', $this->resourceTypeRepository->getByTypeName('user--user')->getPublicName('roles'));

    // Create the request to fetch the articles and fetch included user.
    list($request, $resource_type) = $this->generateProphecies('node', 'article');
    $user = User::load($this->node->getOwnerId());

    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    list($request, $user_resource_type) = $this->generateProphecies('user', 'user');
    $resource_object_user = LabelOnlyResourceObject::createFromEntity($user_resource_type, $user);
    $includes = $this->includeResolver->resolve($resource_object_user, 'user_roles');

    /** @var \Drupal\jsonapi\Normalizer\Value\CacheableNormalization $jsonapi_doc_object */
    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize(
        new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object, $resource_object_user], 2), $includes, new LinkCollection([])),
        'api_json',
        [
          'resource_type' => $resource_type,
          'account' => NULL,
          'sparse_fieldset' => [
            'node--article' => [
              'title',
              'node_type',
              'uid',
            ],
            'user--user' => [
              'user_roles',
            ],
          ],
          'include' => [
            'user_roles',
          ],
        ],
      )->getNormalization();
    $this->assertNotEmpty($jsonapi_doc_object['meta']['omitted']);
    foreach ($jsonapi_doc_object['meta']['omitted']['links'] as $key => $link) {
      if (strpos($key, 'item--') === 0) {
        // Ensure that resource link contains url with the alias field.
        $resource_link = Url::fromUri('internal:/jsonapi/user/user/' . $user->uuid() . '/user_roles')->setAbsolute()->toString(TRUE);
        $this->assertEquals($resource_link->getGeneratedUrl(), $link['href']);
        $this->assertEquals("The current user is not allowed to view this relationship. The user only has authorization for the 'view label' operation.", $link['meta']['detail']);
      }
    }
  }

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  /**
   * @covers ::normalize
   */
  public function testNormalizeConfig() {
    list($request, $resource_type) = $this->generateProphecies('node_type', 'node_type', 'id');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->nodeType);
    $document_wrapper = new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1), new NullIncludedData(), new LinkCollection([]));

    $jsonapi_doc_object = $this
      ->getNormalizer()
      ->normalize($document_wrapper, 'api_json', [
        'resource_type' => $resource_type,
        'account' => NULL,
        'sparse_fieldset' => [
          'node_type--node_type' => [
            'description',
            'display_submitted',
          ],
        ],
      ]);
    $normalized = $jsonapi_doc_object->getNormalization();
    $this->assertSame(['description', 'display_submitted'], array_keys($normalized['data']['attributes']));
    $this->assertSame($normalized['data']['id'], NodeType::load('article')->uuid());
    $this->assertSame($normalized['data']['type'], 'node_type--node_type');
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
    $this->assertSame(['config:node.type.article'], $jsonapi_doc_object->getCacheTags());
  }

  /**
   * Try to POST a node and check if it exists afterwards.
   *
   * @covers ::denormalize
   */
  public function testDenormalize() {
    $payload = '{"data":{"type":"article","attributes":{"title":"Testing article"}}}';

    list($request, $resource_type) = $this->generateProphecies('node', 'article', 'id');
    $node = $this
      ->getNormalizer()
      ->denormalize(Json::decode($payload), NULL, 'api_json', [
        'resource_type' => $resource_type,
      ]);
    $this->assertInstanceOf(Node::class, $node);
    $this->assertSame('Testing article', $node->getTitle());
  }

  /**
   * Try to POST a node and check if it exists afterwards.
   *
   * @covers ::denormalize
   */
  public function testDenormalizeUuid() {
    $configurations = [
      // Good data.
      [
        [
          [$this->term2->uuid(), $this->term1->uuid()],
          $this->user2->uuid(),
        ],
        [
          [$this->term2->id(), $this->term1->id()],
          $this->user2->id(),
        ],
      ],
      // Good data, without any tags.
      [
        [
          [],
          $this->user2->uuid(),
        ],
        [
          [],
          $this->user2->id(),
        ],
      ],
      // Bad data in first tag.
      [
        [
          ['invalid-uuid', $this->term1->uuid()],
          $this->user2->uuid(),
        ],
        [
          [$this->term1->id()],
          $this->user2->id(),
        ],
        'taxonomy_term--tags:invalid-uuid',
      ],
      // Bad data in user and first tag.
      [
        [
          ['invalid-uuid', $this->term1->uuid()],
          'also-invalid-uuid',
        ],
        [
          [$this->term1->id()],
          NULL,
        ],
        'user--user:also-invalid-uuid',
      ],
    ];

    foreach ($configurations as $configuration) {
      list($payload_data, $expected) = $this->denormalizeUuidProviderBuilder($configuration);
      $payload = Json::encode($payload_data);

      list($request, $resource_type) = $this->generateProphecies('node', 'article');
      $this->container->get('request_stack')->push($request);
      try {
        $node = $this
          ->getNormalizer()
          ->denormalize(Json::decode($payload), NULL, 'api_json', [
            'resource_type' => $resource_type,
          ]);
      }
      catch (NotFoundHttpException $e) {
        $non_existing_resource_identifier = $configuration[2];
        $this->assertEquals("The resource identified by `$non_existing_resource_identifier` (given as a relationship item) could not be found.", $e->getMessage());
        continue;
      }

      /* @var \Drupal\node\Entity\Node $node */
      $this->assertInstanceOf(Node::class, $node);
      $this->assertSame('Testing article', $node->getTitle());
      if (!empty($expected['user_id'])) {
        $owner = $node->getOwner();
        $this->assertEquals($expected['user_id'], $owner->id());
      }
      $tags = $node->get('field_tags')->getValue();
      if (!empty($expected['tag_ids'][0])) {
        $this->assertEquals($expected['tag_ids'][0], $tags[0]['target_id']);
      }
      else {
        $this->assertArrayNotHasKey(0, $tags);
      }
      if (!empty($expected['tag_ids'][1])) {
        $this->assertEquals($expected['tag_ids'][1], $tags[1]['target_id']);
      }
      else {
        $this->assertArrayNotHasKey(1, $tags);
      }
    }
  }

  /**
   * Tests denormalization for related resources with missing or invalid types.
   */
  public function testDenormalizeInvalidTypeAndNoType() {
    $payload_data = [
      'data' => [
        'type' => 'node--article',
        'attributes' => [
          'title' => 'Testing article',
          'id' => '33095485-70D2-4E51-A309-535CC5BC0115',
        ],
        'relationships' => [
          'uid' => [
            'data' => [
              'type' => 'user--user',
              'id' => $this->user2->uuid(),
            ],
          ],
          'field_tags' => [
            'data' => [
              [
                'type' => 'foobar',
                'id' => $this->term1->uuid(),
              ],
            ],
          ],
        ],
      ],
    ];

    // Test relationship member with invalid type.
    $payload = Json::encode($payload_data);
    list($request, $resource_type) = $this->generateProphecies('node', 'article');
    $this->container->get('request_stack')->push($request);
    try {
      $this
        ->getNormalizer()
        ->denormalize(Json::decode($payload), NULL, 'api_json', [
          'resource_type' => $resource_type,
        ]);

      $this->fail('No assertion thrown for invalid type');
    }
    catch (BadRequestHttpException $e) {
      $this->assertEquals("Invalid type specified for related resource: 'foobar'", $e->getMessage());
    }

    // Test relationship member with no type.
    unset($payload_data['data']['relationships']['field_tags']['data'][0]['type']);

    $payload = Json::encode($payload_data);
    list($request, $resource_type) = $this->generateProphecies('node', 'article');
    $this->container->get('request_stack')->push($request);
    try {
      $this->container->get('jsonapi_test_normalizers_kernel.jsonapi_document_toplevel')
        ->denormalize(Json::decode($payload), NULL, 'api_json', [
          'resource_type' => $resource_type,
        ]);

      $this->fail('No assertion thrown for missing type');
    }
    catch (BadRequestHttpException $e) {
      $this->assertEquals("No type specified for related resource", $e->getMessage());
    }
  }

  /**
   * We cannot use a PHPUnit data provider because our data depends on $this.
   *
   * @param array $options
   *   Options for how to construct test data.
   *
   * @return array
   *   The test data.
   */
  protected function denormalizeUuidProviderBuilder(array $options) {
    list($input, $expected) = $options;
    list($input_tag_uuids, $input_user_uuid) = $input;
    list($expected_tag_ids, $expected_user_id) = $expected;

    $node = [
      [
        'data' => [
          'type' => 'node--article',
          'attributes' => [
            'title' => 'Testing article',
          ],
          'relationships' => [
            'uid' => [
              'data' => [
                'type' => 'user--user',
                'id' => $input_user_uuid,
              ],
            ],
            'field_tags' => [
              'data' => [],
            ],
          ],
        ],
      ],
      [
        'tag_ids' => $expected_tag_ids,
        'user_id' => $expected_user_id,
      ],
    ];

    if (isset($input_tag_uuids[0])) {
      $node[0]['data']['relationships']['field_tags']['data'][0] = [
        'type' => 'taxonomy_term--tags',
        'id' => $input_tag_uuids[0],
      ];
    }
    if (isset($input_tag_uuids[1])) {
      $node[0]['data']['relationships']['field_tags']['data'][1] = [
        'type' => 'taxonomy_term--tags',
        'id' => $input_tag_uuids[1],
      ];
    }
    return $node;
  }

  /**
   * Ensure that cacheability metadata is properly added.
   *
   * @param \Drupal\Core\Cache\CacheableMetadata $expected_metadata
   *   The expected cacheable metadata.
   * @param array|null $fields
   *   Fields to include in the response, keyed by resource type.
   * @param array|null $includes
   *   Resources paths to include in the response.
   *
   * @dataProvider testCacheableMetadataProvider
   */
  public function testCacheableMetadata(CacheableMetadata $expected_metadata, $fields = NULL, $includes = NULL) {
    list($request, $resource_type) = $this->generateProphecies('node', 'article');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $context = [
      'resource_type' => $resource_type,
      'account' => NULL,
    ];
    $jsonapi_doc_object = $this->getNormalizer()->normalize(new JsonApiDocumentTopLevel(new ResourceObjectData([$resource_object], 1), new NullIncludedData(), new LinkCollection([])), 'api_json', $context);
770 771 772 773 774 775
    foreach ($expected_metadata->getCacheTags() as $tag) {
      $this->assertContains($tag, $jsonapi_doc_object->getCacheTags());
    }
    foreach ($expected_metadata->getCacheContexts() as $context) {
      $this->assertContains($context, $jsonapi_doc_object->getCacheContexts());
    }
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    $this->assertSame($expected_metadata->getCacheMaxAge(), $jsonapi_doc_object->getCacheMaxAge());
  }

  /**
   * Provides test cases for asserting cacheable metadata behavior.
   */
  public function testCacheableMetadataProvider() {
    $cacheable_metadata = function ($metadata) {
      return CacheableMetadata::createFromRenderArray(['#cache' => $metadata]);
    };

    return [
      [
        $cacheable_metadata(['contexts' => ['languages:language_interface']]),
        ['node--article' => 'body'],
      ],
    ];
  }

  /**
   * Decorates a request with sparse fieldsets and includes.
   */
  protected function decorateRequest(Request $request, array $fields = NULL, array $includes = NULL) {
    $parameters = new ParameterBag();
    $parameters->add($fields ? ['fields' => $fields] : []);
    $parameters->add($includes ? ['include' => $includes] : []);
    $request->query = $parameters;
    return $request;
  }

  /**
   * Helper to load the normalizer.
   */
  protected function getNormalizer() {
    $normalizer_service = $this->container->get('jsonapi_test_normalizers_kernel.jsonapi_document_toplevel');
    // Simulate what happens when this normalizer service is used via the
    // serializer service, as it is meant to be used.
    $normalizer_service->setSerializer($this->container->get('jsonapi.serializer'));
    return $normalizer_service;
  }

  /**
   * Generates the prophecies for the mocked entity request.
   *
   * @param string $entity_type_id
   *   The ID of the entity type. Ex: node.
   * @param string $bundle
   *   The bundle. Ex: article.
   *
   * @return array
   *   A numeric array containing the request and the ResourceType.
   *
   * @throws \Exception
   */
  protected function generateProphecies($entity_type_id, $bundle) {
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->get($entity_type_id, $bundle);

    return [new Request(), $resource_type];
  }

}