Primo Committ

This commit is contained in:
paoloar77
2024-05-07 12:17:25 +02:00
commit e73d0e5113
7204 changed files with 884387 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
<?php
namespace Illuminate\Http\Client;
class ConnectionException extends HttpClientException
{
//
}

View File

@@ -0,0 +1,285 @@
<?php
namespace Illuminate\Http\Client;
use Closure;
use function GuzzleHttp\Promise\promise_for;
use GuzzleHttp\Psr7\Response as Psr7Response;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use PHPUnit\Framework\Assert as PHPUnit;
class Factory
{
use Macroable {
__call as macroCall;
}
/**
* The stub callables that will handle requests.
*
* @var \Illuminate\Support\Collection
*/
protected $stubCallbacks;
/**
* Indicates if the factory is recording requests and responses.
*
* @var bool
*/
protected $recording = false;
/**
* The recorded response array.
*
* @var array
*/
protected $recorded = [];
/**
* All created response sequences.
*
* @var array
*/
protected $responseSequences = [];
/**
* Create a new factory instance.
*
* @return void
*/
public function __construct()
{
$this->stubCallbacks = collect();
}
/**
* Create a new response instance for use during stubbing.
*
* @param array|string $body
* @param int $status
* @param array $headers
* @return \GuzzleHttp\Promise\PromiseInterface
*/
public static function response($body = null, $status = 200, $headers = [])
{
if (is_array($body)) {
$body = json_encode($body);
$headers['Content-Type'] = 'application/json';
}
return promise_for(new Psr7Response($status, $headers, $body));
}
/**
* Get an invokable object that returns a sequence of responses in order for use during stubbing.
*
* @param array $responses
* @return \Illuminate\Http\Client\ResponseSequence
*/
public function sequence(array $responses = [])
{
return $this->responseSequences[] = new ResponseSequence($responses);
}
/**
* Register a stub callable that will intercept requests and be able to return stub responses.
*
* @param callable|array $callback
* @return $this
*/
public function fake($callback = null)
{
$this->record();
if (is_null($callback)) {
$callback = function () {
return static::response();
};
}
if (is_array($callback)) {
foreach ($callback as $url => $callable) {
$this->stubUrl($url, $callable);
}
return $this;
}
$this->stubCallbacks = $this->stubCallbacks->merge(collect([
$callback instanceof Closure
? $callback
: function () use ($callback) {
return $callback;
},
]));
return $this;
}
/**
* Register a response sequence for the given URL pattern.
*
* @param string $url
* @return \Illuminate\Http\Client\ResponseSequence
*/
public function fakeSequence($url = '*')
{
return tap($this->sequence(), function ($sequence) use ($url) {
$this->fake([$url => $sequence]);
});
}
/**
* Stub the given URL using the given callback.
*
* @param string $url
* @param \Illuminate\Http\Client\Response|\GuzzleHttp\Promise\PromiseInterface|callable $callback
* @return $this
*/
public function stubUrl($url, $callback)
{
return $this->fake(function ($request, $options) use ($url, $callback) {
if (! Str::is(Str::start($url, '*'), $request->url())) {
return;
}
return $callback instanceof Closure || $callback instanceof ResponseSequence
? $callback($request, $options)
: $callback;
});
}
/**
* Begin recording request / response pairs.
*
* @return $this
*/
protected function record()
{
$this->recording = true;
return $this;
}
/**
* Record a request response pair.
*
* @param \Illuminate\Http\Client\Request $request
* @param \Illuminate\Http\Client\Response $response
* @return void
*/
public function recordRequestResponsePair($request, $response)
{
if ($this->recording) {
$this->recorded[] = [$request, $response];
}
}
/**
* Assert that a request / response pair was recorded matching a given truth test.
*
* @param callable $callback
* @return void
*/
public function assertSent($callback)
{
PHPUnit::assertTrue(
$this->recorded($callback)->count() > 0,
'An expected request was not recorded.'
);
}
/**
* Assert that a request / response pair was not recorded matching a given truth test.
*
* @param callable $callback
* @return void
*/
public function assertNotSent($callback)
{
PHPUnit::assertFalse(
$this->recorded($callback)->count() > 0,
'Unexpected request was recorded.'
);
}
/**
* Assert that no request / response pair was recorded.
*
* @return void
*/
public function assertNothingSent()
{
PHPUnit::assertEmpty(
$this->recorded,
'Requests were recorded.'
);
}
/**
* Assert how many requests have been recorded.
*
* @param int $count
* @return void
*/
public function assertSentCount($count)
{
PHPUnit::assertCount($count, $this->recorded);
}
/**
* Assert that every created response sequence is empty.
*
* @return void
*/
public function assertSequencesAreEmpty()
{
foreach ($this->responseSequences as $responseSequence) {
PHPUnit::assertTrue(
$responseSequence->isEmpty(),
'Not all response sequences are empty.'
);
}
}
/**
* Get a collection of the request / response pairs matching the given truth test.
*
* @param callable $callback
* @return \Illuminate\Support\Collection
*/
public function recorded($callback)
{
if (empty($this->recorded)) {
return collect();
}
$callback = $callback ?: function () {
return true;
};
return collect($this->recorded)->filter(function ($pair) use ($callback) {
return $callback($pair[0], $pair[1]);
});
}
/**
* Execute a method against a new pending request instance.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $parameters);
}
return tap(new PendingRequest($this), function ($request) {
$request->stub($this->stubCallbacks);
})->{$method}(...$parameters);
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace Illuminate\Http\Client;
use Exception;
class HttpClientException extends Exception
{
//
}

View File

@@ -0,0 +1,775 @@
<?php
namespace Illuminate\Http\Client;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\HandlerStack;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
class PendingRequest
{
use Macroable;
/**
* The factory instance.
*
* @var \Illuminate\Http\Client\Factory|null
*/
protected $factory;
/**
* The base URL for the request.
*
* @var string
*/
protected $baseUrl = '';
/**
* The request body format.
*
* @var string
*/
protected $bodyFormat;
/**
* The raw body for the request.
*
* @var string
*/
protected $pendingBody;
/**
* The pending files for the request.
*
* @var array
*/
protected $pendingFiles = [];
/**
* The request cookies.
*
* @var array
*/
protected $cookies;
/**
* The transfer stats for the request.
*
* \GuzzleHttp\TransferStats
*/
protected $transferStats;
/**
* The request options.
*
* @var array
*/
protected $options = [];
/**
* The number of times to try the request.
*
* @var int
*/
protected $tries = 1;
/**
* The number of milliseconds to wait between retries.
*
* @var int
*/
protected $retryDelay = 100;
/**
* The callbacks that should execute before the request is sent.
*
* @var \Illuminate\Support\Collection
*/
protected $beforeSendingCallbacks;
/**
* The stub callables that will handle requests.
*
* @var \Illuminate\Support\Collection|null
*/
protected $stubCallbacks;
/**
* The middleware callables added by users that will handle requests.
*
* @var \Illuminate\Support\Collection
*/
protected $middleware;
/**
* Create a new HTTP Client instance.
*
* @param \Illuminate\Http\Client\Factory|null $factory
* @return void
*/
public function __construct(Factory $factory = null)
{
$this->factory = $factory;
$this->middleware = new Collection;
$this->asJson();
$this->options = [
'http_errors' => false,
];
$this->beforeSendingCallbacks = collect([function (Request $request, array $options) {
$this->cookies = $options['cookies'];
}]);
}
/**
* Set the base URL for the pending request.
*
* @param string $url
* @return $this
*/
public function baseUrl(string $url)
{
$this->baseUrl = $url;
return $this;
}
/**
* Attach a raw body to the request.
*
* @param resource|string $content
* @param string $contentType
* @return $this
*/
public function withBody($content, $contentType)
{
$this->bodyFormat('body');
$this->pendingBody = $content;
$this->contentType($contentType);
return $this;
}
/**
* Indicate the request contains JSON.
*
* @return $this
*/
public function asJson()
{
return $this->bodyFormat('json')->contentType('application/json');
}
/**
* Indicate the request contains form parameters.
*
* @return $this
*/
public function asForm()
{
return $this->bodyFormat('form_params')->contentType('application/x-www-form-urlencoded');
}
/**
* Attach a file to the request.
*
* @param string $name
* @param string $contents
* @param string|null $filename
* @param array $headers
* @return $this
*/
public function attach($name, $contents, $filename = null, array $headers = [])
{
$this->asMultipart();
$this->pendingFiles[] = array_filter([
'name' => $name,
'contents' => $contents,
'headers' => $headers,
'filename' => $filename,
]);
return $this;
}
/**
* Indicate the request is a multi-part form request.
*
* @return $this
*/
public function asMultipart()
{
return $this->bodyFormat('multipart');
}
/**
* Specify the body format of the request.
*
* @param string $format
* @return $this
*/
public function bodyFormat(string $format)
{
return tap($this, function ($request) use ($format) {
$this->bodyFormat = $format;
});
}
/**
* Specify the request's content type.
*
* @param string $contentType
* @return $this
*/
public function contentType(string $contentType)
{
return $this->withHeaders(['Content-Type' => $contentType]);
}
/**
* Indicate that JSON should be returned by the server.
*
* @return $this
*/
public function acceptJson()
{
return $this->accept('application/json');
}
/**
* Indicate the type of content that should be returned by the server.
*
* @param string $contentType
* @return $this
*/
public function accept($contentType)
{
return $this->withHeaders(['Accept' => $contentType]);
}
/**
* Add the given headers to the request.
*
* @param array $headers
* @return $this
*/
public function withHeaders(array $headers)
{
return tap($this, function ($request) use ($headers) {
return $this->options = array_merge_recursive($this->options, [
'headers' => $headers,
]);
});
}
/**
* Specify the basic authentication username and password for the request.
*
* @param string $username
* @param string $password
* @return $this
*/
public function withBasicAuth(string $username, string $password)
{
return tap($this, function ($request) use ($username, $password) {
return $this->options['auth'] = [$username, $password];
});
}
/**
* Specify the digest authentication username and password for the request.
*
* @param string $username
* @param string $password
* @return $this
*/
public function withDigestAuth($username, $password)
{
return tap($this, function ($request) use ($username, $password) {
return $this->options['auth'] = [$username, $password, 'digest'];
});
}
/**
* Specify an authorization token for the request.
*
* @param string $token
* @param string $type
* @return $this
*/
public function withToken($token, $type = 'Bearer')
{
return tap($this, function ($request) use ($token, $type) {
return $this->options['headers']['Authorization'] = trim($type.' '.$token);
});
}
/**
* Specify the cookies that should be included with the request.
*
* @param array $cookies
* @param string $domain
* @return $this
*/
public function withCookies(array $cookies, string $domain)
{
return tap($this, function ($request) use ($cookies, $domain) {
return $this->options = array_merge_recursive($this->options, [
'cookies' => CookieJar::fromArray($cookies, $domain),
]);
});
}
/**
* Indicate that redirects should not be followed.
*
* @return $this
*/
public function withoutRedirecting()
{
return tap($this, function ($request) {
return $this->options['allow_redirects'] = false;
});
}
/**
* Indicate that TLS certificates should not be verified.
*
* @return $this
*/
public function withoutVerifying()
{
return tap($this, function ($request) {
return $this->options['verify'] = false;
});
}
/**
* Specify the path where the body of the response should be stored.
*
* @param string|resource $to
* @return $this
*/
public function sink($to)
{
return tap($this, function ($request) use ($to) {
return $this->options['sink'] = $to;
});
}
/**
* Specify the timeout (in seconds) for the request.
*
* @param int $seconds
* @return $this
*/
public function timeout(int $seconds)
{
return tap($this, function () use ($seconds) {
$this->options['timeout'] = $seconds;
});
}
/**
* Specify the number of times the request should be attempted.
*
* @param int $times
* @param int $sleep
* @return $this
*/
public function retry(int $times, int $sleep = 0)
{
$this->tries = $times;
$this->retryDelay = $sleep;
return $this;
}
/**
* Merge new options into the client.
*
* @param array $options
* @return $this
*/
public function withOptions(array $options)
{
return tap($this, function ($request) use ($options) {
return $this->options = array_merge_recursive($this->options, $options);
});
}
/**
* Add new middleware the client handler stack.
*
* @param callable $middleware
* @return $this
*/
public function withMiddleware(callable $middleware)
{
$this->middleware->push($middleware);
return $this;
}
/**
* Add a new "before sending" callback to the request.
*
* @param callable $callback
* @return $this
*/
public function beforeSending($callback)
{
return tap($this, function () use ($callback) {
$this->beforeSendingCallbacks[] = $callback;
});
}
/**
* Issue a GET request to the given URL.
*
* @param string $url
* @param array|string|null $query
* @return \Illuminate\Http\Client\Response
*/
public function get(string $url, $query = null)
{
return $this->send('GET', $url, [
'query' => $query,
]);
}
/**
* Issue a HEAD request to the given URL.
*
* @param string $url
* @param array|string|null $query
* @return \Illuminate\Http\Client\Response
*/
public function head(string $url, $query = null)
{
return $this->send('HEAD', $url, [
'query' => $query,
]);
}
/**
* Issue a POST request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function post(string $url, array $data = [])
{
return $this->send('POST', $url, [
$this->bodyFormat => $data,
]);
}
/**
* Issue a PATCH request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function patch($url, $data = [])
{
return $this->send('PATCH', $url, [
$this->bodyFormat => $data,
]);
}
/**
* Issue a PUT request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function put($url, $data = [])
{
return $this->send('PUT', $url, [
$this->bodyFormat => $data,
]);
}
/**
* Issue a DELETE request to the given URL.
*
* @param string $url
* @param array $data
* @return \Illuminate\Http\Client\Response
*/
public function delete($url, $data = [])
{
return $this->send('DELETE', $url, empty($data) ? [] : [
$this->bodyFormat => $data,
]);
}
/**
* Send the request to the given URL.
*
* @param string $method
* @param string $url
* @param array $options
* @return \Illuminate\Http\Client\Response
*
* @throws \Exception
*/
public function send(string $method, string $url, array $options = [])
{
$url = ltrim(rtrim($this->baseUrl, '/').'/'.ltrim($url, '/'), '/');
if (isset($options[$this->bodyFormat])) {
if ($this->bodyFormat === 'multipart') {
$options[$this->bodyFormat] = $this->parseMultipartBodyFormat($options[$this->bodyFormat]);
} elseif ($this->bodyFormat === 'body') {
$options[$this->bodyFormat] = $this->pendingBody;
}
if (is_array($options[$this->bodyFormat])) {
$options[$this->bodyFormat] = array_merge(
$options[$this->bodyFormat], $this->pendingFiles
);
}
}
[$this->pendingBody, $this->pendingFiles] = [null, []];
return retry($this->tries ?? 1, function () use ($method, $url, $options) {
try {
$laravelData = $this->parseRequestData($method, $url, $options);
return tap(new Response($this->buildClient()->request($method, $url, $this->mergeOptions([
'laravel_data' => $laravelData,
'on_stats' => function ($transferStats) {
$this->transferStats = $transferStats;
},
], $options))), function ($response) {
$response->cookies = $this->cookies;
$response->transferStats = $this->transferStats;
if ($this->tries > 1 && ! $response->successful()) {
$response->throw();
}
});
} catch (ConnectException $e) {
throw new ConnectionException($e->getMessage(), 0, $e);
}
}, $this->retryDelay ?? 100);
}
/**
* Parse multi-part form data.
*
* @param array $data
* @return array|array[]
*/
protected function parseMultipartBodyFormat(array $data)
{
return collect($data)->map(function ($value, $key) {
return is_array($value) ? $value : ['name' => $key, 'contents' => $value];
})->values()->all();
}
/**
* Get the request data as an array so that we can attach it to the request for convenient assertions.
*
* @param string $method
* @param string $url
* @param array $options
* @return array
*/
protected function parseRequestData($method, $url, array $options)
{
$laravelData = $options[$this->bodyFormat] ?? $options['query'] ?? [];
$urlString = Str::of($url);
if (empty($laravelData) && $method === 'GET' && $urlString->contains('?')) {
$laravelData = (string) $urlString->after('?');
}
if (is_string($laravelData)) {
parse_str($laravelData, $parsedData);
$laravelData = is_array($parsedData) ? $parsedData : [];
}
return $laravelData;
}
/**
* Build the Guzzle client.
*
* @return \GuzzleHttp\Client
*/
public function buildClient()
{
return new Client([
'handler' => $this->buildHandlerStack(),
'cookies' => true,
]);
}
/**
* Build the before sending handler stack.
*
* @return \GuzzleHttp\HandlerStack
*/
public function buildHandlerStack()
{
return tap(HandlerStack::create(), function ($stack) {
$stack->push($this->buildBeforeSendingHandler());
$stack->push($this->buildRecorderHandler());
$stack->push($this->buildStubHandler());
$this->middleware->each(function ($middleware) use ($stack) {
$stack->push($middleware);
});
});
}
/**
* Build the before sending handler.
*
* @return \Closure
*/
public function buildBeforeSendingHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
return $handler($this->runBeforeSendingCallbacks($request, $options), $options);
};
};
}
/**
* Build the recorder handler.
*
* @return \Closure
*/
public function buildRecorderHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
$promise = $handler($this->runBeforeSendingCallbacks($request, $options), $options);
return $promise->then(function ($response) use ($request, $options) {
optional($this->factory)->recordRequestResponsePair(
(new Request($request))->withData($options['laravel_data']),
new Response($response)
);
return $response;
});
};
};
}
/**
* Build the stub handler.
*
* @return \Closure
*/
public function buildStubHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
$response = ($this->stubCallbacks ?? collect())
->map
->__invoke((new Request($request))->withData($options['laravel_data']), $options)
->filter()
->first();
if (is_null($response)) {
return $handler($request, $options);
}
$response = is_array($response) ? Factory::response($response) : $response;
$sink = $options['sink'] ?? null;
if ($sink) {
$response->then($this->sinkStubHandler($sink));
}
return $response;
};
};
}
/**
* Get the sink stub handler callback.
*
* @param string $sink
* @return \Closure
*/
protected function sinkStubHandler($sink)
{
return function ($response) use ($sink) {
$body = $response->getBody()->getContents();
if (is_string($sink)) {
file_put_contents($sink, $body);
return;
}
fwrite($sink, $body);
rewind($sink);
};
}
/**
* Execute the "before sending" callbacks.
*
* @param \GuzzleHttp\Psr7\RequestInterface $request
* @param array $options
* @return \Closure
*/
public function runBeforeSendingCallbacks($request, array $options)
{
return tap($request, function ($request) use ($options) {
$this->beforeSendingCallbacks->each->__invoke(
(new Request($request))->withData($options['laravel_data']),
$options
);
});
}
/**
* Merge the given options with the current request options.
*
* @param array $options
* @return array
*/
public function mergeOptions(...$options)
{
return array_merge_recursive($this->options, ...$options);
}
/**
* Register a stub callable that will intercept requests and be able to return stub responses.
*
* @param callable $callback
* @return $this
*/
public function stub($callback)
{
$this->stubCallbacks = collect($callback);
return $this;
}
}

View File

@@ -0,0 +1,305 @@
<?php
namespace Illuminate\Http\Client;
use ArrayAccess;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use LogicException;
class Request implements ArrayAccess
{
/**
* The underlying PSR request.
*
* @var \Psr\Http\Message\RequestInterface
*/
protected $request;
/**
* The decoded payload for the request.
*
* @var array
*/
protected $data;
/**
* Create a new request instance.
*
* @param \Psr\Http\Message\RequestInterface $request
* @return void
*/
public function __construct($request)
{
$this->request = $request;
}
/**
* Get the request method.
*
* @return string
*/
public function method()
{
return $this->request->getMethod();
}
/**
* Get the URL of the request.
*
* @return string
*/
public function url()
{
return (string) $this->request->getUri();
}
/**
* Determine if the request has a given header.
*
* @param string $key
* @param mixed $value
* @return bool
*/
public function hasHeader($key, $value = null)
{
if (is_null($value)) {
return ! empty($this->request->getHeaders()[$key]);
}
$headers = $this->headers();
if (! Arr::has($headers, $key)) {
return false;
}
$value = is_array($value) ? $value : [$value];
return empty(array_diff($value, $headers[$key]));
}
/**
* Determine if the request has the given headers.
*
* @param array|string $headers
* @return bool
*/
public function hasHeaders($headers)
{
if (is_string($headers)) {
$headers = [$headers => null];
}
foreach ($headers as $key => $value) {
if (! $this->hasHeader($key, $value)) {
return false;
}
}
return true;
}
/**
* Get the values for the header with the given name.
*
* @param string $key
* @return array
*/
public function header($key)
{
return Arr::get($this->headers(), $key, []);
}
/**
* Get the request headers.
*
* @return array
*/
public function headers()
{
return collect($this->request->getHeaders())->mapWithKeys(function ($values, $header) {
return [$header => $values];
})->all();
}
/**
* Get the body of the request.
*
* @return string
*/
public function body()
{
return (string) $this->request->getBody();
}
/**
* Determine if the request contains the given file.
*
* @param string $name
* @param string|null $value
* @param string|null $filename
* @return bool
*/
public function hasFile($name, $value = null, $filename = null)
{
if (! $this->isMultipart()) {
return false;
}
return collect($this->data)->reject(function ($file) use ($name, $value, $filename) {
return $file['name'] != $name ||
($value && $file['contents'] != $value) ||
($filename && $file['filename'] != $filename);
})->count() > 0;
}
/**
* Get the request's data (form parameters or JSON).
*
* @return array
*/
public function data()
{
if ($this->isForm()) {
return $this->parameters();
} elseif ($this->isJson()) {
return $this->json();
}
return $this->data ?? [];
}
/**
* Get the request's form parameters.
*
* @return array
*/
protected function parameters()
{
if (! $this->data) {
parse_str($this->body(), $parameters);
$this->data = $parameters;
}
return $this->data;
}
/**
* Get the JSON decoded body of the request.
*
* @return array
*/
protected function json()
{
if (! $this->data) {
$this->data = json_decode($this->body(), true);
}
return $this->data;
}
/**
* Determine if the request is simple form data.
*
* @return bool
*/
public function isForm()
{
return $this->hasHeader('Content-Type', 'application/x-www-form-urlencoded');
}
/**
* Determine if the request is JSON.
*
* @return bool
*/
public function isJson()
{
return $this->hasHeader('Content-Type') &&
Str::contains($this->header('Content-Type')[0], 'json');
}
/**
* Determine if the request is multipart.
*
* @return bool
*/
public function isMultipart()
{
return $this->hasHeader('Content-Type') &&
Str::contains($this->header('Content-Type')[0], 'multipart');
}
/**
* Set the decoded data on the request.
*
* @param array $data
* @return $this
*/
public function withData(array $data)
{
$this->data = $data;
return $this;
}
/**
* Get the underlying PSR compliant request instance.
*
* @return \Psr\Http\Message\RequestInterface
*/
public function toPsrRequest()
{
return $this->request;
}
/**
* Determine if the given offset exists.
*
* @param string $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->data()[$offset]);
}
/**
* Get the value for a given offset.
*
* @param string $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->data()[$offset];
}
/**
* Set the value at the given offset.
*
* @param string $offset
* @param mixed $value
* @return void
*
* @throws \LogicException
*/
public function offsetSet($offset, $value)
{
throw new LogicException('Request data may not be mutated using array access.');
}
/**
* Unset the value at the given offset.
*
* @param string $offset
* @return void
*
* @throws \LogicException
*/
public function offsetUnset($offset)
{
throw new LogicException('Request data may not be mutated using array access.');
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Illuminate\Http\Client;
class RequestException extends HttpClientException
{
/**
* The response instance.
*
* @var \Illuminate\Http\Client\Response
*/
public $response;
/**
* Create a new exception instance.
*
* @param \Illuminate\Http\Client\Response $response
* @return void
*/
public function __construct(Response $response)
{
parent::__construct("HTTP request returned status code {$response->status()}.", $response->status());
$this->response = $response;
}
}

View File

@@ -0,0 +1,285 @@
<?php
namespace Illuminate\Http\Client;
use ArrayAccess;
use Illuminate\Support\Traits\Macroable;
use LogicException;
class Response implements ArrayAccess
{
use Macroable {
__call as macroCall;
}
/**
* The underlying PSR response.
*
* @var \Psr\Http\Message\ResponseInterface
*/
protected $response;
/**
* The decoded JSON response.
*
* @var array
*/
protected $decoded;
/**
* Create a new response instance.
*
* @param \Psr\Http\Message\MessageInterface $response
* @return void
*/
public function __construct($response)
{
$this->response = $response;
}
/**
* Get the body of the response.
*
* @return string
*/
public function body()
{
return (string) $this->response->getBody();
}
/**
* Get the JSON decoded body of the response as an array or scalar value.
*
* @return mixed
*/
public function json()
{
if (! $this->decoded) {
$this->decoded = json_decode($this->body(), true);
}
return $this->decoded;
}
/**
* Get the JSON decoded body of the response as an object.
*
* @return object
*/
public function object()
{
return json_decode($this->body(), false);
}
/**
* Get a header from the response.
*
* @param string $header
* @return string
*/
public function header(string $header)
{
return $this->response->getHeaderLine($header);
}
/**
* Get the headers from the response.
*
* @return array
*/
public function headers()
{
return collect($this->response->getHeaders())->mapWithKeys(function ($v, $k) {
return [$k => $v];
})->all();
}
/**
* Get the status code of the response.
*
* @return int
*/
public function status()
{
return (int) $this->response->getStatusCode();
}
/**
* Get the effective URI of the response.
*
* @return \Psr\Http\Message\UriInterface
*/
public function effectiveUri()
{
return $this->transferStats->getEffectiveUri();
}
/**
* Determine if the request was successful.
*
* @return bool
*/
public function successful()
{
return $this->status() >= 200 && $this->status() < 300;
}
/**
* Determine if the response code was "OK".
*
* @return bool
*/
public function ok()
{
return $this->status() === 200;
}
/**
* Determine if the response was a redirect.
*
* @return bool
*/
public function redirect()
{
return $this->status() >= 300 && $this->status() < 400;
}
/**
* Determine if the response indicates a client or server error occurred.
*
* @return bool
*/
public function failed()
{
return $this->serverError() || $this->clientError();
}
/**
* Determine if the response indicates a client error occurred.
*
* @return bool
*/
public function clientError()
{
return $this->status() >= 400 && $this->status() < 500;
}
/**
* Determine if the response indicates a server error occurred.
*
* @return bool
*/
public function serverError()
{
return $this->status() >= 500;
}
/**
* Get the response cookies.
*
* @return \GuzzleHttp\Cookie\CookieJar
*/
public function cookies()
{
return $this->cookies;
}
/**
* Get the underlying PSR response for the response.
*
* @return \Psr\Http\Message\ResponseInterface
*/
public function toPsrResponse()
{
return $this->response;
}
/**
* Throw an exception if a server or client error occurred.
*
* @return $this
*
* @throws \Illuminate\Http\Client\RequestException
*/
public function throw()
{
if ($this->serverError() || $this->clientError()) {
throw new RequestException($this);
}
return $this;
}
/**
* Determine if the given offset exists.
*
* @param string $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->json()[$offset]);
}
/**
* Get the value for a given offset.
*
* @param string $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->json()[$offset];
}
/**
* Set the value at the given offset.
*
* @param string $offset
* @param mixed $value
* @return void
*
* @throws \LogicException
*/
public function offsetSet($offset, $value)
{
throw new LogicException('Response data may not be mutated using array access.');
}
/**
* Unset the value at the given offset.
*
* @param string $offset
* @return void
*
* @throws \LogicException
*/
public function offsetUnset($offset)
{
throw new LogicException('Response data may not be mutated using array access.');
}
/**
* Get the body of the response.
*
* @return string
*/
public function __toString()
{
return $this->body();
}
/**
* Dynamically proxy other methods to the underlying response.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public function __call($method, $parameters)
{
return static::hasMacro($method)
? $this->macroCall($method, $parameters)
: $this->response->{$method}(...$parameters);
}
}

View File

@@ -0,0 +1,153 @@
<?php
namespace Illuminate\Http\Client;
use OutOfBoundsException;
class ResponseSequence
{
/**
* The responses in the sequence.
*
* @var array
*/
protected $responses;
/**
* Indicates that invoking this sequence when it is empty should throw an exception.
*
* @var bool
*/
protected $failWhenEmpty = true;
/**
* The response that should be returned when the sequence is empty.
*
* @var \GuzzleHttp\Promise\PromiseInterface
*/
protected $emptyResponse;
/**
* Create a new response sequence.
*
* @param array $responses
* @return void
*/
public function __construct(array $responses)
{
$this->responses = $responses;
}
/**
* Push a response to the sequence.
*
* @param string|array $body
* @param int $status
* @param array $headers
* @return $this
*/
public function push($body = '', int $status = 200, array $headers = [])
{
$body = is_array($body) ? json_encode($body) : $body;
return $this->pushResponse(
Factory::response($body, $status, $headers)
);
}
/**
* Push a response with the given status code to the sequence.
*
* @param int $status
* @param array $headers
* @return $this
*/
public function pushStatus(int $status, array $headers = [])
{
return $this->pushResponse(
Factory::response('', $status, $headers)
);
}
/**
* Push response with the contents of a file as the body to the sequence.
*
* @param string $filePath
* @param int $status
* @param array $headers
* @return $this
*/
public function pushFile(string $filePath, int $status = 200, array $headers = [])
{
$string = file_get_contents($filePath);
return $this->pushResponse(
Factory::response($string, $status, $headers)
);
}
/**
* Push a response to the sequence.
*
* @param mixed $response
* @return $this
*/
public function pushResponse($response)
{
$this->responses[] = $response;
return $this;
}
/**
* Make the sequence return a default response when it is empty.
*
* @param \GuzzleHttp\Promise\PromiseInterface|\Closure $response
* @return $this
*/
public function whenEmpty($response)
{
$this->failWhenEmpty = false;
$this->emptyResponse = $response;
return $this;
}
/**
* Make the sequence return a default response when it is empty.
*
* @return $this
*/
public function dontFailWhenEmpty()
{
return $this->whenEmpty(Factory::response());
}
/**
* Indicate that this sequence has depleted all of its responses.
*
* @return bool
*/
public function isEmpty()
{
return count($this->responses) === 0;
}
/**
* Get the next response in the sequence.
*
* @return mixed
*/
public function __invoke()
{
if ($this->failWhenEmpty && count($this->responses) === 0) {
throw new OutOfBoundsException('A request was made, but the response sequence is empty.');
}
if (! $this->failWhenEmpty && count($this->responses) === 0) {
return value($this->emptyResponse ?? Factory::response());
}
return array_shift($this->responses);
}
}