Patched to Drupal 8.4.8 level. See https://www.drupal.org/sa-core-2018-004 and patch...
[yaffs-website] / web / core / lib / Drupal / Core / Test / HttpClientMiddleware / TestHttpClientMiddleware.php
1 <?php
2
3 namespace Drupal\Core\Test\HttpClientMiddleware;
4
5 use Drupal\Core\Utility\Error;
6 use Psr\Http\Message\RequestInterface;
7 use Psr\Http\Message\ResponseInterface;
8
9 /**
10  * Overrides the User-Agent HTTP header for outbound HTTP requests.
11  */
12 class TestHttpClientMiddleware {
13
14   /**
15    * {@inheritdoc}
16    *
17    * HTTP middleware that replaces the user agent for simpletest requests.
18    */
19   public function __invoke() {
20     // If the database prefix is being used by SimpleTest to run the tests in a copied
21     // database then set the user-agent header to the database prefix so that any
22     // calls to other Drupal pages will run the SimpleTest prefixed database. The
23     // user-agent is used to ensure that multiple testing sessions running at the
24     // same time won't interfere with each other as they would if the database
25     // prefix were stored statically in a file or database variable.
26     return function ($handler) {
27       return function (RequestInterface $request, array $options) use ($handler) {
28         if ($test_prefix = drupal_valid_test_ua()) {
29           $request = $request->withHeader('User-Agent', drupal_generate_test_ua($test_prefix));
30         }
31         return $handler($request, $options)
32           ->then(function (ResponseInterface $response) use ($request) {
33             if (!drupal_valid_test_ua()) {
34               return $response;
35             }
36             $headers = $response->getHeaders();
37             foreach ($headers as $header_name => $header_values) {
38               if (preg_match('/^X-Drupal-Assertion-[0-9]+$/', $header_name, $matches)) {
39                 foreach ($header_values as $header_value) {
40                   // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
41                   // the header.
42                   $parameters = unserialize(urldecode($header_value));
43                   if (count($parameters) === 3) {
44                     throw new \Exception($parameters[1] . ': ' . $parameters[0] . "\n" . Error::formatBacktrace([$parameters[2]]));
45                   }
46                   else {
47                     throw new \Exception('Error thrown with the wrong amount of parameters.');
48                   }
49                 }
50               }
51             }
52             return $response;
53           });
54       };
55     };
56   }
57
58 }