5e49c2403b677defc9e641483d6f39c2556ee4ed
[yaffs-website] / web / core / modules / system / tests / modules / system_test / src / Controller / SystemTestController.php
1 <?php
2
3 namespace Drupal\system_test\Controller;
4
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 use Drupal\Core\Url;
12 use Symfony\Component\HttpFoundation\RedirectResponse;
13 use Symfony\Component\HttpFoundation\Request;
14 use Symfony\Component\HttpFoundation\Response;
15 use Drupal\Core\Lock\LockBackendInterface;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17
18 /**
19  * Controller routines for system_test routes.
20  */
21 class SystemTestController extends ControllerBase {
22
23   /**
24    * The lock service.
25    *
26    * @var \Drupal\Core\Lock\LockBackendInterface
27    */
28   protected $lock;
29
30   /**
31    * The persistent lock service.
32    *
33    * @var \Drupal\Core\Lock\LockBackendInterface
34    */
35   protected $persistentLock;
36
37   /**
38    * The current user.
39    *
40    * @var \Drupal\Core\Session\AccountInterface
41    */
42   protected $currentUser;
43
44   /**
45    * The renderer.
46    *
47    * @var \Drupal\Core\Render\RendererInterface
48    */
49   protected $renderer;
50
51   /**
52    * Constructs the SystemTestController.
53    *
54    * @param \Drupal\Core\Lock\LockBackendInterface $lock
55    *   The lock service.
56    * @param \Drupal\Core\Lock\LockBackendInterface $persistent_lock
57    *   The persistent lock service.
58    * @param \Drupal\Core\Session\AccountInterface $current_user
59    *   The current user.
60    * @param \Drupal\Core\Render\RendererInterface $renderer
61    *   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     $this->currentUser = $current_user;
67     $this->renderer = $renderer;
68   }
69
70   /**
71    * {@inheritdoc}
72    */
73   public static function create(ContainerInterface $container) {
74     return new static(
75       $container->get('lock'),
76       $container->get('lock.persistent'),
77       $container->get('current_user'),
78       $container->get('renderer')
79     );
80   }
81
82   /**
83    * Tests main content fallback.
84    *
85    * @return string
86    *   The text to display.
87    */
88   public function mainContentFallback() {
89     return ['#markup' => $this->t('Content to test main content fallback')];
90   }
91
92   /**
93    * Tests setting messages and removing one before it is displayed.
94    *
95    * @return string
96    *   Empty string, we just test the setting of messages.
97    */
98   public function drupalSetMessageTest() {
99     // Set two messages.
100     drupal_set_message('First message (removed).');
101     drupal_set_message(t('Second message with <em>markup!</em> (not removed).'));
102
103     // Remove the first.
104     unset($_SESSION['messages']['status'][0]);
105
106     // Duplicate message check.
107     drupal_set_message('Non Duplicated message', 'status', FALSE);
108     drupal_set_message('Non Duplicated message', 'status', FALSE);
109
110     drupal_set_message('Duplicated message', 'status', TRUE);
111     drupal_set_message('Duplicated message', 'status', TRUE);
112
113     // Add a Markup message.
114     drupal_set_message(Markup::create('Markup with <em>markup!</em>'));
115     // Test duplicate Markup messages.
116     drupal_set_message(Markup::create('Markup with <em>markup!</em>'));
117     // Ensure that multiple Markup messages work.
118     drupal_set_message(Markup::create('Markup2 with <em>markup!</em>'));
119
120     // Test mixing of types.
121     drupal_set_message(Markup::create('Non duplicate Markup / string.'));
122     drupal_set_message('Non duplicate Markup / string.');
123     drupal_set_message(Markup::create('Duplicate Markup / string.'), 'status', TRUE);
124     drupal_set_message('Duplicate Markup / string.', 'status', TRUE);
125
126     // Test auto-escape of non safe strings.
127     drupal_set_message('<em>This<span>markup will be</span> escaped</em>.');
128
129     return [];
130   }
131
132   /**
133    * Controller to return $_GET['destination'] for testing.
134    *
135    * @param \Symfony\Component\HttpFoundation\Request $request
136    *   The request.
137    *
138    * @return \Symfony\Component\HttpFoundation\Response
139    *   The response.
140    */
141   public function getDestination(Request $request) {
142     $response = new Response($request->query->get('destination'));
143     return $response;
144   }
145
146   /**
147    * Controller to return $_REQUEST['destination'] for testing.
148    *
149    * @param \Symfony\Component\HttpFoundation\Request $request
150    *   The request.
151    *
152    * @return \Symfony\Component\HttpFoundation\Response
153    *   The response.
154    */
155   public function requestDestination(Request $request) {
156     $response = new Response($request->request->get('destination'));
157     return $response;
158   }
159
160   /**
161    * Try to acquire a named lock and report the outcome.
162    */
163   public function lockAcquire() {
164     if ($this->lock->acquire('system_test_lock_acquire')) {
165       $this->lock->release('system_test_lock_acquire');
166       return ['#markup' => 'TRUE: Lock successfully acquired in \Drupal\system_test\Controller\SystemTestController::lockAcquire()'];
167     }
168     else {
169       return ['#markup' => 'FALSE: Lock not acquired in \Drupal\system_test\Controller\SystemTestController::lockAcquire()'];
170     }
171   }
172
173   /**
174    * Try to acquire a specific lock, and then exit.
175    */
176   public function lockExit() {
177     if ($this->lock->acquire('system_test_lock_exit', 900)) {
178       echo 'TRUE: Lock successfully acquired in \Drupal\system_test\Controller\SystemTestController::lockExit()';
179       // The shut-down function should release the lock.
180       exit();
181     }
182     else {
183       return ['#markup' => 'FALSE: Lock not acquired in system_test_lock_exit()'];
184     }
185   }
186
187   /**
188    * Creates a lock that will persist across requests.
189    *
190    * @param string $lock_name
191    *   The name of the persistent lock to acquire.
192    *
193    * @return string
194    *   The text to display.
195    */
196   public function lockPersist($lock_name) {
197     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    * Set cache tag on on the returned render array.
207    */
208   public function system_test_cache_tags_page() {
209     $build['main'] = [
210       '#cache' => ['tags' => ['system_test_cache_tags_page']],
211       '#pre_render' => [
212         '\Drupal\system_test\Controller\SystemTestController::preRenderCacheTags',
213       ],
214       'message' => [
215         '#markup' => 'Cache tags page example',
216       ],
217     ];
218     return $build;
219   }
220
221   /**
222    * Set cache max-age on the returned render array.
223    */
224   public function system_test_cache_maxage_page() {
225     $build['main'] = [
226       '#cache' => ['max-age' => 90],
227       'message' => [
228         '#markup' => 'Cache max-age page example',
229       ],
230     ];
231     return $build;
232   }
233
234   /**
235    * Sets a cache tag on an element to help test #pre_render and cache tags.
236    */
237   public static function preRenderCacheTags($elements) {
238     $elements['#cache']['tags'][] = 'pre_render';
239     return $elements;
240   }
241
242   /**
243    * Initialize authorize.php during testing.
244    *
245    * @see system_authorized_init()
246    */
247   public function authorizeInit($page_title) {
248     $authorize_url = Url::fromUri('base:core/authorize.php', ['absolute' => TRUE])->toString();
249     system_authorized_init('system_test_authorize_run', __DIR__ . '/../../system_test.module', [], $page_title);
250     return new RedirectResponse($authorize_url);
251   }
252
253   /**
254    * Sets a header.
255    */
256   public function setHeader(Request $request) {
257     $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     $response->setContent($this->t('The following header was set: %name: %value', ['%name' => $query['name'], '%value' => $query['value']]));
262
263     return $response;
264   }
265
266   /**
267    * A simple page callback that uses a plain Symfony response object.
268    */
269   public function respondWithReponse(Request $request) {
270     return new Response('test');
271   }
272
273   /**
274    * A plain Symfony reponse with Cache-Control: public, max-age=60.
275    */
276   public function respondWithPublicResponse() {
277     return (new Response('test'))->setPublic()->setMaxAge(60);
278   }
279
280   /**
281    * A simple page callback that uses a CacheableResponse object.
282    */
283   public function respondWithCacheableReponse(Request $request) {
284     return new CacheableResponse('test');
285   }
286
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     // If using PHP-FPM then fastcgi_finish_request() will have been fired
293     // preventing further output to the browser which means that the escaping of
294     // the exception message can not be tested.
295     // @see _drupal_shutdown_function()
296     // @see \Drupal\system\Tests\System\ShutdownFunctionsTest
297     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    * Returns the title for system_test.info.yml's configure route.
305    *
306    * @param string $foo
307    *   Any string for the {foo} slug.
308    *
309    * @return string
310    */
311   public function configureTitle($foo) {
312     return 'Bar.' . $foo;
313   }
314
315   /**
316    * Simple argument echo.
317    *
318    * @param string $text
319    *   Any string for the {text} slug.
320    *
321    * @return array
322    *   A render array.
323    */
324   public function simpleEcho($text) {
325     return [
326       '#plain_text' => $text,
327     ];
328   }
329
330   /**
331    * Shows permission-dependent content.
332    *
333    * @return array
334    *   A render array.
335    */
336   public function permissionDependentContent() {
337     $build = [];
338
339     // The content depends on the access result.
340     $access = AccessResult::allowedIfHasPermission($this->currentUser, 'pet llamas');
341     $this->renderer->addCacheableDependency($build, $access);
342
343     // Build the content.
344     if ($access->isAllowed()) {
345       $build['allowed'] = ['#markup' => 'Permission to pet llamas: yes!'];
346     }
347     else {
348       $build['forbidden'] = ['#markup' => 'Permission to pet llamas: no!'];
349     }
350
351     return $build;
352   }
353
354   /**
355    * Returns the current date.
356    *
357    * @return \Symfony\Component\HttpFoundation\Response
358    *   A Response object containing the current date.
359    */
360   public function getCurrentDate() {
361     // Uses specific time to test that the right timezone is used.
362     $response = new Response(\Drupal::service('date.formatter')->format(1452702549));
363     return $response;
364   }
365
366   /**
367    * Returns a response with a test header set from the request.
368    *
369    * @return \Symfony\Component\HttpFoundation\Response
370    *   A Response object containing the test header.
371    */
372   public function getTestHeader(Request $request) {
373     $response = new Response();
374     $response->headers->set('Test-Header', $request->headers->get('Test-Header'));
375     return $response;
376   }
377
378 }