SystemTestController.php 10.7 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\system_test\Controller;

5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Cache\CacheableResponse;
7
use Drupal\Core\Controller\ControllerBase;
8
use Drupal\Core\Render\RendererInterface;
9
use Drupal\Core\Render\Markup;
10
use Drupal\Core\Session\AccountInterface;
11 12
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
13 14
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
15 16
use Drupal\Core\Lock\LockBackendInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
17 18 19 20 21 22

/**
 * Controller routines for system_test routes.
 */
class SystemTestController extends ControllerBase {

23 24 25 26 27 28 29
  /**
   * The lock service.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $lock;

30 31 32 33 34 35 36
  /**
   * The persistent lock service.
   *
   * @var \Drupal\Core\Lock\LockBackendInterface
   */
  protected $persistentLock;

37 38 39 40 41 42 43 44 45 46 47 48 49 50
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

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

51 52 53
  /**
   * Constructs the SystemTestController.
   *
54 55
   * @param \Drupal\Core\Lock\LockBackendInterface $lock
   *   The lock service.
56 57
   * @param \Drupal\Core\Lock\LockBackendInterface $persistent_lock
   *   The persistent lock service.
58 59 60 61
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
62
   */
63
  public function __construct(LockBackendInterface $lock, LockBackendInterface $persistent_lock, AccountInterface $current_user, RendererInterface $renderer) {
64
    $this->lock = $lock;
65
    $this->persistentLock = $persistent_lock;
66 67
    $this->currentUser = $current_user;
    $this->renderer = $renderer;
68 69 70 71 72 73
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
74 75 76 77 78 79
    return new static(
      $container->get('lock'),
      $container->get('lock.persistent'),
      $container->get('current_user'),
      $container->get('renderer')
    );
80 81
  }

82 83 84 85 86 87 88
  /**
   * Tests main content fallback.
   *
   * @return string
   *   The text to display.
   */
  public function mainContentFallback() {
89
    return ['#markup' => $this->t('Content to test main content fallback')];
90 91
  }

92 93 94 95 96 97 98 99 100
  /**
   * Tests setting messages and removing one before it is displayed.
   *
   * @return string
   *   Empty string, we just test the setting of messages.
   */
  public function drupalSetMessageTest() {
    // Set two messages.
    drupal_set_message('First message (removed).');
101
    drupal_set_message(t('Second message with <em>markup!</em> (not removed).'));
102 103 104

    // Remove the first.
    unset($_SESSION['messages']['status'][0]);
105 106 107 108 109 110 111

    // Duplicate message check.
    drupal_set_message('Non Duplicated message', 'status', FALSE);
    drupal_set_message('Non Duplicated message', 'status', FALSE);

    drupal_set_message('Duplicated message', 'status', TRUE);
    drupal_set_message('Duplicated message', 'status', TRUE);
112

113 114 115 116 117
    // Add a Markup message.
    drupal_set_message(Markup::create('Markup with <em>markup!</em>'));
    // Test duplicate Markup messages.
    drupal_set_message(Markup::create('Markup with <em>markup!</em>'));
    // Ensure that multiple Markup messages work.
118
    drupal_set_message(Markup::create('Markup2 with <em>markup!</em>'));
119 120

    // Test mixing of types.
121 122 123 124
    drupal_set_message(Markup::create('Non duplicate Markup / string.'));
    drupal_set_message('Non duplicate Markup / string.');
    drupal_set_message(Markup::create('Duplicate Markup / string.'), 'status', TRUE);
    drupal_set_message('Duplicate Markup / string.', 'status', TRUE);
125 126 127 128

    // Test auto-escape of non safe strings.
    drupal_set_message('<em>This<span>markup will be</span> escaped</em>.');

129
    return [];
130 131
  }

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  /**
   * Controller to return $_GET['destination'] for testing.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response.
   */
  public function getDestination(Request $request) {
    $response = new Response($request->query->get('destination'));
    return $response;
  }

  /**
   * Controller to return $_REQUEST['destination'] for testing.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response.
   */
  public function requestDestination(Request $request) {
    $response = new Response($request->request->get('destination'));
    return $response;
  }

160
  /**
161
   * Try to acquire a named lock and report the outcome.
162 163
   */
  public function lockAcquire() {
164 165 166 167 168 169 170
    if ($this->lock->acquire('system_test_lock_acquire')) {
      $this->lock->release('system_test_lock_acquire');
      return ['#markup' => 'TRUE: Lock successfully acquired in \Drupal\system_test\Controller\SystemTestController::lockAcquire()'];
    }
    else {
      return ['#markup' => 'FALSE: Lock not acquired in \Drupal\system_test\Controller\SystemTestController::lockAcquire()'];
    }
171 172 173
  }

  /**
174
   * Try to acquire a specific lock, and then exit.
175 176
   */
  public function lockExit() {
177 178 179 180 181 182 183 184
    if ($this->lock->acquire('system_test_lock_exit', 900)) {
      echo 'TRUE: Lock successfully acquired in \Drupal\system_test\Controller\SystemTestController::lockExit()';
      // The shut-down function should release the lock.
      exit();
    }
    else {
      return ['#markup' => 'FALSE: Lock not acquired in system_test_lock_exit()'];
    }
185 186
  }

187 188 189 190 191 192 193 194 195 196 197
  /**
   * Creates a lock that will persist across requests.
   *
   * @param string $lock_name
   *   The name of the persistent lock to acquire.
   *
   * @return string
   *   The text to display.
   */
  public function lockPersist($lock_name) {
    if ($this->persistentLock->acquire($lock_name)) {
198
      return ['#markup' => 'TRUE: Lock successfully acquired in SystemTestController::lockPersist()'];
199 200
    }
    else {
201
      return ['#markup' => 'FALSE: Lock not acquired in SystemTestController::lockPersist()'];
202 203 204
    }
  }

205 206 207
  /**
   * Set cache tag on on the returned render array.
   */
208
  public function system_test_cache_tags_page() {
209
    $build['main'] = array(
210
      '#cache' => array('tags' => array('system_test_cache_tags_page')),
211 212 213 214 215 216
      '#pre_render' => array(
        '\Drupal\system_test\Controller\SystemTestController::preRenderCacheTags',
      ),
      'message' => array(
        '#markup' => 'Cache tags page example',
      ),
217 218 219 220
    );
    return $build;
  }

221 222 223 224 225 226 227 228 229 230 231 232 233
  /**
   * Set cache max-age on the returned render array.
   */
  public function system_test_cache_maxage_page() {
    $build['main'] = array(
      '#cache' => array('max-age' => 90),
      'message' => array(
        '#markup' => 'Cache max-age page example',
      ),
    );
    return $build;
  }

234 235 236 237
  /**
   * Sets a cache tag on an element to help test #pre_render and cache tags.
   */
  public static function preRenderCacheTags($elements) {
238
    $elements['#cache']['tags'][] = 'pre_render';
239 240 241
    return $elements;
  }

242
  /**
243 244
   * Initialize authorize.php during testing.
   *
245
   * @see system_authorized_init()
246 247
   */
  public function authorizeInit($page_title) {
248
    $authorize_url = Url::fromUri('base:core/authorize.php', array('absolute' => TRUE))->toString();
249
    system_authorized_init('system_test_authorize_run', __DIR__ . '/../../system_test.module', array(), $page_title);
250
    return new RedirectResponse($authorize_url);
251 252 253
  }

  /**
254
   * Sets a header.
255
   */
256 257
  public function setHeader(Request $request) {
    $query = $request->query->all();
258
    $response = new CacheableResponse();
259
    $response->headers->set($query['name'], $query['value']);
260
    $response->getCacheableMetadata()->addCacheContexts(['url.query_args:name', 'url.query_args:value']);
261 262 263
    $response->setContent($this->t('The following header was set: %name: %value', array('%name' => $query['name'], '%value' => $query['value'])));

    return $response;
264 265
  }

266 267 268 269 270 271 272
  /**
   * A simple page callback that uses a plain Symfony response object.
   */
  public function respondWithReponse(Request $request) {
    return new Response('test');
  }

273 274 275 276 277 278 279
  /**
   * A plain Symfony reponse with Cache-Control: public, max-age=60.
   */
  public function respondWithPublicResponse() {
    return (new Response('test'))->setPublic()->setMaxAge(60);
  }

280 281 282 283 284 285 286
  /**
   * A simple page callback that uses a CacheableResponse object.
   */
  public function respondWithCacheableReponse(Request $request) {
    return new CacheableResponse('test');
  }

287
  /**
288
   * A simple page callback which adds a register shutdown function.
289 290
   */
  public function shutdownFunctions($arg1, $arg2) {
291
    drupal_register_shutdown_function('_system_test_first_shutdown_function', $arg1, $arg2);
292 293 294 295 296 297
    // If using PHP-FPM then fastcgi_finish_request() will have been fired
    // preventing further output to the browser which means that the escaping of
    // the exception message can not be tested.
    // @see _drupal_shutdown_function()
    // @see \Drupal\system\Tests\System\ShutdownFunctionsTest
    if (function_exists('fastcgi_finish_request')) {
298
      return ['#markup' => 'The function fastcgi_finish_request exists when serving the request.'];
299
    }
300
    return [];
301 302
  }

303 304 305 306 307 308 309 310 311 312 313 314
  /**
   * Returns the title for system_test.info.yml's configure route.
   *
   * @param string $foo
   *   Any string for the {foo} slug.
   *
   * @return string
   */
  public function configureTitle($foo) {
    return 'Bar.' . $foo;
  }

315 316 317 318 319 320 321 322 323 324 325
  /**
   * Shows permission-dependent content.
   *
   * @return array
   *   A render array.
   */
  public function permissionDependentContent() {
    $build = [];

    // The content depends on the access result.
    $access = AccessResult::allowedIfHasPermission($this->currentUser, 'pet llamas');
326
    $this->renderer->addCacheableDependency($build, $access);
327 328 329 330 331 332 333 334 335 336 337 338

    // Build the content.
    if ($access->isAllowed()) {
      $build['allowed'] = ['#markup' => 'Permission to pet llamas: yes!'];
    }
    else {
      $build['forbidden'] = ['#markup' => 'Permission to pet llamas: no!'];
    }

    return $build;
  }

339 340 341
  /**
   * Returns the current date.
   *
342
   * @return \Symfony\Component\HttpFoundation\Response
343 344 345 346 347 348 349 350
   *   A Response object containing the current date.
   */
  public function getCurrentDate() {
    // Uses specific time to test that the right timezone is used.
    $response = new Response(\Drupal::service('date.formatter')->format(1452702549));
    return $response;
  }

351 352 353
  /**
   * Returns a response with a test header set from the request.
   *
354
   * @return \Symfony\Component\HttpFoundation\Response
355 356 357 358 359 360 361 362
   *   A Response object containing the test header.
   */
  public function getTestHeader(Request $request) {
    $response = new Response();
    $response->headers->set('Test-Header', $request->headers->get('Test-Header'));
    return $response;
  }

363
}