MockHttpClientMiddleware.php in Thunder 8.5
File
tests/modules/thunder_test_mock_request/src/MockHttpClientMiddleware.php
View source
<?php
namespace Drupal\thunder_test_mock_request;
use Drupal\Core\State\StateInterface;
use GuzzleHttp\Psr7\Response;
use function GuzzleHttp\Promise\promise_for;
use Psr\Http\Message\RequestInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class MockHttpClientMiddleware {
protected $request;
protected $state;
public function __construct(RequestStack $requestStack, StateInterface $state) {
$this->request = $requestStack
->getCurrentRequest();
$this->state = $state;
}
public static function addUrlResponse($url, $body, array $headers = [], $status = 200) {
$items = \Drupal::state()
->get(static::class, []);
$items[$url] = [
'body' => $body,
'headers' => $headers,
'status' => $status,
];
\Drupal::state()
->set(static::class, $items);
}
public function __invoke() {
return function ($handler) {
return function (RequestInterface $request, array $options) use ($handler) {
$items = $this->state
->get(static::class, []);
$url = (string) $request
->getUri();
if (!empty($items[$url])) {
$response = new Response($items[$url]['status'], $items[$url]['headers'], $items[$url]['body']);
return promise_for($response);
}
elseif (strstr($this->request
->getHttpHost(), $request
->getUri()
->getHost()) === FALSE) {
throw new \Exception(sprintf("No response for %s defined. See MockHttpClientMiddleware::addUrlResponse().", $url));
}
return $handler($request, $options);
};
};
}
}