TokenTest.php 8.25 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Tests\Core\Utility\TokenTest.
6 7 8 9
 */

namespace Drupal\Tests\Core\Utility;

10 11
use Drupal\Core\Cache\Context\CacheContextsManager;
use Drupal\Core\DependencyInjection\ContainerBuilder;
12
use Drupal\Core\Language\LanguageInterface;
13
use Drupal\Core\Render\BubbleableMetadata;
14 15 16 17
use Drupal\Core\Utility\Token;
use Drupal\Tests\UnitTestCase;

/**
18
 * @coversDefaultClass \Drupal\Core\Utility\Token
19
 * @group Utility
20
 */
21
class TokenTest extends UnitTestCase {
22 23 24 25 26 27 28 29 30 31 32

  /**
   * The cache used for testing.
   *
   * @var \Drupal\Core\Cache\CacheBackendInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $cache;

  /**
   * The language manager used for testing.
   *
33
   * @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject
34 35 36 37 38 39 40 41 42 43
   */
  protected $languageManager;

  /**
   * The module handler service used for testing.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $moduleHandler;

44 45 46 47 48 49 50
  /**
   * The language interface used for testing.
   *
   * @var \Drupal\Core\Language\LanguageInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $language;

51 52 53 54 55 56 57
  /**
   * The token service under test.
   *
   * @var \Drupal\Core\Utility\Token|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $token;

58 59 60 61 62 63 64
  /**
   * The cache tags invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $cacheTagsInvalidator;

65 66 67 68 69 70 71 72 73 74 75 76 77 78
  /**
   * The cache contexts manager.
   *
   * @var \Drupal\Core\Cache\Context\CacheContextsManager
   */
  protected $cacheContextManager;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $renderer;

79 80 81
  /**
   * {@inheritdoc}
   */
82
  protected function setUp() {
83 84
    $this->cache = $this->getMock('\Drupal\Core\Cache\CacheBackendInterface');

85
    $this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface');
86 87 88

    $this->moduleHandler = $this->getMock('\Drupal\Core\Extension\ModuleHandlerInterface');

89 90
    $this->language = $this->getMock('\Drupal\Core\Language\LanguageInterface');

91 92
    $this->cacheTagsInvalidator = $this->getMock('\Drupal\Core\Cache\CacheTagsInvalidatorInterface');

93 94 95 96 97 98 99 100 101 102 103
    $this->renderer = $this->getMock('Drupal\Core\Render\RendererInterface');

    $this->token = new Token($this->moduleHandler, $this->cache, $this->languageManager, $this->cacheTagsInvalidator, $this->renderer);

    $container = new ContainerBuilder();
    $this->cacheContextManager = new CacheContextsManager($container, [
      'current_user',
      'custom_context'
    ]);
    $container->set('cache_contexts_manager', $this->cacheContextManager);
    \Drupal::setContainer($container);
104 105 106
  }

  /**
107
   * @covers ::getInfo
108 109 110 111 112
   */
  public function testGetInfo() {
    $token_info = array(
      'types' => array(
        'foo' => array(
113
          'name' => $this->randomMachineName(),
114 115 116 117
        ),
      ),
    );

118 119 120
    $this->language->expects($this->atLeastOnce())
      ->method('getId')
      ->will($this->returnValue($this->randomMachineName()));
121 122 123

    $this->languageManager->expects($this->once())
      ->method('getCurrentLanguage')
124
      ->with(LanguageInterface::TYPE_CONTENT)
125
      ->will($this->returnValue($this->language));
126 127 128 129 130 131 132

    // The persistent cache must only be hit once, after which the info is
    // cached statically.
    $this->cache->expects($this->once())
      ->method('get');
    $this->cache->expects($this->once())
      ->method('set')
133
      ->with('token_info:' . $this->language->getId(), $token_info);
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151

    $this->moduleHandler->expects($this->once())
      ->method('invokeAll')
      ->with('token_info')
      ->will($this->returnValue($token_info));
    $this->moduleHandler->expects($this->once())
      ->method('alter')
      ->with('token_info', $token_info);

    // Get the information for the first time. The cache should be checked, the
    // hooks invoked, and the info should be set to the cache should.
    $this->token->getInfo();
    // Get the information for the second time. The data must be returned from
    // the static cache, so the persistent cache must not be accessed and the
    // hooks must not be invoked.
    $this->token->getInfo();
  }

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 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 246 247 248 249 250 251 252 253
  /**
   * @covers ::replace
   */
  public function testReplaceWithBubbleableMetadataObject() {
    $this->moduleHandler->expects($this->any())
      ->method('invokeAll')
      ->willReturn(['[node:title]' => 'hello world']);

    $bubbleable_metadata = new BubbleableMetadata();
    $bubbleable_metadata->setCacheContexts(['current_user']);
    $bubbleable_metadata->setCacheMaxAge(12);

    $node = $this->prophesize('Drupal\node\NodeInterface');
    $node->getCacheTags()->willReturn(['node:1']);
    $node->getCacheContexts()->willReturn(['custom_context']);
    $node->getCacheMaxAge()->willReturn(10);
    $node = $node->reveal();

    $result = $this->token->replace('[node:title]', ['node' => $node], [], $bubbleable_metadata);
    $this->assertEquals('hello world', $result);

    $this->assertEquals(['node:1'], $bubbleable_metadata->getCacheTags());
    $this->assertEquals([
      'current_user',
      'custom_context'
    ], $bubbleable_metadata->getCacheContexts());
    $this->assertEquals(10, $bubbleable_metadata->getCacheMaxAge());
  }

  /**
   * @covers ::replace
   */
  public function testReplaceWithHookTokensWithBubbleableMetadata() {
    $this->moduleHandler->expects($this->any())
      ->method('invokeAll')
      ->willReturnCallback(function ($hook_name, $args) {
        $cacheable_metadata = $args[4];
        $cacheable_metadata->addCacheContexts(['custom_context']);
        $cacheable_metadata->addCacheTags(['node:1']);
        $cacheable_metadata->setCacheMaxAge(10);

        return ['[node:title]' => 'hello world'];
      });

    $node = $this->prophesize('Drupal\node\NodeInterface');
    $node->getCacheContexts()->willReturn([]);
    $node->getCacheTags()->willReturn([]);
    $node->getCacheMaxAge()->willReturn(14);
    $node = $node->reveal();

    $bubbleable_metadata = new BubbleableMetadata();
    $bubbleable_metadata->setCacheContexts(['current_user']);
    $bubbleable_metadata->setCacheMaxAge(12);

    $result = $this->token->replace('[node:title]', ['node' => $node], [], $bubbleable_metadata);
    $this->assertEquals('hello world', $result);
    $this->assertEquals(['node:1'], $bubbleable_metadata->getCacheTags());
    $this->assertEquals([
      'current_user',
      'custom_context'
    ], $bubbleable_metadata->getCacheContexts());
    $this->assertEquals(10, $bubbleable_metadata->getCacheMaxAge());
  }

  /**
   * @covers ::replace
   * @covers ::replace
   */
  public function testReplaceWithHookTokensAlterWithBubbleableMetadata() {
    $this->moduleHandler->expects($this->any())
      ->method('invokeAll')
      ->willReturn([]);

    $this->moduleHandler->expects($this->any())
      ->method('alter')
      ->willReturnCallback(function ($hook_name, array &$replacements, array $context, BubbleableMetadata $bubbleable_metadata) {
        $replacements['[node:title]'] = 'hello world';
        $bubbleable_metadata->addCacheContexts(['custom_context']);
        $bubbleable_metadata->addCacheTags(['node:1']);
        $bubbleable_metadata->setCacheMaxAge(10);
      });

    $node = $this->prophesize('Drupal\node\NodeInterface');
    $node->getCacheContexts()->willReturn([]);
    $node->getCacheTags()->willReturn([]);
    $node->getCacheMaxAge()->willReturn(14);
    $node = $node->reveal();

    $bubbleable_metadata = new BubbleableMetadata();
    $bubbleable_metadata->setCacheContexts(['current_user']);
    $bubbleable_metadata->setCacheMaxAge(12);

    $result = $this->token->replace('[node:title]', ['node' => $node], [], $bubbleable_metadata);
    $this->assertEquals('hello world', $result);
    $this->assertEquals(['node:1'], $bubbleable_metadata->getCacheTags());
    $this->assertEquals([
      'current_user',
      'custom_context'
    ], $bubbleable_metadata->getCacheContexts());
    $this->assertEquals(10, $bubbleable_metadata->getCacheMaxAge());
  }

254 255 256 257 258 259 260 261 262 263 264
  /**
   * @covers ::resetInfo
   */
  public function testResetInfo() {
    $this->cacheTagsInvalidator->expects($this->once())
      ->method('invalidateTags')
      ->with(['token_info']);

    $this->token->resetInfo();
  }

265
}