You are here

public function MessageCheckAndDeleteWorkerTest::testProcessItem in Message 8

Tests that items are only deleted when appropriate.

@covers ::processItem

File

tests/src/Kernel/Plugin/QueueWorker/MessageCheckAndDeleteWorkerTest.php, line 87

Class

MessageCheckAndDeleteWorkerTest
Tests the multi-valued field check and delete after entity deletion.

Namespace

Drupal\Tests\message\Kernel\Plugin\QueueWorker

Code

public function testProcessItem() {

  // Create a message template.
  $template = strtolower($this
    ->randomMachineName());
  $this
    ->createMessageTemplate($template, 'Dummy message', 'This is a dummy message text', [
    'Dummy message template.',
  ]);

  // Add a node reference field to the template.
  $field_name = strtolower($this
    ->randomMachineName());
  FieldStorageConfig::create([
    'field_name' => $field_name,
    'entity_type' => 'message',
    'translatable' => FALSE,
    'entity_types' => [],
    'settings' => [
      'target_type' => 'node',
    ],
    'type' => 'entity_reference',
    'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED,
  ])
    ->save();
  FieldConfig::create([
    'label' => 'Entity reference field',
    'field_name' => $field_name,
    'entity_type' => 'message',
    'bundle' => $template,
    'settings' => [
      'handler' => 'default',
      'handler_settings' => [
        'target_bundles' => [
          'node',
        ],
        'auto_create' => TRUE,
      ],
    ],
  ])
    ->save();
  $this
    ->createPlugin();

  // Create a message that still has at least one valid reference. This should
  // not be deleted.
  $node_type = $this
    ->createContentType();
  $node = Node::create([
    'type' => $node_type
      ->id(),
    'title' => 'Zebras rule',
  ]);
  $node
    ->save();
  $message = Message::create([
    'template' => $template,
  ]);
  $message
    ->set($field_name, [
    1,
    100,
  ]);
  $message
    ->save();
  $this->plugin
    ->processItem([
    $message
      ->id() => [
      $field_name,
    ],
  ]);
  $this
    ->assertNotEmpty(Message::load($message
    ->id()), 'Message exists after deleting one of two referenced nodes.');

  // If there are no valid references left, then the message should be
  // deleted.
  $node
    ->delete();
  $this->plugin
    ->processItem([
    $message
      ->id() => [
      $field_name,
    ],
  ]);
  $this
    ->assertEmpty(Message::load($message
    ->id()), 'Message deleted after deleting all referenced nodes.');
}