TestHttpClientMiddleware.php 2.7 KB

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