You are here

public function FileEntityNormalizerTest::testImageFieldSerializePersist in File Entity (fieldable files) 8.2

Tests that image field is identical before and after de/serialization.

File

tests/src/Kernel/FileEntityNormalizerTest.php, line 163

Class

FileEntityNormalizerTest
Tests the File entity normalizer.

Namespace

Drupal\Tests\file_entity\Kernel

Code

public function testImageFieldSerializePersist() {

  // Create a node type.
  $node_type = NodeType::create(array(
    'type' => $this
      ->randomMachineName(),
  ));
  $node_type
    ->save();

  // Create a file.
  $file_name = $this
    ->randomMachineName() . '.jpg';
  file_put_contents("public://{$file_name}", $this
    ->randomString());
  $image = File::create(array(
    'uri' => "public://{$file_name}",
  ));
  $image
    ->save();

  // Attach a file field to the node type.
  $image_field_storage = FieldStorageConfig::create(array(
    'type' => 'image',
    'entity_type' => 'node',
    'field_name' => 'field_image',
  ));
  $image_field_storage
    ->save();
  $file_field_instance = FieldConfig::create(array(
    'field_storage' => $image_field_storage,
    'entity_type' => 'node',
    'bundle' => $node_type
      ->id(),
  ));
  $file_field_instance
    ->save();

  // Create a node referencing the image.
  $node = Node::create(array(
    'title' => 'A node with a image',
    'type' => $node_type
      ->id(),
    'field_image' => array(
      'target_id' => $image
        ->id(),
      'alt' => 'the image alternative',
      'title' => 'the title',
      'width' => 50,
      'height' => 50,
    ),
    'status' => TRUE,
  ));

  // Export.
  $serialized = $this->container
    ->get('serializer')
    ->serialize($node, 'hal_json');

  // Import again.
  $deserialized = $this->container
    ->get('serializer')
    ->deserialize($serialized, 'Drupal\\node\\Entity\\Node', 'hal_json');

  // Compare.
  $this
    ->assertEquals($node
    ->toArray()['field_image'], $deserialized
    ->toArray()['field_image'], "Image field persists.");
}