You are here

protected function DrupalTestBrowser::doRequest in Drupal 9

File

core/tests/Drupal/Tests/DrupalTestBrowser.php, line 83

Class

DrupalTestBrowser
Enables a BrowserKitDriver mink driver to use a Guzzle client.

Namespace

Drupal\Tests

Code

protected function doRequest($request) {
  $headers = [];
  foreach ($request
    ->getServer() as $key => $val) {
    $key = strtolower(str_replace('_', '-', $key));
    $content_headers = [
      'content-length' => TRUE,
      'content-md5' => TRUE,
      'content-type' => TRUE,
    ];
    if (strpos($key, 'http-') === 0) {
      $headers[substr($key, 5)] = $val;
    }
    elseif (isset($content_headers[$key])) {
      $headers[$key] = $val;
    }
  }
  $cookies = CookieJar::fromArray($this
    ->getCookieJar()
    ->allRawValues($request
    ->getUri()), parse_url($request
    ->getUri(), PHP_URL_HOST));
  $request_options = [
    'cookies' => $cookies,
    'allow_redirects' => FALSE,
  ];
  if (!\in_array($request
    ->getMethod(), [
    'GET',
    'HEAD',
  ], TRUE)) {
    if (NULL !== ($content = $request
      ->getContent())) {
      $request_options['body'] = $content;
    }
    else {
      if ($files = $request
        ->getFiles()) {
        $request_options['multipart'] = [];
        $this
          ->addPostFields($request
          ->getParameters(), $request_options['multipart']);
        $this
          ->addPostFiles($files, $request_options['multipart']);
      }
      else {
        $request_options['form_params'] = $request
          ->getParameters();
      }
    }
  }
  if (!empty($headers)) {
    $request_options['headers'] = $headers;
  }
  $method = $request
    ->getMethod();
  $uri = $request
    ->getUri();

  // Let BrowserKit handle redirects
  try {
    $response = $this
      ->getClient()
      ->request($method, $uri, $request_options);
  } catch (RequestException $e) {
    if (!$e
      ->hasResponse()) {
      throw $e;
    }
    $response = $e
      ->getResponse();
  }
  return $this
    ->createResponse($response);
}