mustache_templates-8.x-1.0-beta4/modules/mustache_test/src/Controller/MustacheCacheableTestController.php
modules/mustache_test/src/Controller/MustacheCacheableTestController.php
<?php
namespace Drupal\mustache_test\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\mustache\Helpers\MustacheRenderTemplate;
use Drupal\mustache_test\TestLinks;
/**
* A controller delivering cacheable resources for testing Mustache templates.
*/
class MustacheCacheableTestController {
/**
* Returns a Json response containing cacheable dummy data.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* A cacheable JSON response.
*/
public function cacheableJsonFeed() {
$time_sequence = \Drupal::time()->getRequestTime() - 1636290361;
$data = [
'foo' => 'bar',
'id' => uniqid(),
'number' => rand(),
'sequence' => $time_sequence,
'nested' => ['key' => rand()],
];
$response = new CacheableJsonResponse();
$response->setJson(json_encode($data));
$response->setMaxAge(10);
$response->setSharedMaxAge(10);
$expires = new \DateTime('now', new \DateTimeZone('UTC'));
$expires->setTimestamp(\Drupal::time()->getCurrentTime() + 10);
$response->setExpires($expires);
return $response;
}
/**
* Returns a plain page for interactively testing using previous data.
*
* @return array
* A build array for rendering the Mustache template.
*/
public function pageInteractivePrevious() {
$build = MustacheRenderTemplate::build('test_previous');
$build->usingDataFromUrl('/mustache-test/cacheable-json');
$build->exposeData();
$build->withClientSynchronization()
->morphing()
->startsWhenElementWasTriggered('.click-me')
->atEvent('click')
->always();
$render = [
$build->toRenderArray(),
[
'#type' => 'markup',
'#markup' => '<div class="click-me">Click here to refresh!</div>',
],
['#markup' => TestLinks::get()],
];
return $render;
}
/**
* Returns a plain page for testing magic conditions.
*
* @return array
* A build array for rendering the Mustache template.
*/
public function pageMagicConditions() {
$build = MustacheRenderTemplate::build('test_magic_conditions');
$build->usingDataFromUrl('/mustache-test/cacheable-json');
$build->exposeData();
$build->withClientSynchronization()
->morphing()
->startsWhenElementWasTriggered('.click-me')
->atEvent('click')
->always();
$render = [
$build->toRenderArray(),
[
'#type' => 'markup',
'#markup' => '<div class="click-me">Click here to refresh!</div>',
],
['#markup' => TestLinks::get()],
];
return $render;
}
}
