mirror of
https://github.com/BookStackApp/BookStack.git
synced 2025-07-30 04:23:11 +03:00
Started aligning app-wide outbound http calling behaviour
This commit is contained in:
28
app/Http/HttpClientHistory.php
Normal file
28
app/Http/HttpClientHistory.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Http;
|
||||
|
||||
use GuzzleHttp\Psr7\Request as GuzzleRequest;
|
||||
|
||||
class HttpClientHistory
|
||||
{
|
||||
public function __construct(
|
||||
protected &$container
|
||||
) {
|
||||
}
|
||||
|
||||
public function requestCount(): int
|
||||
{
|
||||
return count($this->container);
|
||||
}
|
||||
|
||||
public function requestAt(int $index): ?GuzzleRequest
|
||||
{
|
||||
return $this->container[$index]['request'] ?? null;
|
||||
}
|
||||
|
||||
public function latestRequest(): ?GuzzleRequest
|
||||
{
|
||||
return $this->requestAt($this->requestCount() - 1);
|
||||
}
|
||||
}
|
61
app/Http/HttpRequestService.php
Normal file
61
app/Http/HttpRequestService.php
Normal file
@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace BookStack\Http;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Handler\MockHandler;
|
||||
use GuzzleHttp\HandlerStack;
|
||||
use GuzzleHttp\Middleware;
|
||||
use GuzzleHttp\Psr7\Request as GuzzleRequest;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
|
||||
class HttpRequestService
|
||||
{
|
||||
protected ?HandlerStack $handler = null;
|
||||
|
||||
/**
|
||||
* Build a new http client for sending requests on.
|
||||
*/
|
||||
public function buildClient(int $timeout, array $options): ClientInterface
|
||||
{
|
||||
$defaultOptions = [
|
||||
'timeout' => $timeout,
|
||||
'handler' => $this->handler,
|
||||
];
|
||||
|
||||
return new Client(array_merge($options, $defaultOptions));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new JSON http request for use with a client.
|
||||
*/
|
||||
public function jsonRequest(string $method, string $uri, array $data): GuzzleRequest
|
||||
{
|
||||
$headers = ['Content-Type' => 'application/json'];
|
||||
return new GuzzleRequest($method, $uri, $headers, json_encode($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock any http clients built from this service, and response with the given responses.
|
||||
* Returns history which can then be queried.
|
||||
* @link https://docs.guzzlephp.org/en/stable/testing.html#history-middleware
|
||||
*/
|
||||
public function mockClient(array $responses = []): HttpClientHistory
|
||||
{
|
||||
$container = [];
|
||||
$history = Middleware::history($container);
|
||||
$mock = new MockHandler($responses);
|
||||
$this->handler = HandlerStack::create($mock);
|
||||
$this->handler->push($history, 'history');
|
||||
|
||||
return new HttpClientHistory($container);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear mocking that has been set up for clients.
|
||||
*/
|
||||
public function clearMocking(): void
|
||||
{
|
||||
$this->handler = null;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user