EntityToJsonApiTest.php 7.67 KB
Newer Older
1 2 3 4 5
<?php

namespace Drupal\Tests\jsonapi_extras\Kernel;

use Drupal\Component\Serialization\Json;
6
use Drupal\Core\Entity\EntityInterface;
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\file\Entity\File;
use Drupal\jsonapi\LinkManager\LinkManager;
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 Prophecy\Argument;

/**
 * @coversDefaultClass \Drupal\jsonapi_extras\EntityToJsonApi
 * @group jsonapi
 * @group jsonapi_serializer
 * @group legacy
 *
 * @internal
 */
class EntityToJsonApiTest extends JsonapiKernelTestBase {

  use ImageFieldCreationTrait;

  /**
   * System under test.
   *
36
   * @var \Drupal\jsonapi_extras\EntityToJsonApi
37 38 39 40 41 42 43 44
   */
  protected $sut;

  /**
   * {@inheritdoc}
   */
  public static $modules = [
    'jsonapi',
45
    'jsonapi_extras',
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 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
    'field',
    'node',
    'serialization',
    'system',
    'taxonomy',
    'text',
    'user',
    'file',
    'image',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    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']);
    $this->nodeType = NodeType::create([
      'type' => 'article',
    ]);
    $this->nodeType->save();
    $this->createEntityReferenceField(
      'node',
      'article',
      'field_tags',
      'Tags',
      'taxonomy_term',
      'default',
      ['target_bundles' => ['tags']],
      FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED
    );

    $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,
      '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();

    $link_manager = $this->prophesize(LinkManager::class);
    $link_manager
145 146 147 148 149 150
      ->getEntityLink(
        Argument::any(),
        Argument::any(),
        Argument::type('array'),
        Argument::type('string')
      )
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
      ->willReturn('dummy_entity_link');
    $link_manager
      ->getRequestLink(Argument::any())
      ->willReturn('dummy_document_link');
    $this->container->set('jsonapi.link_manager', $link_manager->reveal());

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

    $this->role = Role::create([
      'id' => RoleInterface::ANONYMOUS_ID,
      'permissions' => [
        'access content',
      ],
    ]);
    $this->role->save();
166
    $this->sut = $this->container->get('jsonapi_extras.entity.to_jsonapi');
167 168 169 170 171 172 173 174
  }

  /**
   * @covers ::serialize
   * @covers ::normalize
   */
  public function testSerialize() {
    $entities = [
175 176 177 178 179 180
      [
        $this->node,
        ['field_tags'],
        [
          [
            'type' => 'taxonomy_term--tags',
181
            'id' => $this->term1->uuid(),
182
            'attributes' => [
183
              'tid' => (int) $this->term1->id(),
184 185 186 187 188
              'name' => $this->term1->label(),
            ],
          ],
          [
            'type' => 'taxonomy_term--tags',
189
            'id' => $this->term2->uuid(),
190
            'attributes' => [
191
              'tid' => (int) $this->term2->id(),
192 193 194 195 196 197 198 199
              'name' => $this->term2->label(),
            ],
          ],
        ],
      ],
      [$this->user, [], []],
      [$this->file, [], []],
      [$this->term1, [], []],
200
      // Make sure we also support configuration entities.
201 202 203
      [$this->vocabulary, [], []],
      [$this->nodeType, [], []],
      [$this->role, [], []],
204
    ];
205

206 207
    array_walk(
      $entities,
208 209 210
      function ($data) {
        list($entity, $include_fields, $expected_includes) = $data;
        $this->assertEntity($entity, $include_fields, $expected_includes);
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 243 244 245
  /**
   * Checks entity's serialization/normalization.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to serialize/normalize.
   * @param string[] $include_fields
   *   The list of fields to include.
   * @param array[] $expected_includes
   *   The list of partial structures of the "included" key.
   */
  protected function assertEntity(
    EntityInterface $entity,
    array $include_fields = [],
    array $expected_includes = []
  ) {
    $output = $this->sut->serialize($entity, $include_fields);

    static::assertInternalType('string', $output);
    $this->assertJsonApi(Json::decode($output));

    $output = $this->sut->normalize($entity, $include_fields);

    static::assertInternalType('array', $output);
    $this->assertJsonApi($output);

    // Check the includes if they were passed.
    if (!empty($include_fields)) {
      $this->assertJsonApiIncludes($output, $expected_includes);
    }
  }

246 247 248 249 250 251 252
  /**
   * Helper to assert if a string is valid JSON API.
   *
   * @param array $structured
   *   The JSON API data to check.
   */
  protected function assertJsonApi(array $structured) {
253 254 255
    static::assertNotEmpty($structured['data']['type']);
    static::assertNotEmpty($structured['data']['id']);
    static::assertNotEmpty($structured['data']['attributes']);
256
    static::assertInternalType('string', $structured['links']['self']);
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  }

  /**
   * Shallowly checks the list of includes.
   *
   * @param array $structured
   *   The JSON API data to check.
   * @param array[] $includes
   *   The list of partial structures of the "included" key.
   */
  protected function assertJsonApiIncludes(array $structured, array $includes) {
    static::assertFalse(
      empty($structured['included']),
      'The list of includes should is empty.'
    );

    foreach ($includes as $i => $include) {
      static::assertFalse(
        empty($structured['included'][$i]),
        sprintf('The include #%d does not exist.', $i)
      );
      static::assertSame(
        $include['type'],
        $structured['included'][$i]['type'],
        sprintf('The type of include #%d does not match expected value.', $i)
      );

      foreach ($include['attributes'] as $attribute => $expected_value) {
        static::assertSame(
          $expected_value,
          $structured['included'][$i]['attributes'][$attribute],
          sprintf(
            'The "%s" of include #%d doest match the expected value.',
            $attribute,
            $i
          )
        );
      }
    }
296 297 298
  }

}