summaryrefslogtreecommitdiffstatshomepage
path: root/core/tests/Drupal/Tests/XdebugRequestTrait.php
blob: 0093c00e9e1cecc3cf21c1e7f3cda1d83fc0adaa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php

declare(strict_types=1);

namespace Drupal\Tests;

use Symfony\Component\HttpFoundation\Request;

/**
 * Trait for testing with Xdebug cookies extraction from request.
 */
trait XdebugRequestTrait {

  /**
   * Adds xdebug cookies, from request setup.
   *
   * In order to debug web tests you need to either set a cookie, have the
   * Xdebug session in the URL or set an environment variable in case of CLI
   * requests. If the developer listens to connection on the parent site, by
   * default the cookie is not forwarded to the client side, so you cannot
   * debug the code running on the child site. In order to make debuggers work
   * this bit of information is forwarded. Make sure that the debugger listens
   * to at least three external connections.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request.
   *
   * @return array
   *   The extracted cookies.
   */
  protected function extractCookiesFromRequest(Request $request): array {
    $cookie_params = $request->cookies;
    $cookies = [];
    if ($cookie_params->has('XDEBUG_SESSION')) {
      $cookies['XDEBUG_SESSION'][] = $cookie_params->get('XDEBUG_SESSION');
    }
    // For CLI requests, the information is stored in $_SERVER.
    $server = $request->server;
    if ($server->has('XDEBUG_SESSION')) {
      $cookies['XDEBUG_SESSION'][] = $server->get('XDEBUG_SESSION');
    }
    elseif ($server->has('XDEBUG_CONFIG')) {
      // $_SERVER['XDEBUG_CONFIG'] has the form "key1=value1 key2=value2 ...".
      $pairs = array_filter(explode(' ', $server->get('XDEBUG_CONFIG')), function ($value) {
        return str_contains($value, '=');
      });
      foreach ($pairs as $pair) {
        [$key, $value] = explode('=', $pair, 2);
        // Account for key-value pairs being separated by multiple spaces.
        if (trim($key, ' ') == 'idekey') {
          $cookies['XDEBUG_SESSION'][] = trim($value, ' ');
        }
      }
    }
    return $cookies;
  }

}