function BlockContentSaveTest::testImport

Same name in other branches
  1. 8.9.x core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php \Drupal\Tests\block_content\Functional\BlockContentSaveTest::testImport()
  2. 10 core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php \Drupal\Tests\block_content\Functional\BlockContentSaveTest::testImport()
  3. 11.x core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php \Drupal\Tests\block_content\Functional\BlockContentSaveTest::testImport()

Checks whether custom block IDs are saved properly during an import.

File

core/modules/block_content/tests/src/Functional/BlockContentSaveTest.php, line 38

Class

BlockContentSaveTest
Tests $block_content->save() for saving content.

Namespace

Drupal\Tests\block_content\Functional

Code

public function testImport() {
    // Custom block ID must be a number that is not in the database.
    $max_id = (int) \Drupal::entityQueryAggregate('block_content')->accessCheck(FALSE)
        ->aggregate('id', 'max')
        ->execute()[0]['id_max'];
    $test_id = $max_id + mt_rand(1000, 1000000);
    $info = $this->randomMachineName(8);
    $block_array = [
        'info' => $info,
        'body' => [
            'value' => $this->randomMachineName(32),
        ],
        'type' => 'basic',
        'id' => $test_id,
    ];
    $block = BlockContent::create($block_array);
    $block->enforceIsNew(TRUE);
    $block->save();
    // Verify that block_submit did not wipe the provided id.
    $this->assertEquals($test_id, $block->id(), 'Block imported using provide id');
    // Test the import saved.
    $block_by_id = BlockContent::load($test_id);
    $this->assertNotEmpty($block_by_id, 'Custom block load by block ID.');
    $this->assertSame($block_array['body']['value'], $block_by_id->body->value);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.