You are here

HookTokensTest.php in Node Summary Token From P Tags 1.x

Same filename and directory in other branches
  1. 1.0.x tests/src/HookTokensTest.php

File

tests/src/HookTokensTest.php
View source
<?php

namespace Drupal\Tests\node_summary_token_from_p;

use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\filter\Entity\FilterFormat;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\system\Kernel\Token\TokenReplaceKernelTestBase;
class HookTokensTest extends TokenReplaceKernelTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = [
    'node',
    'filter',
    'node_summary_token_from_p',
  ];

  /**
   * Cache.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface
   */
  protected $cache;

  /**
   * {@inheritDoc}
   */
  protected function setUp() {
    parent::setUp();
    $this
      ->installConfig([
      'filter',
      'node',
    ]);
    $this
      ->installEntitySchema('node');
    $this
      ->installSchema('node', [
      'node_access',
    ]);
    $article_node_type = NodeType::create([
      'type' => 'article',
      'name' => 'Article',
    ]);
    $article_node_type
      ->save();
    node_add_body_field($article_node_type);
    $article_node_type_without_body = NodeType::create([
      'type' => 'article_wo_body',
      'name' => 'Article without body',
    ]);
    $article_node_type_without_body
      ->save();
    FilterFormat::create([
      'format' => 'html',
      'name' => 'html',
      'filters' => [],
    ])
      ->save();

    // Add a text field to the content type.
    $field_storage = FieldStorageConfig::create([
      'entity_type' => 'node',
      'field_name' => 'field_text',
      'type' => 'text_long',
      'cardinality' => 1,
    ]);
    $field_storage
      ->save();
    $field = FieldConfig::create([
      'entity_type' => 'node',
      'bundle' => 'article_wo_body',
      'field_name' => 'field_text',
      'label' => 'field_text',
      'required' => FALSE,
    ]);
    $field
      ->save();

    /**
     * @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $entityDisplayRepository
     */
    $entityDisplayRepository = $this->container
      ->get('entity_display.repository');

    // Make sure field_text is shown.
    $display = $entityDisplayRepository
      ->getViewDisplay('node', 'article_wo_body');
    $display
      ->setComponent('field_text', [
      'type' => 'text_default',
    ]);
    $display
      ->save();
    $this->cache = $this->container
      ->get('cache.default');
  }

  /**
   * Test if the normal [node:summary] token still works as required.
   */
  public function testNodeSummaryTokenReplacement() {

    // Create a user and a node.
    $account = $this
      ->createUser();

    /* @var $node \Drupal\node\NodeInterface */
    $node = Node::create([
      'type' => 'article',
      'tnid' => 0,
      'uid' => $account
        ->id(),
      'title' => 'Title',
      'body' => [
        [
          'value' => 'Regular NODE body for the test.',
          'summary' => 'Fancy NODE summary.',
          'format' => 'plain_text',
        ],
      ],
    ]);
    $node
      ->save();

    // Generate and test tokens.
    $tests = [];
    $tests['[node:summary]'] = $node->body->summary_processed;
    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($node);
    $metadata_tests = [];
    $metadata_tests['[node:summary]'] = $base_bubbleable_metadata;

    // Test to make sure that we generated something for each token.
    $this
      ->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');
    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $this->tokenService
        ->replace($input, [
        'node' => $node,
      ], [
        'langcode' => $this->interfaceLanguage
          ->getId(),
      ], $bubbleable_metadata);
      $this
        ->assertEqual($output, $expected, new FormattableMarkup('Node token %token replaced.', [
        '%token' => $input,
      ]));
      $this
        ->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
    }

    // Repeat for a node without a summary.
    $node = Node::create([
      'type' => 'article',
      'uid' => $account
        ->id(),
      'title' => '<blink>Blinking Text</blink>',
      'body' => [
        [
          'value' => 'A string that looks random like TR5c2I',
          'format' => 'plain_text',
        ],
      ],
    ]);
    $node
      ->save();

    // Generate and test token - use full body as expected value.
    $tests = [];
    $tests['[node:summary]'] = $node->body->processed;

    // Test to make sure that we generated something for each token.
    $this
      ->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated for node without a summary.');
    foreach ($tests as $input => $expected) {
      $output = $this->tokenService
        ->replace($input, [
        'node' => $node,
      ], [
        'language' => $this->interfaceLanguage,
      ]);
      $this
        ->assertEqual($output, $expected, new FormattableMarkup('Node token %token replaced for node without a summary.', [
        '%token' => $input,
      ]));
    }
  }

  /**
   * Test if the [node:summary] token is filled from the field_text field.
   */
  public function testNodeSummaryTokenFromFieldTextReplacement() {

    // Create a user and a node.
    $account = $this
      ->createUser();

    /* @var $node \Drupal\node\NodeInterface */
    $node = Node::create([
      'type' => 'article_wo_body',
      'tnid' => 0,
      'uid' => $account
        ->id(),
      'title' => 'Title',
      'field_text' => [
        [
          'value' => '<p>This is sentence 1. This is sentence 2?</p><p>This is sentence 3!</p><p>This is sentence 4.</p>',
          'format' => 'html',
        ],
      ],
    ]);
    $node
      ->save();

    // Generate and test tokens.
    $tests = [];
    $tests['[node:summary]'] = 'This is sentence 1. This is sentence 2? This is sentence 3!';
    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($node);
    $metadata_tests = [];
    $metadata_tests['[node:summary]'] = $base_bubbleable_metadata;

    // Test to make sure that we generated something for each token.
    $this
      ->assertNotContains(0, array_map('strlen', $tests), 'No empty tokens generated.');
    foreach ($tests as $input => $expected) {
      $bubbleable_metadata = new BubbleableMetadata();
      $output = $this->tokenService
        ->replace($input, [
        'node' => $node,
      ], [
        'langcode' => $this->interfaceLanguage
          ->getId(),
      ], $bubbleable_metadata);
      $this
        ->assertEqual($output, $expected, new FormattableMarkup('Node token %token replaced.', [
        '%token' => $input,
      ]));
      $this
        ->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
    }
  }
  public function testCaching() {

    // Create a user and a node.
    $account = $this
      ->createUser();

    /* @var $node \Drupal\node\NodeInterface */
    $node = Node::create([
      'type' => 'article_wo_body',
      'tnid' => 0,
      'uid' => $account
        ->id(),
      'title' => 'Title',
      'field_text' => [
        [
          'value' => '<p>This is sentence 1. This is sentence 2?</p><p>This is sentence 3!</p><p>This is sentence 4.</p>',
          'format' => 'html',
        ],
      ],
    ]);
    $node
      ->save();
    $cid = 'node_summary_token_from_p:' . $node
      ->id();
    $this
      ->assertFalse($this->cache
      ->get($cid));
    $expected_cached_value = 'This is sentence 1. This is sentence 2? This is sentence 3!';
    $bubbleable_metadata = new BubbleableMetadata();
    $output = $this->tokenService
      ->replace('[node:summary]', [
      'node' => $node,
    ], [
      'langcode' => $this->interfaceLanguage
        ->getId(),
    ], $bubbleable_metadata);
    $this
      ->assertEquals($expected_cached_value, $output);
    $cached = $this->cache
      ->get($cid);
    $this
      ->assertNotFalse($cached);
    $this
      ->assertEquals($expected_cached_value, $cached->data);
    $node
      ->set('field_text', [
      'value' => '<p>Changed.</p><p>This is sentence 1. This is sentence 2?</p><p>This is sentence 3!</p><p>This is sentence 4.</p>',
      'format' => 'html',
    ]);
    $node
      ->save();
    $this
      ->assertEquals($expected_cached_value, $output);
    $expected_cached_value = 'Changed. This is sentence 1. This is sentence 2?';
    $bubbleable_metadata = new BubbleableMetadata();
    $output = $this->tokenService
      ->replace('[node:summary]', [
      'node' => $node,
    ], [
      'langcode' => $this->interfaceLanguage
        ->getId(),
    ], $bubbleable_metadata);
    $this
      ->assertEquals($expected_cached_value, $output);
    $cached = $this->cache
      ->get($cid);
    $this
      ->assertNotFalse($cached);
    $this
      ->assertEquals($expected_cached_value, $cached->data);
  }

}

Classes

Namesort descending Description
HookTokensTest