View source
<?php
namespace Drupal\Tests\Core\Render;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Cache\Context\ContextCacheKeys;
use Drupal\Core\Cache\MemoryBackend;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\Render\PlaceholderGenerator;
use Drupal\Core\Render\PlaceholderingRenderCache;
use Drupal\Core\Render\Renderer;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
abstract class RendererTestBase extends UnitTestCase {
protected $renderer;
protected $renderCache;
protected $placeholderGenerator;
protected $requestStack;
protected $cacheFactory;
protected $cacheContexts;
protected $controllerResolver;
protected $themeManager;
protected $elementInfo;
protected $memoryCache;
protected $currentUserRole;
protected $rendererConfig = [
'required_cache_contexts' => [
'languages:language_interface',
'theme',
],
'auto_placeholder_conditions' => [
'max-age' => 0,
'contexts' => [
'session',
'user',
],
'tags' => [
'current-temperature',
],
],
];
protected function setUp() {
parent::setUp();
$this->controllerResolver = $this
->createMock('Drupal\\Core\\Controller\\ControllerResolverInterface');
$this->themeManager = $this
->createMock('Drupal\\Core\\Theme\\ThemeManagerInterface');
$this->elementInfo = $this
->createMock('Drupal\\Core\\Render\\ElementInfoManagerInterface');
$this->elementInfo
->expects($this
->any())
->method('getInfo')
->willReturnCallback(function ($type) {
switch ($type) {
case 'details':
$info = [
'#theme_wrappers' => [
'details',
],
];
break;
case 'link':
$info = [
'#theme' => 'link',
];
break;
default:
$info = [];
}
$info['#defaults_loaded'] = TRUE;
return $info;
});
$this->requestStack = new RequestStack();
$request = new Request();
$request->server
->set('REQUEST_TIME', $_SERVER['REQUEST_TIME']);
$this->requestStack
->push($request);
$this->cacheFactory = $this
->createMock('Drupal\\Core\\Cache\\CacheFactoryInterface');
$this->cacheContextsManager = $this
->getMockBuilder('Drupal\\Core\\Cache\\Context\\CacheContextsManager')
->disableOriginalConstructor()
->getMock();
$this->cacheContextsManager
->method('assertValidTokens')
->willReturn(TRUE);
$current_user_role =& $this->currentUserRole;
$this->cacheContextsManager
->expects($this
->any())
->method('convertTokensToKeys')
->willReturnCallback(function ($context_tokens) use (&$current_user_role) {
$keys = [];
foreach ($context_tokens as $context_id) {
switch ($context_id) {
case 'user.roles':
$keys[] = 'r.' . $current_user_role;
break;
case 'languages:language_interface':
$keys[] = 'en';
break;
case 'theme':
$keys[] = 'stark';
break;
default:
$keys[] = $context_id;
}
}
return new ContextCacheKeys($keys, new CacheableMetadata());
});
$this->placeholderGenerator = new PlaceholderGenerator($this->rendererConfig);
$this->renderCache = new PlaceholderingRenderCache($this->requestStack, $this->cacheFactory, $this->cacheContextsManager, $this->placeholderGenerator);
$this->renderer = new Renderer($this->controllerResolver, $this->themeManager, $this->elementInfo, $this->placeholderGenerator, $this->renderCache, $this->requestStack, $this->rendererConfig);
$container = new ContainerBuilder();
$container
->set('cache_contexts_manager', $this->cacheContextsManager);
$container
->set('render_cache', $this->renderCache);
$container
->set('renderer', $this->renderer);
\Drupal::setContainer($container);
}
protected function randomContextValue() {
$tokens = [
'llama',
'alpaca',
'camel',
'moose',
'elk',
];
return $tokens[mt_rand(0, 4)];
}
protected function setUpUnusedCache() {
$this->cacheFactory
->expects($this
->never())
->method('get');
}
protected function setupMemoryCache() {
$this->memoryCache = $this->memoryCache ?: new MemoryBackend();
$this->cacheFactory
->expects($this
->atLeastOnce())
->method('get')
->with('render')
->willReturn($this->memoryCache);
}
protected function setUpRequest($method = 'GET') {
$request = Request::create('/', $method);
$request->server
->set('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
$this->requestStack
->push($request);
}
protected function assertRenderCacheItem($cid, $data, $bin = 'render') {
$cache_backend = $this->cacheFactory
->get($bin);
$cached = $cache_backend
->get($cid);
$this
->assertNotFalse($cached, sprintf('Expected cache item "%s" exists.', $cid));
if ($cached !== FALSE) {
$this
->assertEquals($data, $cached->data, sprintf('Cache item "%s" has the expected data.', $cid));
$this
->assertSame(Cache::mergeTags($data['#cache']['tags'], [
'rendered',
]), $cached->tags, "The cache item's cache tags also has the 'rendered' cache tag.");
}
}
}
class PlaceholdersTest implements TrustedCallbackInterface {
public static function callback($animal, $use_animal_as_array_key = FALSE) {
$value = $animal;
if ($use_animal_as_array_key) {
$value = [
$animal => TRUE,
];
}
return [
'#markup' => '<p>This is a rendered placeholder!</p>',
'#attached' => [
'drupalSettings' => [
'dynamic_animal' => $value,
],
],
];
}
public static function callbackPerUser($animal) {
$build = static::callback($animal);
$build['#cache']['contexts'][] = 'user';
return $build;
}
public static function callbackTagCurrentTemperature($animal) {
$build = static::callback($animal);
$build['#cache']['tags'][] = 'current-temperature';
return $build;
}
public static function trustedCallbacks() {
return [
'callbackTagCurrentTemperature',
'callbackPerUser',
'callback',
];
}
}