Dep: update
주로 PHAN
This commit is contained in:
+17
-1
@@ -1,5 +1,18 @@
|
||||
# Change Log
|
||||
|
||||
## 6.5.5 - 2020-06-16
|
||||
|
||||
* Unpin version constraint for `symfony/polyfill-intl-idn` [#2678](https://github.com/guzzle/guzzle/pull/2678)
|
||||
|
||||
## 6.5.4 - 2020-05-25
|
||||
|
||||
* Fix various intl icu issues [#2626](https://github.com/guzzle/guzzle/pull/2626)
|
||||
|
||||
## 6.5.3 - 2020-04-18
|
||||
|
||||
* Use Symfony intl-idn polyfill [#2550](https://github.com/guzzle/guzzle/pull/2550)
|
||||
* Remove use of internal functions [#2548](https://github.com/guzzle/guzzle/pull/2548)
|
||||
|
||||
## 6.5.2 - 2019-12-23
|
||||
|
||||
* idn_to_ascii() fix for old PHP versions [#2489](https://github.com/guzzle/guzzle/pull/2489)
|
||||
@@ -14,7 +27,10 @@
|
||||
* Improvement: Added support for reset internal queue in MockHandler. [#2143](https://github.com/guzzle/guzzle/pull/2143)
|
||||
* Improvement: Added support to pass arbitrary options to `curl_multi_init`. [#2287](https://github.com/guzzle/guzzle/pull/2287)
|
||||
* Fix: Gracefully handle passing `null` to the `header` option. [#2132](https://github.com/guzzle/guzzle/pull/2132)
|
||||
* Fix: `RetryMiddleware` did not do exponential delay between retires due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132)
|
||||
* Fix: `RetryMiddleware` did not do exponential delay between retries due unit mismatch. [#2132](https://github.com/guzzle/guzzle/pull/2132)
|
||||
Previously, `RetryMiddleware` would sleep for 1 millisecond, then 2 milliseconds, then 4 milliseconds.
|
||||
**After this change, `RetryMiddleware` will sleep for 1 second, then 2 seconds, then 4 seconds.**
|
||||
`Middleware::retry()` accepts a second callback parameter to override the default timeouts if needed.
|
||||
* Fix: Prevent undefined offset when using array for ssl_key options. [#2348](https://github.com/guzzle/guzzle/pull/2348)
|
||||
* Deprecated `ClientInterface::VERSION`
|
||||
|
||||
|
||||
+2
-2
@@ -23,6 +23,7 @@
|
||||
"require": {
|
||||
"php": ">=5.5",
|
||||
"ext-json": "*",
|
||||
"symfony/polyfill-intl-idn": "^1.17.0",
|
||||
"guzzlehttp/promises": "^1.0",
|
||||
"guzzlehttp/psr7": "^1.6.1"
|
||||
},
|
||||
@@ -32,8 +33,7 @@
|
||||
"psr/log": "^1.1"
|
||||
},
|
||||
"suggest": {
|
||||
"psr/log": "Required for using the Log middleware",
|
||||
"ext-intl": "Required for Internationalized Domain Name (IDN) support"
|
||||
"psr/log": "Required for using the Log middleware"
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
|
||||
+7
-17
@@ -2,7 +2,7 @@
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Cookie\CookieJar;
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Exception\GuzzleException;
|
||||
use GuzzleHttp\Promise;
|
||||
use GuzzleHttp\Psr7;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
@@ -47,9 +47,8 @@ class Client implements ClientInterface
|
||||
* wire. The function is called with a Psr7\Http\Message\RequestInterface
|
||||
* and array of transfer options, and must return a
|
||||
* GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
|
||||
* Psr7\Http\Message\ResponseInterface on success. "handler" is a
|
||||
* constructor only option that cannot be overridden in per/request
|
||||
* options. If no handler is provided, a default handler will be created
|
||||
* Psr7\Http\Message\ResponseInterface on success.
|
||||
* If no handler is provided, a default handler will be created
|
||||
* that enables all of the request options below by attaching all of the
|
||||
* default middleware to the handler.
|
||||
* - base_uri: (string|UriInterface) Base URI of the client that is merged
|
||||
@@ -217,7 +216,7 @@ class Client implements ClientInterface
|
||||
|
||||
if (isset($config['idn_conversion']) && ($config['idn_conversion'] !== false)) {
|
||||
$idnOptions = ($config['idn_conversion'] === true) ? IDNA_DEFAULT : $config['idn_conversion'];
|
||||
$uri = _idn_uri_convert($uri, $idnOptions);
|
||||
$uri = Utils::idnUriConvert($uri, $idnOptions);
|
||||
}
|
||||
|
||||
return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
|
||||
@@ -236,19 +235,10 @@ class Client implements ClientInterface
|
||||
'http_errors' => true,
|
||||
'decode_content' => true,
|
||||
'verify' => true,
|
||||
'cookies' => false
|
||||
'cookies' => false,
|
||||
'idn_conversion' => true,
|
||||
];
|
||||
|
||||
// idn_to_ascii() is a part of ext-intl and might be not available
|
||||
$defaults['idn_conversion'] = function_exists('idn_to_ascii')
|
||||
// Old ICU versions don't have this constant, so we are basically stuck (see https://github.com/guzzle/guzzle/pull/2424
|
||||
// and https://github.com/guzzle/guzzle/issues/2448 for details)
|
||||
&& (
|
||||
defined('INTL_IDNA_VARIANT_UTS46')
|
||||
||
|
||||
PHP_VERSION_ID < 70200
|
||||
);
|
||||
|
||||
// Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
|
||||
|
||||
// We can only trust the HTTP_PROXY environment variable in a CLI
|
||||
@@ -498,7 +488,7 @@ class Client implements ClientInterface
|
||||
/**
|
||||
* Throw Exception with pre-set message.
|
||||
* @return void
|
||||
* @throws InvalidArgumentException Invalid body.
|
||||
* @throws \InvalidArgumentException Invalid body.
|
||||
*/
|
||||
private function invalidBody()
|
||||
{
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ interface ClientInterface
|
||||
/**
|
||||
* @deprecated Will be removed in Guzzle 7.0.0
|
||||
*/
|
||||
const VERSION = '6.5.1';
|
||||
const VERSION = '6.5.5';
|
||||
|
||||
/**
|
||||
* Send an HTTP request.
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Utils;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
@@ -102,7 +102,7 @@ class CurlMultiHandler
|
||||
{
|
||||
// Add any delayed handles if needed.
|
||||
if ($this->delays) {
|
||||
$currentTime = \GuzzleHttp\_current_time();
|
||||
$currentTime = Utils::currentTime();
|
||||
foreach ($this->delays as $id => $delay) {
|
||||
if ($currentTime >= $delay) {
|
||||
unset($this->delays[$id]);
|
||||
@@ -154,7 +154,7 @@ class CurlMultiHandler
|
||||
if (empty($easy->options['delay'])) {
|
||||
curl_multi_add_handle($this->_mh, $easy->handle);
|
||||
} else {
|
||||
$this->delays[$id] = \GuzzleHttp\_current_time() + ($easy->options['delay'] / 1000);
|
||||
$this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +206,7 @@ class CurlMultiHandler
|
||||
|
||||
private function timeToNext()
|
||||
{
|
||||
$currentTime = \GuzzleHttp\_current_time();
|
||||
$currentTime = Utils::currentTime();
|
||||
$nextTime = PHP_INT_MAX;
|
||||
foreach ($this->delays as $time) {
|
||||
if ($time < $nextTime) {
|
||||
|
||||
+3
-2
@@ -7,6 +7,7 @@ use GuzzleHttp\Promise\FulfilledPromise;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use GuzzleHttp\Utils;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -33,7 +34,7 @@ class StreamHandler
|
||||
usleep($options['delay'] * 1000);
|
||||
}
|
||||
|
||||
$startTime = isset($options['on_stats']) ? \GuzzleHttp\_current_time() : null;
|
||||
$startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
|
||||
|
||||
try {
|
||||
// Does not support the expect header.
|
||||
@@ -82,7 +83,7 @@ class StreamHandler
|
||||
$stats = new TransferStats(
|
||||
$request,
|
||||
$response,
|
||||
\GuzzleHttp\_current_time() - $startTime,
|
||||
Utils::currentTime() - $startTime,
|
||||
$error,
|
||||
[]
|
||||
);
|
||||
|
||||
+1
-1
@@ -193,7 +193,7 @@ class RedirectMiddleware
|
||||
$uri = $this->redirectUri($request, $response, $protocols);
|
||||
if (isset($options['idn_conversion']) && ($options['idn_conversion'] !== false)) {
|
||||
$idnOptions = ($options['idn_conversion'] === true) ? IDNA_DEFAULT : $options['idn_conversion'];
|
||||
$uri = _idn_uri_convert($uri, $idnOptions);
|
||||
$uri = Utils::idnUriConvert($uri, $idnOptions);
|
||||
}
|
||||
|
||||
$modify['uri'] = $uri;
|
||||
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
use Symfony\Polyfill\Intl\Idn\Idn;
|
||||
|
||||
final class Utils
|
||||
{
|
||||
/**
|
||||
* Wrapper for the hrtime() or microtime() functions
|
||||
* (depending on the PHP version, one of the two is used)
|
||||
*
|
||||
* @return float|mixed UNIX timestamp
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public static function currentTime()
|
||||
{
|
||||
return function_exists('hrtime') ? hrtime(true) / 1e9 : microtime(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $options
|
||||
*
|
||||
* @return UriInterface
|
||||
* @throws InvalidArgumentException
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public static function idnUriConvert(UriInterface $uri, $options = 0)
|
||||
{
|
||||
if ($uri->getHost()) {
|
||||
$asciiHost = self::idnToAsci($uri->getHost(), $options, $info);
|
||||
if ($asciiHost === false) {
|
||||
$errorBitSet = isset($info['errors']) ? $info['errors'] : 0;
|
||||
|
||||
$errorConstants = array_filter(array_keys(get_defined_constants()), function ($name) {
|
||||
return substr($name, 0, 11) === 'IDNA_ERROR_';
|
||||
});
|
||||
|
||||
$errors = [];
|
||||
foreach ($errorConstants as $errorConstant) {
|
||||
if ($errorBitSet & constant($errorConstant)) {
|
||||
$errors[] = $errorConstant;
|
||||
}
|
||||
}
|
||||
|
||||
$errorMessage = 'IDN conversion failed';
|
||||
if ($errors) {
|
||||
$errorMessage .= ' (errors: ' . implode(', ', $errors) . ')';
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException($errorMessage);
|
||||
} else {
|
||||
if ($uri->getHost() !== $asciiHost) {
|
||||
// Replace URI only if the ASCII version is different
|
||||
$uri = $uri->withHost($asciiHost);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $domain
|
||||
* @param int $options
|
||||
* @param array $info
|
||||
*
|
||||
* @return string|false
|
||||
*/
|
||||
private static function idnToAsci($domain, $options, &$info = [])
|
||||
{
|
||||
if (\preg_match('%^[ -~]+$%', $domain) === 1) {
|
||||
return $domain;
|
||||
}
|
||||
|
||||
if (\extension_loaded('intl') && defined('INTL_IDNA_VARIANT_UTS46')) {
|
||||
return \idn_to_ascii($domain, $options, INTL_IDNA_VARIANT_UTS46, $info);
|
||||
}
|
||||
|
||||
/*
|
||||
* The Idn class is marked as @internal. Verify that class and method exists.
|
||||
*/
|
||||
if (method_exists(Idn::class, 'idn_to_ascii')) {
|
||||
return Idn::idn_to_ascii($domain, $options, Idn::INTL_IDNA_VARIANT_UTS46, $info);
|
||||
}
|
||||
|
||||
throw new \RuntimeException('ext-intl or symfony/polyfill-intl-idn not loaded or too old');
|
||||
}
|
||||
}
|
||||
+1
-61
@@ -1,12 +1,10 @@
|
||||
<?php
|
||||
namespace GuzzleHttp;
|
||||
|
||||
use GuzzleHttp\Exception\InvalidArgumentException;
|
||||
use GuzzleHttp\Handler\CurlHandler;
|
||||
use GuzzleHttp\Handler\CurlMultiHandler;
|
||||
use GuzzleHttp\Handler\Proxy;
|
||||
use GuzzleHttp\Handler\StreamHandler;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Expands a URI template
|
||||
@@ -99,8 +97,8 @@ function debug_resource($value = null)
|
||||
*
|
||||
* The returned handler is not wrapped by any default middlewares.
|
||||
*
|
||||
* @throws \RuntimeException if no viable Handler is available.
|
||||
* @return callable Returns the best handler for the given system.
|
||||
* @throws \RuntimeException if no viable Handler is available.
|
||||
*/
|
||||
function choose_handler()
|
||||
{
|
||||
@@ -334,61 +332,3 @@ function json_encode($value, $options = 0, $depth = 512)
|
||||
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper for the hrtime() or microtime() functions
|
||||
* (depending on the PHP version, one of the two is used)
|
||||
*
|
||||
* @return float|mixed UNIX timestamp
|
||||
* @internal
|
||||
*/
|
||||
function _current_time()
|
||||
{
|
||||
return function_exists('hrtime') ? hrtime(true) / 1e9 : microtime(true);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $options
|
||||
*
|
||||
* @return UriInterface
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
function _idn_uri_convert(UriInterface $uri, $options = 0)
|
||||
{
|
||||
if ($uri->getHost()) {
|
||||
$idnaVariant = defined('INTL_IDNA_VARIANT_UTS46') ? INTL_IDNA_VARIANT_UTS46 : 0;
|
||||
$asciiHost = $idnaVariant === 0
|
||||
? idn_to_ascii($uri->getHost(), $options)
|
||||
: idn_to_ascii($uri->getHost(), $options, $idnaVariant, $info);
|
||||
if ($asciiHost === false) {
|
||||
$errorBitSet = isset($info['errors']) ? $info['errors'] : 0;
|
||||
|
||||
$errorConstants = array_filter(array_keys(get_defined_constants()), function ($name) {
|
||||
return substr($name, 0, 11) === 'IDNA_ERROR_';
|
||||
});
|
||||
|
||||
$errors = [];
|
||||
foreach ($errorConstants as $errorConstant) {
|
||||
if ($errorBitSet & constant($errorConstant)) {
|
||||
$errors[] = $errorConstant;
|
||||
}
|
||||
}
|
||||
|
||||
$errorMessage = 'IDN conversion failed';
|
||||
if ($errors) {
|
||||
$errorMessage .= ' (errors: ' . implode(', ', $errors) . ')';
|
||||
}
|
||||
|
||||
throw new InvalidArgumentException($errorMessage);
|
||||
} else {
|
||||
if ($uri->getHost() !== $asciiHost) {
|
||||
// Replace URI only if the ASCII version is different
|
||||
$uri = $uri->withHost($asciiHost);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $uri;
|
||||
}
|
||||
|
||||
+19
@@ -1,5 +1,24 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 1.4.1 - 2021-02-18
|
||||
|
||||
- Fixed `each_limit` skipping promises and failing
|
||||
|
||||
## 1.4.0 - 2020-09-30
|
||||
|
||||
### Added
|
||||
|
||||
- Support for PHP 8
|
||||
- Optional `$recursive` flag to `all`
|
||||
- Replaced functions by static methods
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix empty `each` processing
|
||||
- Fix promise handling for Iterators of non-unique keys
|
||||
- Fixed `method_exists` crashes on PHP 8
|
||||
- Memory leak on exceptions
|
||||
|
||||
|
||||
## 1.3.1 - 2016-12-20
|
||||
|
||||
|
||||
Vendored
+35
-7
@@ -26,7 +26,7 @@ for a general introduction to promises.
|
||||
- Promises can be cancelled.
|
||||
- Works with any object that has a `then` function.
|
||||
- C# style async/await coroutine promises using
|
||||
`GuzzleHttp\Promise\coroutine()`.
|
||||
`GuzzleHttp\Promise\Coroutine::of()`.
|
||||
|
||||
|
||||
# Quick start
|
||||
@@ -88,7 +88,7 @@ $promise
|
||||
});
|
||||
|
||||
// Resolving the promise triggers the $onFulfilled callbacks and outputs
|
||||
// "Hello, reader".
|
||||
// "Hello, reader."
|
||||
$promise->resolve('reader.');
|
||||
```
|
||||
|
||||
@@ -150,7 +150,7 @@ use GuzzleHttp\Promise\Promise;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise->then(null, function ($reason) {
|
||||
throw new \Exception($reason);
|
||||
throw new Exception($reason);
|
||||
})->then(null, function ($reason) {
|
||||
assert($reason->getMessage() === 'Error!');
|
||||
});
|
||||
@@ -182,7 +182,6 @@ invoked using the value returned from the `$onRejected` callback.
|
||||
|
||||
```php
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\RejectedPromise;
|
||||
|
||||
$promise = new Promise();
|
||||
$promise
|
||||
@@ -220,7 +219,7 @@ the promise is rejected with the exception and the exception is thrown.
|
||||
|
||||
```php
|
||||
$promise = new Promise(function () use (&$promise) {
|
||||
throw new \Exception('foo');
|
||||
throw new Exception('foo');
|
||||
});
|
||||
|
||||
$promise->wait(); // throws the exception.
|
||||
@@ -397,7 +396,7 @@ $deferred = new React\Promise\Deferred();
|
||||
$reactPromise = $deferred->promise();
|
||||
|
||||
// Create a Guzzle promise that is fulfilled with a React promise.
|
||||
$guzzlePromise = new \GuzzleHttp\Promise\Promise();
|
||||
$guzzlePromise = new GuzzleHttp\Promise\Promise();
|
||||
$guzzlePromise->then(function ($value) use ($reactPromise) {
|
||||
// Do something something with the value...
|
||||
// Return the React promise
|
||||
@@ -424,7 +423,7 @@ instance.
|
||||
|
||||
```php
|
||||
// Get the global task queue
|
||||
$queue = \GuzzleHttp\Promise\queue();
|
||||
$queue = GuzzleHttp\Promise\Utils::queue();
|
||||
$queue->run();
|
||||
```
|
||||
|
||||
@@ -502,3 +501,32 @@ $promise->then(function ($value) { echo $value; });
|
||||
$promise->resolve('foo');
|
||||
// prints "foo"
|
||||
```
|
||||
|
||||
|
||||
## Upgrading from Function API
|
||||
|
||||
A static API was first introduced in 1.4.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API will be removed in 2.0.0. A migration table has been provided here for your convenience:
|
||||
|
||||
| Original Function | Replacement Method |
|
||||
|----------------|----------------|
|
||||
| `queue` | `Utils::queue` |
|
||||
| `task` | `Utils::task` |
|
||||
| `promise_for` | `Create::promiseFor` |
|
||||
| `rejection_for` | `Create::rejectionFor` |
|
||||
| `exception_for` | `Create::exceptionFor` |
|
||||
| `iter_for` | `Create::iterFor` |
|
||||
| `inspect` | `Utils::inspect` |
|
||||
| `inspect_all` | `Utils::inspectAll` |
|
||||
| `unwrap` | `Utils::unwrap` |
|
||||
| `all` | `Utils::all` |
|
||||
| `some` | `Utils::some` |
|
||||
| `any` | `Utils::any` |
|
||||
| `settle` | `Utils::settle` |
|
||||
| `each` | `Each::of` |
|
||||
| `each_limit` | `Each::ofLimit` |
|
||||
| `each_limit_all` | `Each::ofLimitAll` |
|
||||
| `!is_fulfilled` | `Is::pending` |
|
||||
| `is_fulfilled` | `Is::fulfilled` |
|
||||
| `is_rejected` | `Is::rejected` |
|
||||
| `is_settled` | `Is::settled` |
|
||||
| `coroutine` | `Coroutine::of` |
|
||||
|
||||
+9
-4
@@ -11,10 +11,10 @@
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": ">=5.5.0"
|
||||
"php": ">=5.5"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^4.0"
|
||||
"symfony/phpunit-bridge": "^4.4 || ^5.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
@@ -22,9 +22,14 @@
|
||||
},
|
||||
"files": ["src/functions_include.php"]
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"GuzzleHttp\\Promise\\Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vendor/bin/phpunit",
|
||||
"test-ci": "vendor/bin/phpunit --coverage-text"
|
||||
"test": "vendor/bin/simple-phpunit",
|
||||
"test-ci": "vendor/bin/simple-phpunit --coverage-text"
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
|
||||
+23
-5
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
use Exception;
|
||||
@@ -9,7 +10,7 @@ use Throwable;
|
||||
* Creates a promise that is resolved using a generator that yields values or
|
||||
* promises (somewhat similar to C#'s async keyword).
|
||||
*
|
||||
* When called, the coroutine function will start an instance of the generator
|
||||
* When called, the Coroutine::of method will start an instance of the generator
|
||||
* and returns a promise that is fulfilled with its final yielded value.
|
||||
*
|
||||
* Control is returned back to the generator when the yielded promise settles.
|
||||
@@ -22,7 +23,7 @@ use Throwable;
|
||||
* return new Promise\FulfilledPromise($value);
|
||||
* }
|
||||
*
|
||||
* $promise = Promise\coroutine(function () {
|
||||
* $promise = Promise\Coroutine::of(function () {
|
||||
* $value = (yield createPromise('a'));
|
||||
* try {
|
||||
* $value = (yield createPromise($value . 'b'));
|
||||
@@ -38,6 +39,7 @@ use Throwable;
|
||||
* @param callable $generatorFn Generator function to wrap into a promise.
|
||||
*
|
||||
* @return Promise
|
||||
*
|
||||
* @link https://github.com/petkaantonov/bluebird/blob/master/API.md#generators inspiration
|
||||
*/
|
||||
final class Coroutine implements PromiseInterface
|
||||
@@ -65,7 +67,23 @@ final class Coroutine implements PromiseInterface
|
||||
$this->currentPromise->wait();
|
||||
}
|
||||
});
|
||||
$this->nextCoroutine($this->generator->current());
|
||||
try {
|
||||
$this->nextCoroutine($this->generator->current());
|
||||
} catch (\Exception $exception) {
|
||||
$this->result->reject($exception);
|
||||
} catch (Throwable $throwable) {
|
||||
$this->result->reject($throwable);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new coroutine.
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public static function of(callable $generatorFn)
|
||||
{
|
||||
return new self($generatorFn);
|
||||
}
|
||||
|
||||
public function then(
|
||||
@@ -108,7 +126,7 @@ final class Coroutine implements PromiseInterface
|
||||
|
||||
private function nextCoroutine($yielded)
|
||||
{
|
||||
$this->currentPromise = promise_for($yielded)
|
||||
$this->currentPromise = Create::promiseFor($yielded)
|
||||
->then([$this, '_handleSuccess'], [$this, '_handleFailure']);
|
||||
}
|
||||
|
||||
@@ -139,7 +157,7 @@ final class Coroutine implements PromiseInterface
|
||||
{
|
||||
unset($this->currentPromise);
|
||||
try {
|
||||
$nextYield = $this->generator->throw(exception_for($reason));
|
||||
$nextYield = $this->generator->throw(Create::exceptionFor($reason));
|
||||
// The throw was caught, so keep iterating on the coroutine
|
||||
$this->nextCoroutine($nextYield);
|
||||
} catch (Exception $exception) {
|
||||
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class Create
|
||||
{
|
||||
/**
|
||||
* Creates a promise for a value if the value is not a promise.
|
||||
*
|
||||
* @param mixed $value Promise or value.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function promiseFor($value)
|
||||
{
|
||||
if ($value instanceof PromiseInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// Return a Guzzle promise that shadows the given promise.
|
||||
if (is_object($value) && method_exists($value, 'then')) {
|
||||
$wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
|
||||
$cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
|
||||
$promise = new Promise($wfn, $cfn);
|
||||
$value->then([$promise, 'resolve'], [$promise, 'reject']);
|
||||
return $promise;
|
||||
}
|
||||
|
||||
return new FulfilledPromise($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a rejected promise for a reason if the reason is not a promise.
|
||||
* If the provided reason is a promise, then it is returned as-is.
|
||||
*
|
||||
* @param mixed $reason Promise or reason.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function rejectionFor($reason)
|
||||
{
|
||||
if ($reason instanceof PromiseInterface) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
return new RejectedPromise($reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an exception for a rejected promise value.
|
||||
*
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @return \Exception|\Throwable
|
||||
*/
|
||||
public static function exceptionFor($reason)
|
||||
{
|
||||
if ($reason instanceof \Exception || $reason instanceof \Throwable) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
return new RejectionException($reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an iterator for the given value.
|
||||
*
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return \Iterator
|
||||
*/
|
||||
public static function iterFor($value)
|
||||
{
|
||||
if ($value instanceof \Iterator) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return new \ArrayIterator($value);
|
||||
}
|
||||
|
||||
return new \ArrayIterator([$value]);
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class Each
|
||||
{
|
||||
/**
|
||||
* Given an iterator that yields promises or values, returns a promise that
|
||||
* is fulfilled with a null value when the iterator has been consumed or
|
||||
* the aggregate promise has been fulfilled or rejected.
|
||||
*
|
||||
* $onFulfilled is a function that accepts the fulfilled value, iterator
|
||||
* index, and the aggregate promise. The callback can invoke any necessary
|
||||
* side effects and choose to resolve or reject the aggregate if needed.
|
||||
*
|
||||
* $onRejected is a function that accepts the rejection reason, iterator
|
||||
* index, and the aggregate promise. The callback can invoke any necessary
|
||||
* side effects and choose to resolve or reject the aggregate if needed.
|
||||
*
|
||||
* @param mixed $iterable Iterator or array to iterate over.
|
||||
* @param callable $onFulfilled
|
||||
* @param callable $onRejected
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function of(
|
||||
$iterable,
|
||||
callable $onFulfilled = null,
|
||||
callable $onRejected = null
|
||||
) {
|
||||
return (new EachPromise($iterable, [
|
||||
'fulfilled' => $onFulfilled,
|
||||
'rejected' => $onRejected
|
||||
]))->promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Like of, but only allows a certain number of outstanding promises at any
|
||||
* given time.
|
||||
*
|
||||
* $concurrency may be an integer or a function that accepts the number of
|
||||
* pending promises and returns a numeric concurrency limit value to allow
|
||||
* for dynamic a concurrency size.
|
||||
*
|
||||
* @param mixed $iterable
|
||||
* @param int|callable $concurrency
|
||||
* @param callable $onFulfilled
|
||||
* @param callable $onRejected
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function ofLimit(
|
||||
$iterable,
|
||||
$concurrency,
|
||||
callable $onFulfilled = null,
|
||||
callable $onRejected = null
|
||||
) {
|
||||
return (new EachPromise($iterable, [
|
||||
'fulfilled' => $onFulfilled,
|
||||
'rejected' => $onRejected,
|
||||
'concurrency' => $concurrency
|
||||
]))->promise();
|
||||
}
|
||||
|
||||
/**
|
||||
* Like limit, but ensures that no promise in the given $iterable argument
|
||||
* is rejected. If any promise is rejected, then the aggregate promise is
|
||||
* rejected with the encountered rejection.
|
||||
*
|
||||
* @param mixed $iterable
|
||||
* @param int|callable $concurrency
|
||||
* @param callable $onFulfilled
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function ofLimitAll(
|
||||
$iterable,
|
||||
$concurrency,
|
||||
callable $onFulfilled = null
|
||||
) {
|
||||
return each_limit(
|
||||
$iterable,
|
||||
$concurrency,
|
||||
$onFulfilled,
|
||||
function ($reason, $idx, PromiseInterface $aggregate) {
|
||||
$aggregate->reject($reason);
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+48
-23
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -9,22 +10,24 @@ class EachPromise implements PromisorInterface
|
||||
{
|
||||
private $pending = [];
|
||||
|
||||
/** @var \Iterator */
|
||||
private $nextPendingIndex = 0;
|
||||
|
||||
/** @var \Iterator|null */
|
||||
private $iterable;
|
||||
|
||||
/** @var callable|int */
|
||||
/** @var callable|int|null */
|
||||
private $concurrency;
|
||||
|
||||
/** @var callable */
|
||||
/** @var callable|null */
|
||||
private $onFulfilled;
|
||||
|
||||
/** @var callable */
|
||||
/** @var callable|null */
|
||||
private $onRejected;
|
||||
|
||||
/** @var Promise */
|
||||
/** @var Promise|null */
|
||||
private $aggregate;
|
||||
|
||||
/** @var bool */
|
||||
/** @var bool|null */
|
||||
private $mutex;
|
||||
|
||||
/**
|
||||
@@ -45,12 +48,12 @@ class EachPromise implements PromisorInterface
|
||||
* allowed number of outstanding concurrently executing promises,
|
||||
* creating a capped pool of promises. There is no limit by default.
|
||||
*
|
||||
* @param mixed $iterable Promises or values to iterate.
|
||||
* @param array $config Configuration options
|
||||
* @param mixed $iterable Promises or values to iterate.
|
||||
* @param array $config Configuration options
|
||||
*/
|
||||
public function __construct($iterable, array $config = [])
|
||||
{
|
||||
$this->iterable = iter_for($iterable);
|
||||
$this->iterable = Create::iterFor($iterable);
|
||||
|
||||
if (isset($config['concurrency'])) {
|
||||
$this->concurrency = $config['concurrency'];
|
||||
@@ -65,6 +68,7 @@ class EachPromise implements PromisorInterface
|
||||
}
|
||||
}
|
||||
|
||||
/** @psalm-suppress InvalidNullableReturnType */
|
||||
public function promise()
|
||||
{
|
||||
if ($this->aggregate) {
|
||||
@@ -73,14 +77,29 @@ class EachPromise implements PromisorInterface
|
||||
|
||||
try {
|
||||
$this->createPromise();
|
||||
/** @psalm-assert Promise $this->aggregate */
|
||||
$this->iterable->rewind();
|
||||
$this->refillPending();
|
||||
if (!$this->checkIfFinished()) {
|
||||
$this->refillPending();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
/**
|
||||
* @psalm-suppress NullReference
|
||||
* @phpstan-ignore-next-line
|
||||
*/
|
||||
$this->aggregate->reject($e);
|
||||
} catch (\Exception $e) {
|
||||
/**
|
||||
* @psalm-suppress NullReference
|
||||
* @phpstan-ignore-next-line
|
||||
*/
|
||||
$this->aggregate->reject($e);
|
||||
}
|
||||
|
||||
/**
|
||||
* @psalm-suppress NullableReturnStatement
|
||||
* @phpstan-ignore-next-line
|
||||
*/
|
||||
return $this->aggregate;
|
||||
}
|
||||
|
||||
@@ -89,17 +108,12 @@ class EachPromise implements PromisorInterface
|
||||
$this->mutex = false;
|
||||
$this->aggregate = new Promise(function () {
|
||||
reset($this->pending);
|
||||
if (empty($this->pending) && !$this->iterable->valid()) {
|
||||
$this->aggregate->resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Consume a potentially fluctuating list of promises while
|
||||
// ensuring that indexes are maintained (precluding array_shift).
|
||||
while ($promise = current($this->pending)) {
|
||||
next($this->pending);
|
||||
$promise->wait();
|
||||
if ($this->aggregate->getState() !== PromiseInterface::PENDING) {
|
||||
if (Is::settled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -109,6 +123,7 @@ class EachPromise implements PromisorInterface
|
||||
$clearFn = function () {
|
||||
$this->iterable = $this->concurrency = $this->pending = null;
|
||||
$this->onFulfilled = $this->onRejected = null;
|
||||
$this->nextPendingIndex = 0;
|
||||
};
|
||||
|
||||
$this->aggregate->then($clearFn, $clearFn);
|
||||
@@ -148,22 +163,32 @@ class EachPromise implements PromisorInterface
|
||||
return false;
|
||||
}
|
||||
|
||||
$promise = promise_for($this->iterable->current());
|
||||
$idx = $this->iterable->key();
|
||||
$promise = Create::promiseFor($this->iterable->current());
|
||||
$key = $this->iterable->key();
|
||||
|
||||
// Iterable keys may not be unique, so we use a counter to
|
||||
// guarantee uniqueness
|
||||
$idx = $this->nextPendingIndex++;
|
||||
|
||||
$this->pending[$idx] = $promise->then(
|
||||
function ($value) use ($idx) {
|
||||
function ($value) use ($idx, $key) {
|
||||
if ($this->onFulfilled) {
|
||||
call_user_func(
|
||||
$this->onFulfilled, $value, $idx, $this->aggregate
|
||||
$this->onFulfilled,
|
||||
$value,
|
||||
$key,
|
||||
$this->aggregate
|
||||
);
|
||||
}
|
||||
$this->step($idx);
|
||||
},
|
||||
function ($reason) use ($idx) {
|
||||
function ($reason) use ($idx, $key) {
|
||||
if ($this->onRejected) {
|
||||
call_user_func(
|
||||
$this->onRejected, $reason, $idx, $this->aggregate
|
||||
$this->onRejected,
|
||||
$reason,
|
||||
$key,
|
||||
$this->aggregate
|
||||
);
|
||||
}
|
||||
$this->step($idx);
|
||||
@@ -201,7 +226,7 @@ class EachPromise implements PromisorInterface
|
||||
private function step($idx)
|
||||
{
|
||||
// If the promise was already resolved, then ignore this step.
|
||||
if ($this->aggregate->getState() !== PromiseInterface::PENDING) {
|
||||
if (Is::settled($this->aggregate)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+6
-4
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -13,9 +14,10 @@ class FulfilledPromise implements PromiseInterface
|
||||
|
||||
public function __construct($value)
|
||||
{
|
||||
if (method_exists($value, 'then')) {
|
||||
if (is_object($value) && method_exists($value, 'then')) {
|
||||
throw new \InvalidArgumentException(
|
||||
'You cannot create a FulfilledPromise with a promise.');
|
||||
'You cannot create a FulfilledPromise with a promise.'
|
||||
);
|
||||
}
|
||||
|
||||
$this->value = $value;
|
||||
@@ -30,11 +32,11 @@ class FulfilledPromise implements PromiseInterface
|
||||
return $this;
|
||||
}
|
||||
|
||||
$queue = queue();
|
||||
$queue = Utils::queue();
|
||||
$p = new Promise([$queue, 'run']);
|
||||
$value = $this->value;
|
||||
$queue->add(static function () use ($p, $value, $onFulfilled) {
|
||||
if ($p->getState() === self::PENDING) {
|
||||
if (Is::pending($p)) {
|
||||
try {
|
||||
$p->resolve($onFulfilled($value));
|
||||
} catch (\Throwable $e) {
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class Is
|
||||
{
|
||||
/**
|
||||
* Returns true if a promise is pending.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function pending(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::PENDING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled or rejected.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function settled(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() !== PromiseInterface::PENDING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function fulfilled(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::FULFILLED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is rejected.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function rejected(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::REJECTED;
|
||||
}
|
||||
}
|
||||
+33
-35
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -41,14 +42,13 @@ class Promise implements PromiseInterface
|
||||
|
||||
// Return a fulfilled promise and immediately invoke any callbacks.
|
||||
if ($this->state === self::FULFILLED) {
|
||||
return $onFulfilled
|
||||
? promise_for($this->result)->then($onFulfilled)
|
||||
: promise_for($this->result);
|
||||
$promise = Create::promiseFor($this->result);
|
||||
return $onFulfilled ? $promise->then($onFulfilled) : $promise;
|
||||
}
|
||||
|
||||
// It's either cancelled or rejected, so return a rejected promise
|
||||
// and immediately invoke any callbacks.
|
||||
$rejection = rejection_for($this->result);
|
||||
$rejection = Create::rejectionFor($this->result);
|
||||
return $onRejected ? $rejection->then(null, $onRejected) : $rejection;
|
||||
}
|
||||
|
||||
@@ -61,19 +61,15 @@ class Promise implements PromiseInterface
|
||||
{
|
||||
$this->waitIfPending();
|
||||
|
||||
$inner = $this->result instanceof PromiseInterface
|
||||
? $this->result->wait($unwrap)
|
||||
: $this->result;
|
||||
|
||||
if ($this->result instanceof PromiseInterface) {
|
||||
return $this->result->wait($unwrap);
|
||||
}
|
||||
if ($unwrap) {
|
||||
if ($this->result instanceof PromiseInterface
|
||||
|| $this->state === self::FULFILLED
|
||||
) {
|
||||
return $inner;
|
||||
} else {
|
||||
// It's rejected so "unwrap" and throw an exception.
|
||||
throw exception_for($inner);
|
||||
if ($this->state === self::FULFILLED) {
|
||||
return $this->result;
|
||||
}
|
||||
// It's rejected so "unwrap" and throw an exception.
|
||||
throw Create::exceptionFor($this->result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +99,7 @@ class Promise implements PromiseInterface
|
||||
}
|
||||
|
||||
// Reject the promise only if it wasn't rejected in a then callback.
|
||||
/** @psalm-suppress RedundantCondition */
|
||||
if ($this->state === self::PENDING) {
|
||||
$this->reject(new CancellationException('Promise has been cancelled'));
|
||||
}
|
||||
@@ -148,17 +145,15 @@ class Promise implements PromiseInterface
|
||||
|
||||
// If the value was not a settled promise or a thenable, then resolve
|
||||
// it in the task queue using the correct ID.
|
||||
if (!method_exists($value, 'then')) {
|
||||
if (!is_object($value) || !method_exists($value, 'then')) {
|
||||
$id = $state === self::FULFILLED ? 1 : 2;
|
||||
// It's a success, so resolve the handlers in the queue.
|
||||
queue()->add(static function () use ($id, $value, $handlers) {
|
||||
Utils::queue()->add(static function () use ($id, $value, $handlers) {
|
||||
foreach ($handlers as $handler) {
|
||||
self::callHandler($id, $value, $handler);
|
||||
}
|
||||
});
|
||||
} elseif ($value instanceof Promise
|
||||
&& $value->getState() === self::PENDING
|
||||
) {
|
||||
} elseif ($value instanceof Promise && Is::pending($value)) {
|
||||
// We can just merge our handlers onto the next promise.
|
||||
$value->handlers = array_merge($value->handlers, $handlers);
|
||||
} else {
|
||||
@@ -184,8 +179,6 @@ class Promise implements PromiseInterface
|
||||
* @param int $index 1 (resolve) or 2 (reject).
|
||||
* @param mixed $value Value to pass to the callback.
|
||||
* @param array $handler Array of handler data (promise and callbacks).
|
||||
*
|
||||
* @return array Returns the next group to resolve.
|
||||
*/
|
||||
private static function callHandler($index, $value, array $handler)
|
||||
{
|
||||
@@ -194,13 +187,21 @@ class Promise implements PromiseInterface
|
||||
|
||||
// The promise may have been cancelled or resolved before placing
|
||||
// this thunk in the queue.
|
||||
if ($promise->getState() !== self::PENDING) {
|
||||
if (Is::settled($promise)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (isset($handler[$index])) {
|
||||
$promise->resolve($handler[$index]($value));
|
||||
/*
|
||||
* If $f throws an exception, then $handler will be in the exception
|
||||
* stack trace. Since $handler contains a reference to the callable
|
||||
* itself we get a circular reference. We clear the $handler
|
||||
* here to avoid that memory leak.
|
||||
*/
|
||||
$f = $handler[$index];
|
||||
unset($handler);
|
||||
$promise->resolve($f($value));
|
||||
} elseif ($index === 1) {
|
||||
// Forward resolution values as-is.
|
||||
$promise->resolve($value);
|
||||
@@ -224,15 +225,16 @@ class Promise implements PromiseInterface
|
||||
} elseif ($this->waitList) {
|
||||
$this->invokeWaitList();
|
||||
} else {
|
||||
// If there's not wait function, then reject the promise.
|
||||
// If there's no wait function, then reject the promise.
|
||||
$this->reject('Cannot wait on a promise that has '
|
||||
. 'no internal wait function. You must provide a wait '
|
||||
. 'function when constructing the promise to be able to '
|
||||
. 'wait on a promise.');
|
||||
}
|
||||
|
||||
queue()->run();
|
||||
Utils::queue()->run();
|
||||
|
||||
/** @psalm-suppress RedundantCondition */
|
||||
if ($this->state === self::PENDING) {
|
||||
$this->reject('Invoking the wait callback did not resolve the promise');
|
||||
}
|
||||
@@ -263,17 +265,13 @@ class Promise implements PromiseInterface
|
||||
$this->waitList = null;
|
||||
|
||||
foreach ($waitList as $result) {
|
||||
while (true) {
|
||||
do {
|
||||
$result->waitIfPending();
|
||||
$result = $result->result;
|
||||
} while ($result instanceof Promise);
|
||||
|
||||
if ($result->result instanceof Promise) {
|
||||
$result = $result->result;
|
||||
} else {
|
||||
if ($result->result instanceof PromiseInterface) {
|
||||
$result->result->wait(false);
|
||||
}
|
||||
break;
|
||||
}
|
||||
if ($result instanceof PromiseInterface) {
|
||||
$result->wait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -56,6 +57,7 @@ interface PromiseInterface
|
||||
* Resolve the promise with the given value.
|
||||
*
|
||||
* @param mixed $value
|
||||
*
|
||||
* @throws \RuntimeException if the promise is already resolved.
|
||||
*/
|
||||
public function resolve($value);
|
||||
@@ -64,6 +66,7 @@ interface PromiseInterface
|
||||
* Reject the promise with the given reason.
|
||||
*
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @throws \RuntimeException if the promise is already resolved.
|
||||
*/
|
||||
public function reject($reason);
|
||||
@@ -86,6 +89,7 @@ interface PromiseInterface
|
||||
* @param bool $unwrap
|
||||
*
|
||||
* @return mixed
|
||||
*
|
||||
* @throws \LogicException if the promise has no wait function or if the
|
||||
* promise does not settle after waiting.
|
||||
*/
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
|
||||
+9
-5
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -13,9 +14,10 @@ class RejectedPromise implements PromiseInterface
|
||||
|
||||
public function __construct($reason)
|
||||
{
|
||||
if (method_exists($reason, 'then')) {
|
||||
if (is_object($reason) && method_exists($reason, 'then')) {
|
||||
throw new \InvalidArgumentException(
|
||||
'You cannot create a RejectedPromise with a promise.');
|
||||
'You cannot create a RejectedPromise with a promise.'
|
||||
);
|
||||
}
|
||||
|
||||
$this->reason = $reason;
|
||||
@@ -30,11 +32,11 @@ class RejectedPromise implements PromiseInterface
|
||||
return $this;
|
||||
}
|
||||
|
||||
$queue = queue();
|
||||
$queue = Utils::queue();
|
||||
$reason = $this->reason;
|
||||
$p = new Promise([$queue, 'run']);
|
||||
$queue->add(static function () use ($p, $reason, $onRejected) {
|
||||
if ($p->getState() === self::PENDING) {
|
||||
if (Is::pending($p)) {
|
||||
try {
|
||||
// Return a resolved promise if onRejected does not throw.
|
||||
$p->resolve($onRejected($reason));
|
||||
@@ -59,8 +61,10 @@ class RejectedPromise implements PromiseInterface
|
||||
public function wait($unwrap = true, $defaultDelivery = null)
|
||||
{
|
||||
if ($unwrap) {
|
||||
throw exception_for($this->reason);
|
||||
throw Create::exceptionFor($this->reason);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getState()
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -12,7 +13,7 @@ class RejectionException extends \RuntimeException
|
||||
private $reason;
|
||||
|
||||
/**
|
||||
* @param mixed $reason Rejection reason.
|
||||
* @param mixed $reason Rejection reason.
|
||||
* @param string $description Optional description
|
||||
*/
|
||||
public function __construct($reason, $description = null)
|
||||
|
||||
+3
-2
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -8,7 +9,7 @@ namespace GuzzleHttp\Promise;
|
||||
* maintains a constant stack size. You can use the task queue asynchronously
|
||||
* by calling the `run()` function of the global task queue in an event loop.
|
||||
*
|
||||
* GuzzleHttp\Promise\queue()->run();
|
||||
* GuzzleHttp\Promise\Utils::queue()->run();
|
||||
*/
|
||||
class TaskQueue implements TaskQueueInterface
|
||||
{
|
||||
@@ -42,8 +43,8 @@ class TaskQueue implements TaskQueueInterface
|
||||
|
||||
public function run()
|
||||
{
|
||||
/** @var callable $task */
|
||||
while ($task = array_shift($this->queue)) {
|
||||
/** @var callable $task */
|
||||
$task();
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
interface TaskQueueInterface
|
||||
@@ -13,8 +14,6 @@ interface TaskQueueInterface
|
||||
/**
|
||||
* Adds a task to the queue that will be executed the next time run is
|
||||
* called.
|
||||
*
|
||||
* @param callable $task
|
||||
*/
|
||||
public function add(callable $task);
|
||||
|
||||
|
||||
+274
@@ -0,0 +1,274 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
final class Utils
|
||||
{
|
||||
/**
|
||||
* Get the global task queue used for promise resolution.
|
||||
*
|
||||
* This task queue MUST be run in an event loop in order for promises to be
|
||||
* settled asynchronously. It will be automatically run when synchronously
|
||||
* waiting on a promise.
|
||||
*
|
||||
* <code>
|
||||
* while ($eventLoop->isRunning()) {
|
||||
* GuzzleHttp\Promise\Utils::queue()->run();
|
||||
* }
|
||||
* </code>
|
||||
*
|
||||
* @param TaskQueueInterface $assign Optionally specify a new queue instance.
|
||||
*
|
||||
* @return TaskQueueInterface
|
||||
*/
|
||||
public static function queue(TaskQueueInterface $assign = null)
|
||||
{
|
||||
static $queue;
|
||||
|
||||
if ($assign) {
|
||||
$queue = $assign;
|
||||
} elseif (!$queue) {
|
||||
$queue = new TaskQueue();
|
||||
}
|
||||
|
||||
return $queue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a function to run in the task queue when it is next `run()` and
|
||||
* returns a promise that is fulfilled or rejected with the result.
|
||||
*
|
||||
* @param callable $task Task function to run.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function task(callable $task)
|
||||
{
|
||||
$queue = self::queue();
|
||||
$promise = new Promise([$queue, 'run']);
|
||||
$queue->add(function () use ($task, $promise) {
|
||||
try {
|
||||
$promise->resolve($task());
|
||||
} catch (\Throwable $e) {
|
||||
$promise->reject($e);
|
||||
} catch (\Exception $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
});
|
||||
|
||||
return $promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously waits on a promise to resolve and returns an inspection
|
||||
* state array.
|
||||
*
|
||||
* Returns a state associative array containing a "state" key mapping to a
|
||||
* valid promise state. If the state of the promise is "fulfilled", the
|
||||
* array will contain a "value" key mapping to the fulfilled value of the
|
||||
* promise. If the promise is rejected, the array will contain a "reason"
|
||||
* key mapping to the rejection reason of the promise.
|
||||
*
|
||||
* @param PromiseInterface $promise Promise or value.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function inspect(PromiseInterface $promise)
|
||||
{
|
||||
try {
|
||||
return [
|
||||
'state' => PromiseInterface::FULFILLED,
|
||||
'value' => $promise->wait()
|
||||
];
|
||||
} catch (RejectionException $e) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()];
|
||||
} catch (\Throwable $e) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
|
||||
} catch (\Exception $e) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits on all of the provided promises, but does not unwrap rejected
|
||||
* promises as thrown exception.
|
||||
*
|
||||
* Returns an array of inspection state arrays.
|
||||
*
|
||||
* @see inspect for the inspection state array format.
|
||||
*
|
||||
* @param PromiseInterface[] $promises Traversable of promises to wait upon.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function inspectAll($promises)
|
||||
{
|
||||
$results = [];
|
||||
foreach ($promises as $key => $promise) {
|
||||
$results[$key] = inspect($promise);
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits on all of the provided promises and returns the fulfilled values.
|
||||
*
|
||||
* Returns an array that contains the value of each promise (in the same
|
||||
* order the promises were provided). An exception is thrown if any of the
|
||||
* promises are rejected.
|
||||
*
|
||||
* @param iterable<PromiseInterface> $promises Iterable of PromiseInterface objects to wait on.
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @throws \Exception on error
|
||||
* @throws \Throwable on error in PHP >=7
|
||||
*/
|
||||
public static function unwrap($promises)
|
||||
{
|
||||
$results = [];
|
||||
foreach ($promises as $key => $promise) {
|
||||
$results[$key] = $promise->wait();
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an array of promises, return a promise that is fulfilled when all
|
||||
* the items in the array are fulfilled.
|
||||
*
|
||||
* The promise's fulfillment value is an array with fulfillment values at
|
||||
* respective positions to the original array. If any promise in the array
|
||||
* rejects, the returned promise is rejected with the rejection reason.
|
||||
*
|
||||
* @param mixed $promises Promises or values.
|
||||
* @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function all($promises, $recursive = false)
|
||||
{
|
||||
$results = [];
|
||||
$promise = Each::of(
|
||||
$promises,
|
||||
function ($value, $idx) use (&$results) {
|
||||
$results[$idx] = $value;
|
||||
},
|
||||
function ($reason, $idx, Promise $aggregate) {
|
||||
$aggregate->reject($reason);
|
||||
}
|
||||
)->then(function () use (&$results) {
|
||||
ksort($results);
|
||||
return $results;
|
||||
});
|
||||
|
||||
if (true === $recursive) {
|
||||
$promise = $promise->then(function ($results) use ($recursive, &$promises) {
|
||||
foreach ($promises as $promise) {
|
||||
if (Is::pending($promise)) {
|
||||
return self::all($promises, $recursive);
|
||||
}
|
||||
}
|
||||
return $results;
|
||||
});
|
||||
}
|
||||
|
||||
return $promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate a competitive race between multiple promises or values (values
|
||||
* will become immediately fulfilled promises).
|
||||
*
|
||||
* When count amount of promises have been fulfilled, the returned promise
|
||||
* is fulfilled with an array that contains the fulfillment values of the
|
||||
* winners in order of resolution.
|
||||
*
|
||||
* This promise is rejected with a {@see AggregateException} if the number
|
||||
* of fulfilled promises is less than the desired $count.
|
||||
*
|
||||
* @param int $count Total number of promises.
|
||||
* @param mixed $promises Promises or values.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function some($count, $promises)
|
||||
{
|
||||
$results = [];
|
||||
$rejections = [];
|
||||
|
||||
return Each::of(
|
||||
$promises,
|
||||
function ($value, $idx, PromiseInterface $p) use (&$results, $count) {
|
||||
if (Is::settled($p)) {
|
||||
return;
|
||||
}
|
||||
$results[$idx] = $value;
|
||||
if (count($results) >= $count) {
|
||||
$p->resolve(null);
|
||||
}
|
||||
},
|
||||
function ($reason) use (&$rejections) {
|
||||
$rejections[] = $reason;
|
||||
}
|
||||
)->then(
|
||||
function () use (&$results, &$rejections, $count) {
|
||||
if (count($results) !== $count) {
|
||||
throw new AggregateException(
|
||||
'Not enough promises to fulfill count',
|
||||
$rejections
|
||||
);
|
||||
}
|
||||
ksort($results);
|
||||
return array_values($results);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like some(), with 1 as count. However, if the promise fulfills, the
|
||||
* fulfillment value is not an array of 1 but the value directly.
|
||||
*
|
||||
* @param mixed $promises Promises or values.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function any($promises)
|
||||
{
|
||||
return self::some(1, $promises)->then(function ($values) {
|
||||
return $values[0];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a promise that is fulfilled when all of the provided promises have
|
||||
* been fulfilled or rejected.
|
||||
*
|
||||
* The returned promise is fulfilled with an array of inspection state arrays.
|
||||
*
|
||||
* @see inspect for the inspection state array format.
|
||||
*
|
||||
* @param mixed $promises Promises or values.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*/
|
||||
public static function settle($promises)
|
||||
{
|
||||
$results = [];
|
||||
|
||||
return Each::of(
|
||||
$promises,
|
||||
function ($value, $idx) use (&$results) {
|
||||
$results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
|
||||
},
|
||||
function ($reason, $idx) use (&$results) {
|
||||
$results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
|
||||
}
|
||||
)->then(function () use (&$results) {
|
||||
ksort($results);
|
||||
return $results;
|
||||
});
|
||||
}
|
||||
}
|
||||
+80
-174
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Promise;
|
||||
|
||||
/**
|
||||
@@ -17,18 +18,12 @@ namespace GuzzleHttp\Promise;
|
||||
* @param TaskQueueInterface $assign Optionally specify a new queue instance.
|
||||
*
|
||||
* @return TaskQueueInterface
|
||||
*
|
||||
* @deprecated queue will be removed in guzzlehttp/promises:2.0. Use Utils::queue instead.
|
||||
*/
|
||||
function queue(TaskQueueInterface $assign = null)
|
||||
{
|
||||
static $queue;
|
||||
|
||||
if ($assign) {
|
||||
$queue = $assign;
|
||||
} elseif (!$queue) {
|
||||
$queue = new TaskQueue();
|
||||
}
|
||||
|
||||
return $queue;
|
||||
return Utils::queue($assign);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -38,22 +33,12 @@ function queue(TaskQueueInterface $assign = null)
|
||||
* @param callable $task Task function to run.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated task will be removed in guzzlehttp/promises:2.0. Use Utils::task instead.
|
||||
*/
|
||||
function task(callable $task)
|
||||
{
|
||||
$queue = queue();
|
||||
$promise = new Promise([$queue, 'run']);
|
||||
$queue->add(function () use ($task, $promise) {
|
||||
try {
|
||||
$promise->resolve($task());
|
||||
} catch (\Throwable $e) {
|
||||
$promise->reject($e);
|
||||
} catch (\Exception $e) {
|
||||
$promise->reject($e);
|
||||
}
|
||||
});
|
||||
|
||||
return $promise;
|
||||
return Utils::task($task);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -62,23 +47,12 @@ function task(callable $task)
|
||||
* @param mixed $value Promise or value.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated promise_for will be removed in guzzlehttp/promises:2.0. Use Create::promiseFor instead.
|
||||
*/
|
||||
function promise_for($value)
|
||||
{
|
||||
if ($value instanceof PromiseInterface) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
// Return a Guzzle promise that shadows the given promise.
|
||||
if (method_exists($value, 'then')) {
|
||||
$wfn = method_exists($value, 'wait') ? [$value, 'wait'] : null;
|
||||
$cfn = method_exists($value, 'cancel') ? [$value, 'cancel'] : null;
|
||||
$promise = new Promise($wfn, $cfn);
|
||||
$value->then([$promise, 'resolve'], [$promise, 'reject']);
|
||||
return $promise;
|
||||
}
|
||||
|
||||
return new FulfilledPromise($value);
|
||||
return Create::promiseFor($value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,14 +62,12 @@ function promise_for($value)
|
||||
* @param mixed $reason Promise or reason.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated rejection_for will be removed in guzzlehttp/promises:2.0. Use Create::rejectionFor instead.
|
||||
*/
|
||||
function rejection_for($reason)
|
||||
{
|
||||
if ($reason instanceof PromiseInterface) {
|
||||
return $reason;
|
||||
}
|
||||
|
||||
return new RejectedPromise($reason);
|
||||
return Create::rejectionFor($reason);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -104,12 +76,12 @@ function rejection_for($reason)
|
||||
* @param mixed $reason
|
||||
*
|
||||
* @return \Exception|\Throwable
|
||||
*
|
||||
* @deprecated exception_for will be removed in guzzlehttp/promises:2.0. Use Create::exceptionFor instead.
|
||||
*/
|
||||
function exception_for($reason)
|
||||
{
|
||||
return $reason instanceof \Exception || $reason instanceof \Throwable
|
||||
? $reason
|
||||
: new RejectionException($reason);
|
||||
return Create::exceptionFor($reason);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,16 +90,12 @@ function exception_for($reason)
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return \Iterator
|
||||
*
|
||||
* @deprecated iter_for will be removed in guzzlehttp/promises:2.0. Use Create::iterFor instead.
|
||||
*/
|
||||
function iter_for($value)
|
||||
{
|
||||
if ($value instanceof \Iterator) {
|
||||
return $value;
|
||||
} elseif (is_array($value)) {
|
||||
return new \ArrayIterator($value);
|
||||
} else {
|
||||
return new \ArrayIterator([$value]);
|
||||
}
|
||||
return Create::iterFor($value);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -143,21 +111,12 @@ function iter_for($value)
|
||||
* @param PromiseInterface $promise Promise or value.
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspect instead.
|
||||
*/
|
||||
function inspect(PromiseInterface $promise)
|
||||
{
|
||||
try {
|
||||
return [
|
||||
'state' => PromiseInterface::FULFILLED,
|
||||
'value' => $promise->wait()
|
||||
];
|
||||
} catch (RejectionException $e) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $e->getReason()];
|
||||
} catch (\Throwable $e) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
|
||||
} catch (\Exception $e) {
|
||||
return ['state' => PromiseInterface::REJECTED, 'reason' => $e];
|
||||
}
|
||||
return Utils::inspect($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,19 +125,17 @@ function inspect(PromiseInterface $promise)
|
||||
*
|
||||
* Returns an array of inspection state arrays.
|
||||
*
|
||||
* @see inspect for the inspection state array format.
|
||||
*
|
||||
* @param PromiseInterface[] $promises Traversable of promises to wait upon.
|
||||
*
|
||||
* @return array
|
||||
* @see GuzzleHttp\Promise\inspect for the inspection state array format.
|
||||
*
|
||||
* @deprecated inspect will be removed in guzzlehttp/promises:2.0. Use Utils::inspectAll instead.
|
||||
*/
|
||||
function inspect_all($promises)
|
||||
{
|
||||
$results = [];
|
||||
foreach ($promises as $key => $promise) {
|
||||
$results[$key] = inspect($promise);
|
||||
}
|
||||
|
||||
return $results;
|
||||
return Utils::inspectAll($promises);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,20 +145,18 @@ function inspect_all($promises)
|
||||
* the promises were provided). An exception is thrown if any of the promises
|
||||
* are rejected.
|
||||
*
|
||||
* @param mixed $promises Iterable of PromiseInterface objects to wait on.
|
||||
* @param iterable<PromiseInterface> $promises Iterable of PromiseInterface objects to wait on.
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @throws \Exception on error
|
||||
* @throws \Throwable on error in PHP >=7
|
||||
*
|
||||
* @deprecated unwrap will be removed in guzzlehttp/promises:2.0. Use Utils::unwrap instead.
|
||||
*/
|
||||
function unwrap($promises)
|
||||
{
|
||||
$results = [];
|
||||
foreach ($promises as $key => $promise) {
|
||||
$results[$key] = $promise->wait();
|
||||
}
|
||||
|
||||
return $results;
|
||||
return Utils::unwrap($promises);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -212,25 +167,16 @@ function unwrap($promises)
|
||||
* respective positions to the original array. If any promise in the array
|
||||
* rejects, the returned promise is rejected with the rejection reason.
|
||||
*
|
||||
* @param mixed $promises Promises or values.
|
||||
* @param mixed $promises Promises or values.
|
||||
* @param bool $recursive If true, resolves new promises that might have been added to the stack during its own resolution.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated all will be removed in guzzlehttp/promises:2.0. Use Utils::all instead.
|
||||
*/
|
||||
function all($promises)
|
||||
function all($promises, $recursive = false)
|
||||
{
|
||||
$results = [];
|
||||
return each(
|
||||
$promises,
|
||||
function ($value, $idx) use (&$results) {
|
||||
$results[$idx] = $value;
|
||||
},
|
||||
function ($reason, $idx, Promise $aggregate) {
|
||||
$aggregate->reject($reason);
|
||||
}
|
||||
)->then(function () use (&$results) {
|
||||
ksort($results);
|
||||
return $results;
|
||||
});
|
||||
return Utils::all($promises, $recursive);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -241,45 +187,19 @@ function all($promises)
|
||||
* fulfilled with an array that contains the fulfillment values of the winners
|
||||
* in order of resolution.
|
||||
*
|
||||
* This prommise is rejected with a {@see GuzzleHttp\Promise\AggregateException}
|
||||
* if the number of fulfilled promises is less than the desired $count.
|
||||
* This promise is rejected with a {@see AggregateException} if the number of
|
||||
* fulfilled promises is less than the desired $count.
|
||||
*
|
||||
* @param int $count Total number of promises.
|
||||
* @param mixed $promises Promises or values.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated some will be removed in guzzlehttp/promises:2.0. Use Utils::some instead.
|
||||
*/
|
||||
function some($count, $promises)
|
||||
{
|
||||
$results = [];
|
||||
$rejections = [];
|
||||
|
||||
return each(
|
||||
$promises,
|
||||
function ($value, $idx, PromiseInterface $p) use (&$results, $count) {
|
||||
if ($p->getState() !== PromiseInterface::PENDING) {
|
||||
return;
|
||||
}
|
||||
$results[$idx] = $value;
|
||||
if (count($results) >= $count) {
|
||||
$p->resolve(null);
|
||||
}
|
||||
},
|
||||
function ($reason) use (&$rejections) {
|
||||
$rejections[] = $reason;
|
||||
}
|
||||
)->then(
|
||||
function () use (&$results, &$rejections, $count) {
|
||||
if (count($results) !== $count) {
|
||||
throw new AggregateException(
|
||||
'Not enough promises to fulfill count',
|
||||
$rejections
|
||||
);
|
||||
}
|
||||
ksort($results);
|
||||
return array_values($results);
|
||||
}
|
||||
);
|
||||
return Utils::some($count, $promises);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -289,10 +209,12 @@ function some($count, $promises)
|
||||
* @param mixed $promises Promises or values.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated any will be removed in guzzlehttp/promises:2.0. Use Utils::any instead.
|
||||
*/
|
||||
function any($promises)
|
||||
{
|
||||
return some(1, $promises)->then(function ($values) { return $values[0]; });
|
||||
return Utils::any($promises);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -301,27 +223,17 @@ function any($promises)
|
||||
*
|
||||
* The returned promise is fulfilled with an array of inspection state arrays.
|
||||
*
|
||||
* @see inspect for the inspection state array format.
|
||||
*
|
||||
* @param mixed $promises Promises or values.
|
||||
*
|
||||
* @return PromiseInterface
|
||||
* @see GuzzleHttp\Promise\inspect for the inspection state array format.
|
||||
*
|
||||
* @deprecated settle will be removed in guzzlehttp/promises:2.0. Use Utils::settle instead.
|
||||
*/
|
||||
function settle($promises)
|
||||
{
|
||||
$results = [];
|
||||
|
||||
return each(
|
||||
$promises,
|
||||
function ($value, $idx) use (&$results) {
|
||||
$results[$idx] = ['state' => PromiseInterface::FULFILLED, 'value' => $value];
|
||||
},
|
||||
function ($reason, $idx) use (&$results) {
|
||||
$results[$idx] = ['state' => PromiseInterface::REJECTED, 'reason' => $reason];
|
||||
}
|
||||
)->then(function () use (&$results) {
|
||||
ksort($results);
|
||||
return $results;
|
||||
});
|
||||
return Utils::settle($promises);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -329,29 +241,28 @@ function settle($promises)
|
||||
* fulfilled with a null value when the iterator has been consumed or the
|
||||
* aggregate promise has been fulfilled or rejected.
|
||||
*
|
||||
* $onFulfilled is a function that accepts the fulfilled value, iterator
|
||||
* index, and the aggregate promise. The callback can invoke any necessary side
|
||||
* effects and choose to resolve or reject the aggregate promise if needed.
|
||||
* $onFulfilled is a function that accepts the fulfilled value, iterator index,
|
||||
* and the aggregate promise. The callback can invoke any necessary side
|
||||
* effects and choose to resolve or reject the aggregate if needed.
|
||||
*
|
||||
* $onRejected is a function that accepts the rejection reason, iterator
|
||||
* index, and the aggregate promise. The callback can invoke any necessary side
|
||||
* effects and choose to resolve or reject the aggregate promise if needed.
|
||||
* $onRejected is a function that accepts the rejection reason, iterator index,
|
||||
* and the aggregate promise. The callback can invoke any necessary side
|
||||
* effects and choose to resolve or reject the aggregate if needed.
|
||||
*
|
||||
* @param mixed $iterable Iterator or array to iterate over.
|
||||
* @param callable $onFulfilled
|
||||
* @param callable $onRejected
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated each will be removed in guzzlehttp/promises:2.0. Use Each::of instead.
|
||||
*/
|
||||
function each(
|
||||
$iterable,
|
||||
callable $onFulfilled = null,
|
||||
callable $onRejected = null
|
||||
) {
|
||||
return (new EachPromise($iterable, [
|
||||
'fulfilled' => $onFulfilled,
|
||||
'rejected' => $onRejected
|
||||
]))->promise();
|
||||
return Each::of($iterable, $onFulfilled, $onRejected);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -368,6 +279,8 @@ function each(
|
||||
* @param callable $onRejected
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated each_limit will be removed in guzzlehttp/promises:2.0. Use Each::ofLimit instead.
|
||||
*/
|
||||
function each_limit(
|
||||
$iterable,
|
||||
@@ -375,11 +288,7 @@ function each_limit(
|
||||
callable $onFulfilled = null,
|
||||
callable $onRejected = null
|
||||
) {
|
||||
return (new EachPromise($iterable, [
|
||||
'fulfilled' => $onFulfilled,
|
||||
'rejected' => $onRejected,
|
||||
'concurrency' => $concurrency
|
||||
]))->promise();
|
||||
return Each::ofLimit($iterable, $concurrency, $onFulfilled, $onRejected);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -392,66 +301,63 @@ function each_limit(
|
||||
* @param callable $onFulfilled
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated each_limit_all will be removed in guzzlehttp/promises:2.0. Use Each::ofLimitAll instead.
|
||||
*/
|
||||
function each_limit_all(
|
||||
$iterable,
|
||||
$concurrency,
|
||||
callable $onFulfilled = null
|
||||
) {
|
||||
return each_limit(
|
||||
$iterable,
|
||||
$concurrency,
|
||||
$onFulfilled,
|
||||
function ($reason, $idx, PromiseInterface $aggregate) {
|
||||
$aggregate->reject($reason);
|
||||
}
|
||||
);
|
||||
return Each::ofLimitAll($iterable, $concurrency, $onFulfilled);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled.
|
||||
*
|
||||
* @param PromiseInterface $promise
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @deprecated is_fulfilled will be removed in guzzlehttp/promises:2.0. Use Is::fulfilled instead.
|
||||
*/
|
||||
function is_fulfilled(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::FULFILLED;
|
||||
return Is::fulfilled($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is rejected.
|
||||
*
|
||||
* @param PromiseInterface $promise
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @deprecated is_rejected will be removed in guzzlehttp/promises:2.0. Use Is::rejected instead.
|
||||
*/
|
||||
function is_rejected(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() === PromiseInterface::REJECTED;
|
||||
return Is::rejected($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if a promise is fulfilled or rejected.
|
||||
*
|
||||
* @param PromiseInterface $promise
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @deprecated is_settled will be removed in guzzlehttp/promises:2.0. Use Is::settled instead.
|
||||
*/
|
||||
function is_settled(PromiseInterface $promise)
|
||||
{
|
||||
return $promise->getState() !== PromiseInterface::PENDING;
|
||||
return Is::settled($promise);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new coroutine.
|
||||
*
|
||||
* @see Coroutine
|
||||
*
|
||||
* @param callable $generatorFn
|
||||
*
|
||||
* @return PromiseInterface
|
||||
*
|
||||
* @deprecated coroutine will be removed in guzzlehttp/promises:2.0. Use Coroutine::of instead.
|
||||
*/
|
||||
function coroutine(callable $generatorFn)
|
||||
{
|
||||
return new Coroutine($generatorFn);
|
||||
return Coroutine::of($generatorFn);
|
||||
}
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
name: BC Check
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
roave-bc-check:
|
||||
name: Roave BC Check
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Roave BC Check
|
||||
uses: docker://nyholm/roave-bc-check-ga
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
max-parallel: 10
|
||||
matrix:
|
||||
php: ['5.6', '7.0', '7.1', '7.2', '7.3', '7.4']
|
||||
|
||||
steps:
|
||||
- name: Set up PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: ${{ matrix.php }}
|
||||
coverage: 'none'
|
||||
extensions: mbstring
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Install dependencies
|
||||
run: composer update --no-interaction --no-progress --prefer-dist
|
||||
|
||||
- name: Run tests
|
||||
run: make test
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Integration
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
max-parallel: 10
|
||||
matrix:
|
||||
php: ['7.2', '7.3', '7.4', '8.0']
|
||||
|
||||
steps:
|
||||
- name: Set up PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: ${{ matrix.php }}
|
||||
coverage: none
|
||||
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Download dependencies
|
||||
uses: ramsey/composer-install@v1
|
||||
with:
|
||||
composer-options: --no-interaction --prefer-dist --optimize-autoloader
|
||||
|
||||
- name: Start server
|
||||
run: php -S 127.0.0.1:10002 tests/Integration/server.php &
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
TEST_SERVER: 127.0.0.1:10002
|
||||
run: ./vendor/bin/phpunit --testsuite Integration
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Static analysis
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
php-cs-fixer:
|
||||
name: PHP-CS-Fixer
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Setup PHP
|
||||
uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '7.4'
|
||||
coverage: none
|
||||
extensions: mbstring
|
||||
|
||||
- name: Download dependencies
|
||||
run: composer update --no-interaction --no-progress
|
||||
|
||||
- name: Download PHP CS Fixer
|
||||
run: composer require "friendsofphp/php-cs-fixer:2.18.4"
|
||||
|
||||
- name: Execute PHP CS Fixer
|
||||
run: vendor/bin/php-cs-fixer fix --diff-format udiff --dry-run
|
||||
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
$config = PhpCsFixer\Config::create()
|
||||
->setRiskyAllowed(true)
|
||||
->setRules([
|
||||
'@PSR2' => true,
|
||||
'array_syntax' => ['syntax' => 'short'],
|
||||
'concat_space' => ['spacing' => 'one'],
|
||||
'declare_strict_types' => false,
|
||||
'final_static_access' => true,
|
||||
'fully_qualified_strict_types' => true,
|
||||
'header_comment' => false,
|
||||
'is_null' => ['use_yoda_style' => true],
|
||||
'list_syntax' => ['syntax' => 'long'],
|
||||
'lowercase_cast' => true,
|
||||
'magic_method_casing' => true,
|
||||
'modernize_types_casting' => true,
|
||||
'multiline_comment_opening_closing' => true,
|
||||
'no_alias_functions' => true,
|
||||
'no_alternative_syntax' => true,
|
||||
'no_blank_lines_after_phpdoc' => true,
|
||||
'no_empty_comment' => true,
|
||||
'no_empty_phpdoc' => true,
|
||||
'no_empty_statement' => true,
|
||||
'no_extra_blank_lines' => true,
|
||||
'no_leading_import_slash' => true,
|
||||
'no_trailing_comma_in_singleline_array' => true,
|
||||
'no_unset_cast' => true,
|
||||
'no_unused_imports' => true,
|
||||
'no_whitespace_in_blank_line' => true,
|
||||
'ordered_imports' => true,
|
||||
'php_unit_ordered_covers' => true,
|
||||
'php_unit_test_annotation' => ['style' => 'prefix'],
|
||||
'php_unit_test_case_static_method_calls' => ['call_type' => 'self'],
|
||||
'phpdoc_align' => ['align' => 'vertical'],
|
||||
'phpdoc_no_useless_inheritdoc' => true,
|
||||
'phpdoc_scalar' => true,
|
||||
'phpdoc_separation' => true,
|
||||
'phpdoc_single_line_var_spacing' => true,
|
||||
'phpdoc_trim' => true,
|
||||
'phpdoc_trim_consecutive_blank_line_separation' => true,
|
||||
'phpdoc_types' => true,
|
||||
'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'],
|
||||
'phpdoc_var_without_name' => true,
|
||||
'single_trait_insert_per_statement' => true,
|
||||
'standardize_not_equals' => true,
|
||||
])
|
||||
->setFinder(
|
||||
PhpCsFixer\Finder::create()
|
||||
->in(__DIR__.'/src')
|
||||
->in(__DIR__.'/tests')
|
||||
->name('*.php')
|
||||
)
|
||||
;
|
||||
|
||||
return $config;
|
||||
Vendored
+51
-3
@@ -7,10 +7,59 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
|
||||
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
|
||||
|
||||
|
||||
## [Unreleased]
|
||||
## Unreleased
|
||||
|
||||
## 1.8.2 - 2021-04-26
|
||||
|
||||
### Fixed
|
||||
|
||||
- Handle possibly unset `url` in `stream_get_meta_data`
|
||||
|
||||
## 1.8.1 - 2021-03-21
|
||||
|
||||
### Fixed
|
||||
|
||||
- Issue parsing IPv6 URLs
|
||||
- Issue modifying ServerRequest lost all its attributes
|
||||
|
||||
## 1.8.0 - 2021-03-21
|
||||
|
||||
### Added
|
||||
|
||||
- Locale independent URL parsing
|
||||
- Most classes got a `@final` annotation to prepare for 2.0
|
||||
|
||||
### Fixed
|
||||
|
||||
- Issue when creating stream from `php://input` and curl-ext is not installed
|
||||
- Broken `Utils::tryFopen()` on PHP 8
|
||||
|
||||
## 1.7.0 - 2020-09-30
|
||||
|
||||
### Added
|
||||
|
||||
- Replaced functions by static methods
|
||||
|
||||
### Fixed
|
||||
|
||||
- Converting a non-seekable stream to a string
|
||||
- Handle multiple Set-Cookie correctly
|
||||
- Ignore array keys in header values when merging
|
||||
- Allow multibyte characters to be parsed in `Message:bodySummary()`
|
||||
|
||||
### Changed
|
||||
|
||||
- Restored partial HHVM 3 support
|
||||
|
||||
|
||||
## [1.6.0]
|
||||
## [1.6.1] - 2019-07-02
|
||||
|
||||
### Fixed
|
||||
|
||||
- Accept null and bool header values again
|
||||
|
||||
|
||||
## [1.6.0] - 2019-06-30
|
||||
|
||||
### Added
|
||||
|
||||
@@ -229,7 +278,6 @@ Currently unsupported:
|
||||
|
||||
|
||||
|
||||
[Unreleased]: https://github.com/guzzle/psr7/compare/1.6.0...HEAD
|
||||
[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0
|
||||
[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2
|
||||
[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1
|
||||
|
||||
Vendored
+212
-148
@@ -23,11 +23,11 @@ Reads from multiple streams, one after the other.
|
||||
```php
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
$a = Psr7\stream_for('abc, ');
|
||||
$b = Psr7\stream_for('123.');
|
||||
$a = Psr7\Utils::streamFor('abc, ');
|
||||
$b = Psr7\Utils::streamFor('123.');
|
||||
$composed = new Psr7\AppendStream([$a, $b]);
|
||||
|
||||
$composed->addStream(Psr7\stream_for(' Above all listen to me'));
|
||||
$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me'));
|
||||
|
||||
echo $composed; // abc, 123. Above all listen to me.
|
||||
```
|
||||
@@ -65,7 +65,7 @@ then on disk.
|
||||
```php
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
$original = Psr7\stream_for(fopen('http://www.google.com', 'r'));
|
||||
$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r'));
|
||||
$stream = new Psr7\CachingStream($original);
|
||||
|
||||
$stream->read(1024);
|
||||
@@ -89,7 +89,7 @@ stream becomes too full.
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
// Create an empty stream
|
||||
$stream = Psr7\stream_for();
|
||||
$stream = Psr7\Utils::streamFor();
|
||||
|
||||
// Start dropping data when the stream has more than 10 bytes
|
||||
$dropping = new Psr7\DroppingStream($stream, 10);
|
||||
@@ -112,7 +112,7 @@ to create a concrete class for a simple extension point.
|
||||
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
$stream = Psr7\stream_for('hi');
|
||||
$stream = Psr7\Utils::streamFor('hi');
|
||||
$fnStream = Psr7\FnStream::decorate($stream, [
|
||||
'rewind' => function () use ($stream) {
|
||||
echo 'About to rewind - ';
|
||||
@@ -167,7 +167,7 @@ chunks (e.g. Amazon S3's multipart upload API).
|
||||
```php
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
$original = Psr7\stream_for(fopen('/tmp/test.txt', 'r+'));
|
||||
$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+'));
|
||||
echo $original->getSize();
|
||||
// >>> 1048576
|
||||
|
||||
@@ -197,7 +197,7 @@ NoSeekStream wraps a stream and does not allow seeking.
|
||||
```php
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
$original = Psr7\stream_for('foo');
|
||||
$original = Psr7\Utils::streamFor('foo');
|
||||
$noSeek = new Psr7\NoSeekStream($original);
|
||||
|
||||
echo $noSeek->read(3);
|
||||
@@ -271,7 +271,7 @@ This decorator could be added to any existing stream and used like so:
|
||||
```php
|
||||
use GuzzleHttp\Psr7;
|
||||
|
||||
$original = Psr7\stream_for('foo');
|
||||
$original = Psr7\Utils::streamFor('foo');
|
||||
|
||||
$eofStream = new EofCallbackStream($original, function () {
|
||||
echo 'EOF!';
|
||||
@@ -297,53 +297,189 @@ stream from a PSR-7 stream.
|
||||
```php
|
||||
use GuzzleHttp\Psr7\StreamWrapper;
|
||||
|
||||
$stream = GuzzleHttp\Psr7\stream_for('hello!');
|
||||
$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!');
|
||||
$resource = StreamWrapper::getResource($stream);
|
||||
echo fread($resource, 6); // outputs hello!
|
||||
```
|
||||
|
||||
|
||||
# Function API
|
||||
# Static API
|
||||
|
||||
There are various functions available under the `GuzzleHttp\Psr7` namespace.
|
||||
There are various static methods available under the `GuzzleHttp\Psr7` namespace.
|
||||
|
||||
|
||||
## `function str`
|
||||
## `GuzzleHttp\Psr7\Message::toString`
|
||||
|
||||
`function str(MessageInterface $message)`
|
||||
`public static function toString(MessageInterface $message): string`
|
||||
|
||||
Returns the string representation of an HTTP message.
|
||||
|
||||
```php
|
||||
$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com');
|
||||
echo GuzzleHttp\Psr7\str($request);
|
||||
echo GuzzleHttp\Psr7\Message::toString($request);
|
||||
```
|
||||
|
||||
|
||||
## `function uri_for`
|
||||
## `GuzzleHttp\Psr7\Message::bodySummary`
|
||||
|
||||
`function uri_for($uri)`
|
||||
`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null`
|
||||
|
||||
This function accepts a string or `Psr\Http\Message\UriInterface` and returns a
|
||||
UriInterface for the given value. If the value is already a `UriInterface`, it
|
||||
is returned as-is.
|
||||
Get a short summary of the message body.
|
||||
|
||||
```php
|
||||
$uri = GuzzleHttp\Psr7\uri_for('http://example.com');
|
||||
assert($uri === GuzzleHttp\Psr7\uri_for($uri));
|
||||
```
|
||||
Will return `null` if the response is not printable.
|
||||
|
||||
|
||||
## `function stream_for`
|
||||
## `GuzzleHttp\Psr7\Message::rewindBody`
|
||||
|
||||
`function stream_for($resource = '', array $options = [])`
|
||||
`public static function rewindBody(MessageInterface $message): void`
|
||||
|
||||
Attempts to rewind a message body and throws an exception on failure.
|
||||
|
||||
The body of the message will only be rewound if a call to `tell()`
|
||||
returns a value other than `0`.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Message::parseMessage`
|
||||
|
||||
`public static function parseMessage(string $message): array`
|
||||
|
||||
Parses an HTTP message into an associative array.
|
||||
|
||||
The array contains the "start-line" key containing the start line of
|
||||
the message, "headers" key containing an associative array of header
|
||||
array values, and a "body" key containing the body of the message.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Message::parseRequestUri`
|
||||
|
||||
`public static function parseRequestUri(string $path, array $headers): string`
|
||||
|
||||
Constructs a URI for an HTTP request message.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Message::parseRequest`
|
||||
|
||||
`public static function parseRequest(string $message): Request`
|
||||
|
||||
Parses a request message string into a request object.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Message::parseResponse`
|
||||
|
||||
`public static function parseResponse(string $message): Response`
|
||||
|
||||
Parses a response message string into a response object.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Header::parse`
|
||||
|
||||
`public static function parse(string|array $header): array`
|
||||
|
||||
Parse an array of header values containing ";" separated data into an
|
||||
array of associative arrays representing the header key value pair data
|
||||
of the header. When a parameter does not contain a value, but just
|
||||
contains a key, this function will inject a key with a '' string value.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Header::normalize`
|
||||
|
||||
`public static function normalize(string|array $header): array`
|
||||
|
||||
Converts an array of header values that may contain comma separated
|
||||
headers into an array of headers with no comma separated values.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Query::parse`
|
||||
|
||||
`public static function parse(string $str, int|bool $urlEncoding = true): array`
|
||||
|
||||
Parse a query string into an associative array.
|
||||
|
||||
If multiple values are found for the same key, the value of that key
|
||||
value pair will become an array. This function does not parse nested
|
||||
PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
|
||||
will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Query::build`
|
||||
|
||||
`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string`
|
||||
|
||||
Build a query string from an array of key value pairs.
|
||||
|
||||
This function can use the return value of `parse()` to build a query
|
||||
string. This function does not modify the provided keys when an array is
|
||||
encountered (like `http_build_query()` would).
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::caselessRemove`
|
||||
|
||||
`public static function caselessRemove(iterable<string> $keys, $keys, array $data): array`
|
||||
|
||||
Remove the items given by the keys, case insensitively from the data.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::copyToStream`
|
||||
|
||||
`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void`
|
||||
|
||||
Copy the contents of a stream into another stream until the given number
|
||||
of bytes have been read.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::copyToString`
|
||||
|
||||
`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string`
|
||||
|
||||
Copy the contents of a stream into a string until the given number of
|
||||
bytes have been read.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::hash`
|
||||
|
||||
`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string`
|
||||
|
||||
Calculate a hash of a stream.
|
||||
|
||||
This method reads the entire stream to calculate a rolling hash, based on
|
||||
PHP's `hash_init` functions.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::modifyRequest`
|
||||
|
||||
`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface`
|
||||
|
||||
Clone and modify a request with the given changes.
|
||||
|
||||
This method is useful for reducing the number of clones needed to mutate
|
||||
a message.
|
||||
|
||||
- method: (string) Changes the HTTP method.
|
||||
- set_headers: (array) Sets the given headers.
|
||||
- remove_headers: (array) Remove the given headers.
|
||||
- body: (mixed) Sets the given body.
|
||||
- uri: (UriInterface) Set the URI.
|
||||
- query: (string) Set the query string value of the URI.
|
||||
- version: (string) Set the protocol version.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::readLine`
|
||||
|
||||
`public static function readLine(StreamInterface $stream, int $maxLength = null): string`
|
||||
|
||||
Read a line from the stream up to the maximum allowed buffer length.
|
||||
|
||||
|
||||
## `GuzzleHttp\Psr7\Utils::streamFor`
|
||||
|
||||
`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface`
|
||||
|
||||
Create a new stream based on the input type.
|
||||
|
||||
Options is an associative array that can contain the following keys:
|
||||
|
||||
* - metadata: Array of custom metadata.
|
||||
* - size: Size of the stream.
|
||||
- metadata: Array of custom metadata.
|
||||
- size: Size of the stream.
|
||||
|
||||
This method accepts the following `$resource` types:
|
||||
|
||||
@@ -369,8 +505,8 @@ This method accepts the following `$resource` types:
|
||||
buffered and used in subsequent reads.
|
||||
|
||||
```php
|
||||
$stream = GuzzleHttp\Psr7\stream_for('foo');
|
||||
$stream = GuzzleHttp\Psr7\stream_for(fopen('/path/to/file', 'r'));
|
||||
$stream = GuzzleHttp\Psr7\Utils::streamFor('foo');
|
||||
$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r'));
|
||||
|
||||
$generator = function ($bytes) {
|
||||
for ($i = 0; $i < $bytes; $i++) {
|
||||
@@ -378,147 +514,75 @@ $generator = function ($bytes) {
|
||||
}
|
||||
}
|
||||
|
||||
$stream = GuzzleHttp\Psr7\stream_for($generator(100));
|
||||
$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100));
|
||||
```
|
||||
|
||||
|
||||
## `function parse_header`
|
||||
## `GuzzleHttp\Psr7\Utils::tryFopen`
|
||||
|
||||
`function parse_header($header)`
|
||||
|
||||
Parse an array of header values containing ";" separated data into an array of
|
||||
associative arrays representing the header key value pair data of the header.
|
||||
When a parameter does not contain a value, but just contains a key, this
|
||||
function will inject a key with a '' string value.
|
||||
|
||||
|
||||
## `function normalize_header`
|
||||
|
||||
`function normalize_header($header)`
|
||||
|
||||
Converts an array of header values that may contain comma separated headers
|
||||
into an array of headers with no comma separated values.
|
||||
|
||||
|
||||
## `function modify_request`
|
||||
|
||||
`function modify_request(RequestInterface $request, array $changes)`
|
||||
|
||||
Clone and modify a request with the given changes. This method is useful for
|
||||
reducing the number of clones needed to mutate a message.
|
||||
|
||||
The changes can be one of:
|
||||
|
||||
- method: (string) Changes the HTTP method.
|
||||
- set_headers: (array) Sets the given headers.
|
||||
- remove_headers: (array) Remove the given headers.
|
||||
- body: (mixed) Sets the given body.
|
||||
- uri: (UriInterface) Set the URI.
|
||||
- query: (string) Set the query string value of the URI.
|
||||
- version: (string) Set the protocol version.
|
||||
|
||||
|
||||
## `function rewind_body`
|
||||
|
||||
`function rewind_body(MessageInterface $message)`
|
||||
|
||||
Attempts to rewind a message body and throws an exception on failure. The body
|
||||
of the message will only be rewound if a call to `tell()` returns a value other
|
||||
than `0`.
|
||||
|
||||
|
||||
## `function try_fopen`
|
||||
|
||||
`function try_fopen($filename, $mode)`
|
||||
`public static function tryFopen(string $filename, string $mode): resource`
|
||||
|
||||
Safely opens a PHP stream resource using a filename.
|
||||
|
||||
When fopen fails, PHP normally raises a warning. This function adds an error
|
||||
handler that checks for errors and throws an exception instead.
|
||||
When fopen fails, PHP normally raises a warning. This function adds an
|
||||
error handler that checks for errors and throws an exception instead.
|
||||
|
||||
|
||||
## `function copy_to_string`
|
||||
## `GuzzleHttp\Psr7\Utils::uriFor`
|
||||
|
||||
`function copy_to_string(StreamInterface $stream, $maxLen = -1)`
|
||||
`public static function uriFor(string|UriInterface $uri): UriInterface`
|
||||
|
||||
Copy the contents of a stream into a string until the given number of bytes
|
||||
have been read.
|
||||
Returns a UriInterface for the given value.
|
||||
|
||||
This function accepts a string or UriInterface and returns a
|
||||
UriInterface for the given value. If the value is already a
|
||||
UriInterface, it is returned as-is.
|
||||
|
||||
|
||||
## `function copy_to_stream`
|
||||
## `GuzzleHttp\Psr7\MimeType::fromFilename`
|
||||
|
||||
`function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)`
|
||||
|
||||
Copy the contents of a stream into another stream until the given number of
|
||||
bytes have been read.
|
||||
|
||||
|
||||
## `function hash`
|
||||
|
||||
`function hash(StreamInterface $stream, $algo, $rawOutput = false)`
|
||||
|
||||
Calculate a hash of a Stream. This method reads the entire stream to calculate
|
||||
a rolling hash (based on PHP's hash_init functions).
|
||||
|
||||
|
||||
## `function readline`
|
||||
|
||||
`function readline(StreamInterface $stream, $maxLength = null)`
|
||||
|
||||
Read a line from the stream up to the maximum allowed buffer length.
|
||||
|
||||
|
||||
## `function parse_request`
|
||||
|
||||
`function parse_request($message)`
|
||||
|
||||
Parses a request message string into a request object.
|
||||
|
||||
|
||||
## `function parse_response`
|
||||
|
||||
`function parse_response($message)`
|
||||
|
||||
Parses a response message string into a response object.
|
||||
|
||||
|
||||
## `function parse_query`
|
||||
|
||||
`function parse_query($str, $urlEncoding = true)`
|
||||
|
||||
Parse a query string into an associative array.
|
||||
|
||||
If multiple values are found for the same key, the value of that key value pair
|
||||
will become an array. This function does not parse nested PHP style arrays into
|
||||
an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed into
|
||||
`['foo[a]' => '1', 'foo[b]' => '2']`).
|
||||
|
||||
|
||||
## `function build_query`
|
||||
|
||||
`function build_query(array $params, $encoding = PHP_QUERY_RFC3986)`
|
||||
|
||||
Build a query string from an array of key value pairs.
|
||||
|
||||
This function can use the return value of parse_query() to build a query string.
|
||||
This function does not modify the provided keys when an array is encountered
|
||||
(like http_build_query would).
|
||||
|
||||
|
||||
## `function mimetype_from_filename`
|
||||
|
||||
`function mimetype_from_filename($filename)`
|
||||
`public static function fromFilename(string $filename): string|null`
|
||||
|
||||
Determines the mimetype of a file by looking at its extension.
|
||||
|
||||
|
||||
## `function mimetype_from_extension`
|
||||
## `GuzzleHttp\Psr7\MimeType::fromExtension`
|
||||
|
||||
`function mimetype_from_extension($extension)`
|
||||
`public static function fromExtension(string $extension): string|null`
|
||||
|
||||
Maps a file extensions to a mimetype.
|
||||
|
||||
|
||||
## Upgrading from Function API
|
||||
|
||||
The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API will be removed in 2.0.0. A migration table has been provided here for your convenience:
|
||||
|
||||
| Original Function | Replacement Method |
|
||||
|----------------|----------------|
|
||||
| `str` | `Message::toString` |
|
||||
| `uri_for` | `Utils::uriFor` |
|
||||
| `stream_for` | `Utils::streamFor` |
|
||||
| `parse_header` | `Header::parse` |
|
||||
| `normalize_header` | `Header::normalize` |
|
||||
| `modify_request` | `Utils::modifyRequest` |
|
||||
| `rewind_body` | `Message::rewindBody` |
|
||||
| `try_fopen` | `Utils::tryFopen` |
|
||||
| `copy_to_string` | `Utils::copyToString` |
|
||||
| `copy_to_stream` | `Utils::copyToStream` |
|
||||
| `hash` | `Utils::hash` |
|
||||
| `readline` | `Utils::readLine` |
|
||||
| `parse_request` | `Message::parseRequest` |
|
||||
| `parse_response` | `Message::parseResponse` |
|
||||
| `parse_query` | `Query::parse` |
|
||||
| `build_query` | `Query::build` |
|
||||
| `mimetype_from_filename` | `MimeType::fromFilename` |
|
||||
| `mimetype_from_extension` | `MimeType::fromExtension` |
|
||||
| `_parse_message` | `Message::parseMessage` |
|
||||
| `_parse_request_uri` | `Message::parseRequestUri` |
|
||||
| `get_message_body_summary` | `Message::bodySummary` |
|
||||
| `_caseless_remove` | `Utils::caselessRemove` |
|
||||
|
||||
|
||||
# Additional URI Methods
|
||||
|
||||
Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class,
|
||||
|
||||
Vendored
+3
-3
@@ -21,14 +21,14 @@
|
||||
"ralouphie/getallheaders": "^2.0.5 || ^3.0.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8",
|
||||
"phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10",
|
||||
"ext-zlib": "*"
|
||||
},
|
||||
"provide": {
|
||||
"psr/http-message-implementation": "1.0"
|
||||
},
|
||||
"suggest": {
|
||||
"zendframework/zend-httphandlerrunner": "Emit PSR-7 responses"
|
||||
"laminas/laminas-httphandlerrunner": "Emit PSR-7 responses"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
@@ -43,7 +43,7 @@
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "1.6-dev"
|
||||
"dev-master": "1.7-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+6
-1
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -7,6 +8,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
* Reads from multiple streams, one after the other.
|
||||
*
|
||||
* This is a read-only stream decorator.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class AppendStream implements StreamInterface
|
||||
{
|
||||
@@ -61,7 +64,7 @@ class AppendStream implements StreamInterface
|
||||
|
||||
public function getContents()
|
||||
{
|
||||
return copy_to_string($this);
|
||||
return Utils::copyToString($this);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,6 +101,8 @@ class AppendStream implements StreamInterface
|
||||
}
|
||||
|
||||
$this->streams = [];
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function tell()
|
||||
|
||||
+5
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -10,6 +11,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
* This stream returns a "hwm" metadata value that tells upstream consumers
|
||||
* what the configured high water mark of the stream is, or the maximum
|
||||
* preferred size of the buffer.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class BufferStream implements StreamInterface
|
||||
{
|
||||
@@ -49,6 +52,8 @@ class BufferStream implements StreamInterface
|
||||
public function detach()
|
||||
{
|
||||
$this->close();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getSize()
|
||||
|
||||
+6
-3
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -6,6 +7,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
/**
|
||||
* Stream decorator that can cache previously read bytes from a sequentially
|
||||
* read stream.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class CachingStream implements StreamInterface
|
||||
{
|
||||
@@ -20,7 +23,7 @@ class CachingStream implements StreamInterface
|
||||
/**
|
||||
* We will treat the buffer object as the body of the stream
|
||||
*
|
||||
* @param StreamInterface $stream Stream to cache
|
||||
* @param StreamInterface $stream Stream to cache. The cursor is assumed to be at the beginning of the stream.
|
||||
* @param StreamInterface $target Optionally specify where data is cached
|
||||
*/
|
||||
public function __construct(
|
||||
@@ -28,7 +31,7 @@ class CachingStream implements StreamInterface
|
||||
StreamInterface $target = null
|
||||
) {
|
||||
$this->remoteStream = $stream;
|
||||
$this->stream = $target ?: new Stream(fopen('php://temp', 'r+'));
|
||||
$this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+'));
|
||||
}
|
||||
|
||||
public function getSize()
|
||||
@@ -131,7 +134,7 @@ class CachingStream implements StreamInterface
|
||||
private function cacheEntireStream()
|
||||
{
|
||||
$target = new FnStream(['write' => 'strlen']);
|
||||
copy_to_stream($this, $target);
|
||||
Utils::copyToStream($this, $target);
|
||||
|
||||
return $this->tell();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -6,6 +7,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
/**
|
||||
* Stream decorator that begins dropping data once the size of the underlying
|
||||
* stream becomes too full.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class DroppingStream implements StreamInterface
|
||||
{
|
||||
|
||||
+5
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -8,6 +9,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
*
|
||||
* Allows for easy testing and extension of a provided stream without needing
|
||||
* to create a concrete class for a simple extension point.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class FnStream implements StreamInterface
|
||||
{
|
||||
@@ -34,6 +37,7 @@ class FnStream implements StreamInterface
|
||||
|
||||
/**
|
||||
* Lazily determine which methods are not implemented.
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
public function __get($name)
|
||||
@@ -54,6 +58,7 @@ class FnStream implements StreamInterface
|
||||
|
||||
/**
|
||||
* An unserialize would allow the __destruct to run when the unserialized value goes out of scope.
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
public function __wakeup()
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
final class Header
|
||||
{
|
||||
/**
|
||||
* Parse an array of header values containing ";" separated data into an
|
||||
* array of associative arrays representing the header key value pair data
|
||||
* of the header. When a parameter does not contain a value, but just
|
||||
* contains a key, this function will inject a key with a '' string value.
|
||||
*
|
||||
* @param string|array $header Header to parse into components.
|
||||
*
|
||||
* @return array Returns the parsed header values.
|
||||
*/
|
||||
public static function parse($header)
|
||||
{
|
||||
static $trimmed = "\"' \n\t\r";
|
||||
$params = $matches = [];
|
||||
|
||||
foreach (self::normalize($header) as $val) {
|
||||
$part = [];
|
||||
foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
|
||||
if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
|
||||
$m = $matches[0];
|
||||
if (isset($m[1])) {
|
||||
$part[trim($m[0], $trimmed)] = trim($m[1], $trimmed);
|
||||
} else {
|
||||
$part[] = trim($m[0], $trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($part) {
|
||||
$params[] = $part;
|
||||
}
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an array of header values that may contain comma separated
|
||||
* headers into an array of headers with no comma separated values.
|
||||
*
|
||||
* @param string|array $header Header to normalize.
|
||||
*
|
||||
* @return array Returns the normalized header field values.
|
||||
*/
|
||||
public static function normalize($header)
|
||||
{
|
||||
if (!is_array($header)) {
|
||||
return array_map('trim', explode(',', $header));
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($header as $value) {
|
||||
foreach ((array) $value as $v) {
|
||||
if (strpos($v, ',') === false) {
|
||||
$result[] = $v;
|
||||
continue;
|
||||
}
|
||||
foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) {
|
||||
$result[] = trim($vv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -13,6 +14,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
*
|
||||
* @link http://tools.ietf.org/html/rfc1952
|
||||
* @link http://php.net/manual/en/filters.compression.php
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class InflateStream implements StreamInterface
|
||||
{
|
||||
@@ -33,6 +36,7 @@ class InflateStream implements StreamInterface
|
||||
/**
|
||||
* @param StreamInterface $stream
|
||||
* @param $header
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private function getLengthOfPossibleFilenameHeader(StreamInterface $stream, $header)
|
||||
|
||||
+5
-2
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -6,6 +7,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
/**
|
||||
* Lazily reads or writes to a file that is opened only after an IO operation
|
||||
* take place on the stream.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class LazyOpenStream implements StreamInterface
|
||||
{
|
||||
@@ -14,7 +17,7 @@ class LazyOpenStream implements StreamInterface
|
||||
/** @var string File to open */
|
||||
private $filename;
|
||||
|
||||
/** @var string $mode */
|
||||
/** @var string */
|
||||
private $mode;
|
||||
|
||||
/**
|
||||
@@ -34,6 +37,6 @@ class LazyOpenStream implements StreamInterface
|
||||
*/
|
||||
protected function createStream()
|
||||
{
|
||||
return stream_for(try_fopen($this->filename, $this->mode));
|
||||
return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode));
|
||||
}
|
||||
}
|
||||
|
||||
+4
-2
@@ -1,11 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
|
||||
/**
|
||||
* Decorator used to return only a subset of a stream
|
||||
* Decorator used to return only a subset of a stream.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class LimitStream implements StreamInterface
|
||||
{
|
||||
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
||||
final class Message
|
||||
{
|
||||
/**
|
||||
* Returns the string representation of an HTTP message.
|
||||
*
|
||||
* @param MessageInterface $message Message to convert to a string.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function toString(MessageInterface $message)
|
||||
{
|
||||
if ($message instanceof RequestInterface) {
|
||||
$msg = trim($message->getMethod() . ' '
|
||||
. $message->getRequestTarget())
|
||||
. ' HTTP/' . $message->getProtocolVersion();
|
||||
if (!$message->hasHeader('host')) {
|
||||
$msg .= "\r\nHost: " . $message->getUri()->getHost();
|
||||
}
|
||||
} elseif ($message instanceof ResponseInterface) {
|
||||
$msg = 'HTTP/' . $message->getProtocolVersion() . ' '
|
||||
. $message->getStatusCode() . ' '
|
||||
. $message->getReasonPhrase();
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Unknown message type');
|
||||
}
|
||||
|
||||
foreach ($message->getHeaders() as $name => $values) {
|
||||
if (strtolower($name) === 'set-cookie') {
|
||||
foreach ($values as $value) {
|
||||
$msg .= "\r\n{$name}: " . $value;
|
||||
}
|
||||
} else {
|
||||
$msg .= "\r\n{$name}: " . implode(', ', $values);
|
||||
}
|
||||
}
|
||||
|
||||
return "{$msg}\r\n\r\n" . $message->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a short summary of the message body.
|
||||
*
|
||||
* Will return `null` if the response is not printable.
|
||||
*
|
||||
* @param MessageInterface $message The message to get the body summary
|
||||
* @param int $truncateAt The maximum allowed size of the summary
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function bodySummary(MessageInterface $message, $truncateAt = 120)
|
||||
{
|
||||
$body = $message->getBody();
|
||||
|
||||
if (!$body->isSeekable() || !$body->isReadable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = $body->getSize();
|
||||
|
||||
if ($size === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$summary = $body->read($truncateAt);
|
||||
$body->rewind();
|
||||
|
||||
if ($size > $truncateAt) {
|
||||
$summary .= ' (truncated...)';
|
||||
}
|
||||
|
||||
// Matches any printable character, including unicode characters:
|
||||
// letters, marks, numbers, punctuation, spacing, and separators.
|
||||
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to rewind a message body and throws an exception on failure.
|
||||
*
|
||||
* The body of the message will only be rewound if a call to `tell()`
|
||||
* returns a value other than `0`.
|
||||
*
|
||||
* @param MessageInterface $message Message to rewind
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public static function rewindBody(MessageInterface $message)
|
||||
{
|
||||
$body = $message->getBody();
|
||||
|
||||
if ($body->tell()) {
|
||||
$body->rewind();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an HTTP message into an associative array.
|
||||
*
|
||||
* The array contains the "start-line" key containing the start line of
|
||||
* the message, "headers" key containing an associative array of header
|
||||
* array values, and a "body" key containing the body of the message.
|
||||
*
|
||||
* @param string $message HTTP request or response to parse.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function parseMessage($message)
|
||||
{
|
||||
if (!$message) {
|
||||
throw new \InvalidArgumentException('Invalid message');
|
||||
}
|
||||
|
||||
$message = ltrim($message, "\r\n");
|
||||
|
||||
$messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
|
||||
|
||||
if ($messageParts === false || count($messageParts) !== 2) {
|
||||
throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
|
||||
}
|
||||
|
||||
list($rawHeaders, $body) = $messageParts;
|
||||
$rawHeaders .= "\r\n"; // Put back the delimiter we split previously
|
||||
$headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
|
||||
|
||||
if ($headerParts === false || count($headerParts) !== 2) {
|
||||
throw new \InvalidArgumentException('Invalid message: Missing status line');
|
||||
}
|
||||
|
||||
list($startLine, $rawHeaders) = $headerParts;
|
||||
|
||||
if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') {
|
||||
// Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
|
||||
$rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
|
||||
}
|
||||
|
||||
/** @var array[] $headerLines */
|
||||
$count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
|
||||
|
||||
// If these aren't the same, then one line didn't match and there's an invalid header.
|
||||
if ($count !== substr_count($rawHeaders, "\n")) {
|
||||
// Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
|
||||
if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
|
||||
throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Invalid header syntax');
|
||||
}
|
||||
|
||||
$headers = [];
|
||||
|
||||
foreach ($headerLines as $headerLine) {
|
||||
$headers[$headerLine[1]][] = $headerLine[2];
|
||||
}
|
||||
|
||||
return [
|
||||
'start-line' => $startLine,
|
||||
'headers' => $headers,
|
||||
'body' => $body,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a URI for an HTTP request message.
|
||||
*
|
||||
* @param string $path Path from the start-line
|
||||
* @param array $headers Array of headers (each value an array).
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function parseRequestUri($path, array $headers)
|
||||
{
|
||||
$hostKey = array_filter(array_keys($headers), function ($k) {
|
||||
return strtolower($k) === 'host';
|
||||
});
|
||||
|
||||
// If no host is found, then a full URI cannot be constructed.
|
||||
if (!$hostKey) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$host = $headers[reset($hostKey)][0];
|
||||
$scheme = substr($host, -4) === ':443' ? 'https' : 'http';
|
||||
|
||||
return $scheme . '://' . $host . '/' . ltrim($path, '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a request message string into a request object.
|
||||
*
|
||||
* @param string $message Request message string.
|
||||
*
|
||||
* @return Request
|
||||
*/
|
||||
public static function parseRequest($message)
|
||||
{
|
||||
$data = self::parseMessage($message);
|
||||
$matches = [];
|
||||
if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
|
||||
throw new \InvalidArgumentException('Invalid request string');
|
||||
}
|
||||
$parts = explode(' ', $data['start-line'], 3);
|
||||
$version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
|
||||
|
||||
$request = new Request(
|
||||
$parts[0],
|
||||
$matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1],
|
||||
$data['headers'],
|
||||
$data['body'],
|
||||
$version
|
||||
);
|
||||
|
||||
return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a response message string into a response object.
|
||||
*
|
||||
* @param string $message Response message string.
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
public static function parseResponse($message)
|
||||
{
|
||||
$data = self::parseMessage($message);
|
||||
// According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space
|
||||
// between status-code and reason-phrase is required. But browsers accept
|
||||
// responses without space and reason as well.
|
||||
if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
|
||||
throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
|
||||
}
|
||||
$parts = explode(' ', $data['start-line'], 3);
|
||||
|
||||
return new Response(
|
||||
(int) $parts[1],
|
||||
$data['headers'],
|
||||
$data['body'],
|
||||
explode('/', $parts[0])[1],
|
||||
isset($parts[2]) ? $parts[2] : null
|
||||
);
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -17,7 +18,7 @@ trait MessageTrait
|
||||
/** @var string */
|
||||
private $protocol = '1.1';
|
||||
|
||||
/** @var StreamInterface */
|
||||
/** @var StreamInterface|null */
|
||||
private $stream;
|
||||
|
||||
public function getProtocolVersion()
|
||||
@@ -117,7 +118,7 @@ trait MessageTrait
|
||||
public function getBody()
|
||||
{
|
||||
if (!$this->stream) {
|
||||
$this->stream = stream_for('');
|
||||
$this->stream = Utils::streamFor('');
|
||||
}
|
||||
|
||||
return $this->stream;
|
||||
@@ -194,7 +195,7 @@ trait MessageTrait
|
||||
}
|
||||
|
||||
return trim((string) $value, " \t");
|
||||
}, $values);
|
||||
}, array_values($values));
|
||||
}
|
||||
|
||||
private function assertHeader($header)
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
final class MimeType
|
||||
{
|
||||
/**
|
||||
* Determines the mimetype of a file by looking at its extension.
|
||||
*
|
||||
* @param string $filename
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function fromFilename($filename)
|
||||
{
|
||||
return self::fromExtension(pathinfo($filename, PATHINFO_EXTENSION));
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a file extensions to a mimetype.
|
||||
*
|
||||
* @param string $extension string The file extension.
|
||||
*
|
||||
* @return string|null
|
||||
*
|
||||
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
|
||||
*/
|
||||
public static function fromExtension($extension)
|
||||
{
|
||||
static $mimetypes = [
|
||||
'3gp' => 'video/3gpp',
|
||||
'7z' => 'application/x-7z-compressed',
|
||||
'aac' => 'audio/x-aac',
|
||||
'ai' => 'application/postscript',
|
||||
'aif' => 'audio/x-aiff',
|
||||
'asc' => 'text/plain',
|
||||
'asf' => 'video/x-ms-asf',
|
||||
'atom' => 'application/atom+xml',
|
||||
'avi' => 'video/x-msvideo',
|
||||
'bmp' => 'image/bmp',
|
||||
'bz2' => 'application/x-bzip2',
|
||||
'cer' => 'application/pkix-cert',
|
||||
'crl' => 'application/pkix-crl',
|
||||
'crt' => 'application/x-x509-ca-cert',
|
||||
'css' => 'text/css',
|
||||
'csv' => 'text/csv',
|
||||
'cu' => 'application/cu-seeme',
|
||||
'deb' => 'application/x-debian-package',
|
||||
'doc' => 'application/msword',
|
||||
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'dvi' => 'application/x-dvi',
|
||||
'eot' => 'application/vnd.ms-fontobject',
|
||||
'eps' => 'application/postscript',
|
||||
'epub' => 'application/epub+zip',
|
||||
'etx' => 'text/x-setext',
|
||||
'flac' => 'audio/flac',
|
||||
'flv' => 'video/x-flv',
|
||||
'gif' => 'image/gif',
|
||||
'gz' => 'application/gzip',
|
||||
'htm' => 'text/html',
|
||||
'html' => 'text/html',
|
||||
'ico' => 'image/x-icon',
|
||||
'ics' => 'text/calendar',
|
||||
'ini' => 'text/plain',
|
||||
'iso' => 'application/x-iso9660-image',
|
||||
'jar' => 'application/java-archive',
|
||||
'jpe' => 'image/jpeg',
|
||||
'jpeg' => 'image/jpeg',
|
||||
'jpg' => 'image/jpeg',
|
||||
'js' => 'text/javascript',
|
||||
'json' => 'application/json',
|
||||
'latex' => 'application/x-latex',
|
||||
'log' => 'text/plain',
|
||||
'm4a' => 'audio/mp4',
|
||||
'm4v' => 'video/mp4',
|
||||
'mid' => 'audio/midi',
|
||||
'midi' => 'audio/midi',
|
||||
'mov' => 'video/quicktime',
|
||||
'mkv' => 'video/x-matroska',
|
||||
'mp3' => 'audio/mpeg',
|
||||
'mp4' => 'video/mp4',
|
||||
'mp4a' => 'audio/mp4',
|
||||
'mp4v' => 'video/mp4',
|
||||
'mpe' => 'video/mpeg',
|
||||
'mpeg' => 'video/mpeg',
|
||||
'mpg' => 'video/mpeg',
|
||||
'mpg4' => 'video/mp4',
|
||||
'oga' => 'audio/ogg',
|
||||
'ogg' => 'audio/ogg',
|
||||
'ogv' => 'video/ogg',
|
||||
'ogx' => 'application/ogg',
|
||||
'pbm' => 'image/x-portable-bitmap',
|
||||
'pdf' => 'application/pdf',
|
||||
'pgm' => 'image/x-portable-graymap',
|
||||
'png' => 'image/png',
|
||||
'pnm' => 'image/x-portable-anymap',
|
||||
'ppm' => 'image/x-portable-pixmap',
|
||||
'ppt' => 'application/vnd.ms-powerpoint',
|
||||
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'ps' => 'application/postscript',
|
||||
'qt' => 'video/quicktime',
|
||||
'rar' => 'application/x-rar-compressed',
|
||||
'ras' => 'image/x-cmu-raster',
|
||||
'rss' => 'application/rss+xml',
|
||||
'rtf' => 'application/rtf',
|
||||
'sgm' => 'text/sgml',
|
||||
'sgml' => 'text/sgml',
|
||||
'svg' => 'image/svg+xml',
|
||||
'swf' => 'application/x-shockwave-flash',
|
||||
'tar' => 'application/x-tar',
|
||||
'tif' => 'image/tiff',
|
||||
'tiff' => 'image/tiff',
|
||||
'torrent' => 'application/x-bittorrent',
|
||||
'ttf' => 'application/x-font-ttf',
|
||||
'txt' => 'text/plain',
|
||||
'wav' => 'audio/x-wav',
|
||||
'webm' => 'video/webm',
|
||||
'webp' => 'image/webp',
|
||||
'wma' => 'audio/x-ms-wma',
|
||||
'wmv' => 'video/x-ms-wmv',
|
||||
'woff' => 'application/x-font-woff',
|
||||
'wsdl' => 'application/wsdl+xml',
|
||||
'xbm' => 'image/x-xbitmap',
|
||||
'xls' => 'application/vnd.ms-excel',
|
||||
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'xml' => 'application/xml',
|
||||
'xpm' => 'image/x-xpixmap',
|
||||
'xwd' => 'image/x-xwindowdump',
|
||||
'yaml' => 'text/yaml',
|
||||
'yml' => 'text/yaml',
|
||||
'zip' => 'application/zip',
|
||||
];
|
||||
|
||||
$extension = strtolower($extension);
|
||||
|
||||
return isset($mimetypes[$extension])
|
||||
? $mimetypes[$extension]
|
||||
: null;
|
||||
}
|
||||
}
|
||||
+12
-7
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -6,6 +7,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
/**
|
||||
* Stream that when read returns bytes for a streaming multipart or
|
||||
* multipart/form-data stream.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class MultipartStream implements StreamInterface
|
||||
{
|
||||
@@ -71,7 +74,7 @@ class MultipartStream implements StreamInterface
|
||||
}
|
||||
|
||||
// Add the trailing boundary with CRLF
|
||||
$stream->addStream(stream_for("--{$this->boundary}--\r\n"));
|
||||
$stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n"));
|
||||
|
||||
return $stream;
|
||||
}
|
||||
@@ -84,7 +87,7 @@ class MultipartStream implements StreamInterface
|
||||
}
|
||||
}
|
||||
|
||||
$element['contents'] = stream_for($element['contents']);
|
||||
$element['contents'] = Utils::streamFor($element['contents']);
|
||||
|
||||
if (empty($element['filename'])) {
|
||||
$uri = $element['contents']->getMetadata('uri');
|
||||
@@ -100,9 +103,9 @@ class MultipartStream implements StreamInterface
|
||||
isset($element['headers']) ? $element['headers'] : []
|
||||
);
|
||||
|
||||
$stream->addStream(stream_for($this->getHeaders($headers)));
|
||||
$stream->addStream(Utils::streamFor($this->getHeaders($headers)));
|
||||
$stream->addStream($body);
|
||||
$stream->addStream(stream_for("\r\n"));
|
||||
$stream->addStream(Utils::streamFor("\r\n"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -114,9 +117,11 @@ class MultipartStream implements StreamInterface
|
||||
$disposition = $this->getHeader($headers, 'content-disposition');
|
||||
if (!$disposition) {
|
||||
$headers['Content-Disposition'] = ($filename === '0' || $filename)
|
||||
? sprintf('form-data; name="%s"; filename="%s"',
|
||||
? sprintf(
|
||||
'form-data; name="%s"; filename="%s"',
|
||||
$name,
|
||||
basename($filename))
|
||||
basename($filename)
|
||||
)
|
||||
: "form-data; name=\"{$name}\"";
|
||||
}
|
||||
|
||||
@@ -131,7 +136,7 @@ class MultipartStream implements StreamInterface
|
||||
// Set a default Content-Type if one was not supplied
|
||||
$type = $this->getHeader($headers, 'content-type');
|
||||
if (!$type && ($filename === '0' || $filename)) {
|
||||
if ($type = mimetype_from_filename($filename)) {
|
||||
if ($type = MimeType::fromFilename($filename)) {
|
||||
$headers['Content-Type'] = $type;
|
||||
}
|
||||
}
|
||||
|
||||
+4
-1
@@ -1,10 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Stream decorator that prevents a stream from being seeked
|
||||
* Stream decorator that prevents a stream from being seeked.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class NoSeekStream implements StreamInterface
|
||||
{
|
||||
|
||||
+14
-9
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -12,6 +13,8 @@ use Psr\Http\Message\StreamInterface;
|
||||
* returned by the provided callable is buffered internally until drained using
|
||||
* the read() function of the PumpStream. The provided callable MUST return
|
||||
* false when there is no more data to read.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class PumpStream implements StreamInterface
|
||||
{
|
||||
@@ -31,14 +34,14 @@ class PumpStream implements StreamInterface
|
||||
private $buffer;
|
||||
|
||||
/**
|
||||
* @param callable $source Source of the stream data. The callable MAY
|
||||
* accept an integer argument used to control the
|
||||
* amount of data to return. The callable MUST
|
||||
* return a string when called, or false on error
|
||||
* or EOF.
|
||||
* @param array $options Stream options:
|
||||
* - metadata: Hash of metadata to use with stream.
|
||||
* - size: Size of the stream, if known.
|
||||
* @param callable $source Source of the stream data. The callable MAY
|
||||
* accept an integer argument used to control the
|
||||
* amount of data to return. The callable MUST
|
||||
* return a string when called, or false on error
|
||||
* or EOF.
|
||||
* @param array $options Stream options:
|
||||
* - metadata: Hash of metadata to use with stream.
|
||||
* - size: Size of the stream, if known.
|
||||
*/
|
||||
public function __construct(callable $source, array $options = [])
|
||||
{
|
||||
@@ -51,7 +54,7 @@ class PumpStream implements StreamInterface
|
||||
public function __toString()
|
||||
{
|
||||
try {
|
||||
return copy_to_string($this);
|
||||
return Utils::copyToString($this);
|
||||
} catch (\Exception $e) {
|
||||
return '';
|
||||
}
|
||||
@@ -66,6 +69,8 @@ class PumpStream implements StreamInterface
|
||||
{
|
||||
$this->tellPos = false;
|
||||
$this->source = null;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function getSize()
|
||||
|
||||
Vendored
+113
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
final class Query
|
||||
{
|
||||
/**
|
||||
* Parse a query string into an associative array.
|
||||
*
|
||||
* If multiple values are found for the same key, the value of that key
|
||||
* value pair will become an array. This function does not parse nested
|
||||
* PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2`
|
||||
* will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`.
|
||||
*
|
||||
* @param string $str Query string to parse
|
||||
* @param int|bool $urlEncoding How the query string is encoded
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function parse($str, $urlEncoding = true)
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($str === '') {
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ($urlEncoding === true) {
|
||||
$decoder = function ($value) {
|
||||
return rawurldecode(str_replace('+', ' ', $value));
|
||||
};
|
||||
} elseif ($urlEncoding === PHP_QUERY_RFC3986) {
|
||||
$decoder = 'rawurldecode';
|
||||
} elseif ($urlEncoding === PHP_QUERY_RFC1738) {
|
||||
$decoder = 'urldecode';
|
||||
} else {
|
||||
$decoder = function ($str) {
|
||||
return $str;
|
||||
};
|
||||
}
|
||||
|
||||
foreach (explode('&', $str) as $kvp) {
|
||||
$parts = explode('=', $kvp, 2);
|
||||
$key = $decoder($parts[0]);
|
||||
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
|
||||
if (!isset($result[$key])) {
|
||||
$result[$key] = $value;
|
||||
} else {
|
||||
if (!is_array($result[$key])) {
|
||||
$result[$key] = [$result[$key]];
|
||||
}
|
||||
$result[$key][] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a query string from an array of key value pairs.
|
||||
*
|
||||
* This function can use the return value of `parse()` to build a query
|
||||
* string. This function does not modify the provided keys when an array is
|
||||
* encountered (like `http_build_query()` would).
|
||||
*
|
||||
* @param array $params Query string parameters.
|
||||
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
|
||||
* to encode using RFC3986, or PHP_QUERY_RFC1738
|
||||
* to encode using RFC1738.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function build(array $params, $encoding = PHP_QUERY_RFC3986)
|
||||
{
|
||||
if (!$params) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($encoding === false) {
|
||||
$encoder = function ($str) {
|
||||
return $str;
|
||||
};
|
||||
} elseif ($encoding === PHP_QUERY_RFC3986) {
|
||||
$encoder = 'rawurlencode';
|
||||
} elseif ($encoding === PHP_QUERY_RFC1738) {
|
||||
$encoder = 'urlencode';
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Invalid type');
|
||||
}
|
||||
|
||||
$qs = '';
|
||||
foreach ($params as $k => $v) {
|
||||
$k = $encoder($k);
|
||||
if (!is_array($v)) {
|
||||
$qs .= $k;
|
||||
if ($v !== null) {
|
||||
$qs .= '=' . $encoder($v);
|
||||
}
|
||||
$qs .= '&';
|
||||
} else {
|
||||
foreach ($v as $vv) {
|
||||
$qs .= $k;
|
||||
if ($vv !== null) {
|
||||
$qs .= '=' . $encoder($vv);
|
||||
}
|
||||
$qs .= '&';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $qs ? (string) substr($qs, 0, -1) : '';
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use InvalidArgumentException;
|
||||
@@ -16,7 +17,7 @@ class Request implements RequestInterface
|
||||
/** @var string */
|
||||
private $method;
|
||||
|
||||
/** @var null|string */
|
||||
/** @var string|null */
|
||||
private $requestTarget;
|
||||
|
||||
/** @var UriInterface */
|
||||
@@ -26,7 +27,7 @@ class Request implements RequestInterface
|
||||
* @param string $method HTTP method
|
||||
* @param string|UriInterface $uri URI
|
||||
* @param array $headers Request headers
|
||||
* @param string|null|resource|StreamInterface $body Request body
|
||||
* @param string|resource|StreamInterface|null $body Request body
|
||||
* @param string $version Protocol version
|
||||
*/
|
||||
public function __construct(
|
||||
@@ -51,7 +52,7 @@ class Request implements RequestInterface
|
||||
}
|
||||
|
||||
if ($body !== '' && $body !== null) {
|
||||
$this->stream = stream_for($body);
|
||||
$this->stream = Utils::streamFor($body);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+4
-3
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
@@ -82,7 +83,7 @@ class Response implements ResponseInterface
|
||||
/**
|
||||
* @param int $status Status code
|
||||
* @param array $headers Response headers
|
||||
* @param string|null|resource|StreamInterface $body Response body
|
||||
* @param string|resource|StreamInterface|null $body Response body
|
||||
* @param string $version Protocol version
|
||||
* @param string|null $reason Reason phrase (when empty a default will be used based on the status code)
|
||||
*/
|
||||
@@ -100,7 +101,7 @@ class Response implements ResponseInterface
|
||||
$this->statusCode = $status;
|
||||
|
||||
if ($body !== '' && $body !== null) {
|
||||
$this->stream = stream_for($body);
|
||||
$this->stream = Utils::streamFor($body);
|
||||
}
|
||||
|
||||
$this->setHeaders($headers);
|
||||
@@ -134,7 +135,7 @@ class Response implements ResponseInterface
|
||||
if ($reasonPhrase == '' && isset(self::$phrases[$new->statusCode])) {
|
||||
$reasonPhrase = self::$phrases[$new->statusCode];
|
||||
}
|
||||
$new->reasonPhrase = $reasonPhrase;
|
||||
$new->reasonPhrase = (string) $reasonPhrase;
|
||||
return $new;
|
||||
}
|
||||
|
||||
|
||||
+1
@@ -11,6 +11,7 @@ final class Rfc7230
|
||||
* Note: header delimiter (\r\n) is modified to \r?\n to accept line feed only delimiters for BC reasons.
|
||||
*
|
||||
* @link https://github.com/amphp/http/blob/v1.0.1/src/Rfc7230.php#L12-L15
|
||||
*
|
||||
* @license https://github.com/amphp/http/blob/v1.0.1/LICENSE
|
||||
*/
|
||||
const HEADER_REGEX = "(^([^()<>@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m";
|
||||
|
||||
+9
-6
@@ -4,9 +4,9 @@ namespace GuzzleHttp\Psr7;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
/**
|
||||
* Server-side HTTP request
|
||||
@@ -35,7 +35,7 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
private $cookieParams = [];
|
||||
|
||||
/**
|
||||
* @var null|array|object
|
||||
* @var array|object|null
|
||||
*/
|
||||
private $parsedBody;
|
||||
|
||||
@@ -58,7 +58,7 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
* @param string $method HTTP method
|
||||
* @param string|UriInterface $uri URI
|
||||
* @param array $headers Request headers
|
||||
* @param string|null|resource|StreamInterface $body Request body
|
||||
* @param string|resource|StreamInterface|null $body Request body
|
||||
* @param string $version Protocol version
|
||||
* @param array $serverParams Typically the $_SERVER superglobal
|
||||
*/
|
||||
@@ -79,8 +79,10 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
* Return an UploadedFile instance array.
|
||||
*
|
||||
* @param array $files A array which respect $_FILES structure
|
||||
* @throws InvalidArgumentException for unrecognized values
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @throws InvalidArgumentException for unrecognized values
|
||||
*/
|
||||
public static function normalizeFiles(array $files)
|
||||
{
|
||||
@@ -109,6 +111,7 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
* delegate to normalizeNestedFileSpec() and return that return value.
|
||||
*
|
||||
* @param array $value $_FILES struct
|
||||
*
|
||||
* @return array|UploadedFileInterface
|
||||
*/
|
||||
private static function createUploadedFileFromSpec(array $value)
|
||||
@@ -133,6 +136,7 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
* UploadedFileInterface instances.
|
||||
*
|
||||
* @param array $files
|
||||
*
|
||||
* @return UploadedFileInterface[]
|
||||
*/
|
||||
private static function normalizeNestedFileSpec(array $files = [])
|
||||
@@ -182,7 +186,7 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
|
||||
private static function extractHostAndPortFromAuthority($authority)
|
||||
{
|
||||
$uri = 'http://'.$authority;
|
||||
$uri = 'http://' . $authority;
|
||||
$parts = parse_url($uri);
|
||||
if (false === $parts) {
|
||||
return [null, null];
|
||||
@@ -243,7 +247,6 @@ class ServerRequest extends Request implements ServerRequestInterface
|
||||
return $uri;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
||||
+6
-3
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
@@ -76,8 +77,10 @@ class Stream implements StreamInterface
|
||||
public function __toString()
|
||||
{
|
||||
try {
|
||||
$this->seek(0);
|
||||
return (string) stream_get_contents($this->stream);
|
||||
if ($this->isSeekable()) {
|
||||
$this->seek(0);
|
||||
}
|
||||
return $this->getContents();
|
||||
} catch (\Exception $e) {
|
||||
return '';
|
||||
}
|
||||
@@ -193,7 +196,7 @@ class Stream implements StreamInterface
|
||||
public function seek($offset, $whence = SEEK_SET)
|
||||
{
|
||||
$whence = (int) $whence;
|
||||
|
||||
|
||||
if (!isset($this->stream)) {
|
||||
throw new \RuntimeException('Stream is detached');
|
||||
}
|
||||
|
||||
+4
-1
@@ -1,10 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Stream decorator trait
|
||||
*
|
||||
* @property StreamInterface stream
|
||||
*/
|
||||
trait StreamDecoratorTrait
|
||||
@@ -52,7 +54,7 @@ trait StreamDecoratorTrait
|
||||
|
||||
public function getContents()
|
||||
{
|
||||
return copy_to_string($this);
|
||||
return Utils::copyToString($this);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -140,6 +142,7 @@ trait StreamDecoratorTrait
|
||||
* Implement in subclasses to dynamically create streams when requested.
|
||||
*
|
||||
* @return StreamInterface
|
||||
*
|
||||
* @throws \BadMethodCallException
|
||||
*/
|
||||
protected function createStream()
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
|
||||
/**
|
||||
* Converts Guzzle streams into PHP stream resources.
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class StreamWrapper
|
||||
{
|
||||
@@ -23,6 +26,7 @@ class StreamWrapper
|
||||
* @param StreamInterface $stream The stream to get a resource for
|
||||
*
|
||||
* @return resource
|
||||
*
|
||||
* @throws \InvalidArgumentException if stream is not readable or writable
|
||||
*/
|
||||
public static function getResource(StreamInterface $stream)
|
||||
|
||||
+26
-14
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use InvalidArgumentException;
|
||||
@@ -38,7 +39,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
private $error;
|
||||
|
||||
/**
|
||||
* @var null|string
|
||||
* @var string|null
|
||||
*/
|
||||
private $file;
|
||||
|
||||
@@ -59,10 +60,10 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param StreamInterface|string|resource $streamOrFile
|
||||
* @param int $size
|
||||
* @param int $errorStatus
|
||||
* @param string|null $clientFilename
|
||||
* @param string|null $clientMediaType
|
||||
* @param int $size
|
||||
* @param int $errorStatus
|
||||
* @param string|null $clientFilename
|
||||
* @param string|null $clientMediaType
|
||||
*/
|
||||
public function __construct(
|
||||
$streamOrFile,
|
||||
@@ -85,6 +86,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
* Depending on the value set file or stream variable
|
||||
*
|
||||
* @param mixed $streamOrFile
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
private function setStreamOrFile($streamOrFile)
|
||||
@@ -104,6 +106,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param int $error
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
private function setError($error)
|
||||
@@ -125,6 +128,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param int $size
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
private function setSize($size)
|
||||
@@ -140,7 +144,8 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param mixed $param
|
||||
* @return boolean
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function isStringOrNull($param)
|
||||
{
|
||||
@@ -149,7 +154,8 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param mixed $param
|
||||
* @return boolean
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function isStringNotEmpty($param)
|
||||
{
|
||||
@@ -158,6 +164,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param string|null $clientFilename
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
private function setClientFilename($clientFilename)
|
||||
@@ -173,6 +180,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* @param string|null $clientMediaType
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
private function setClientMediaType($clientMediaType)
|
||||
@@ -189,7 +197,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
/**
|
||||
* Return true if there is no upload error
|
||||
*
|
||||
* @return boolean
|
||||
* @return bool
|
||||
*/
|
||||
private function isOk()
|
||||
{
|
||||
@@ -197,7 +205,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* @return boolean
|
||||
* @return bool
|
||||
*/
|
||||
public function isMoved()
|
||||
{
|
||||
@@ -220,6 +228,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @throws RuntimeException if the upload was not successful.
|
||||
*/
|
||||
public function getStream()
|
||||
@@ -238,11 +247,13 @@ class UploadedFile implements UploadedFileInterface
|
||||
*
|
||||
* @see http://php.net/is_uploaded_file
|
||||
* @see http://php.net/move_uploaded_file
|
||||
*
|
||||
* @param string $targetPath Path to which to move the uploaded file.
|
||||
* @throws RuntimeException if the upload was not successful.
|
||||
*
|
||||
* @throws RuntimeException if the upload was not successful.
|
||||
* @throws InvalidArgumentException if the $path specified is invalid.
|
||||
* @throws RuntimeException on any error during the move operation, or on
|
||||
* the second or subsequent call to the method.
|
||||
* @throws RuntimeException on any error during the move operation, or on
|
||||
* the second or subsequent call to the method.
|
||||
*/
|
||||
public function moveTo($targetPath)
|
||||
{
|
||||
@@ -259,7 +270,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
? rename($this->file, $targetPath)
|
||||
: move_uploaded_file($this->file, $targetPath);
|
||||
} else {
|
||||
copy_to_stream(
|
||||
Utils::copyToStream(
|
||||
$this->getStream(),
|
||||
new LazyOpenStream($targetPath, 'w')
|
||||
);
|
||||
@@ -288,6 +299,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @see http://php.net/manual/en/features.file-upload.errors.php
|
||||
*
|
||||
* @return int One of PHP's UPLOAD_ERR_XXX constants.
|
||||
*/
|
||||
public function getError()
|
||||
@@ -299,7 +311,7 @@ class UploadedFile implements UploadedFileInterface
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @return string|null The filename sent by the client or null if none
|
||||
* was provided.
|
||||
* was provided.
|
||||
*/
|
||||
public function getClientFilename()
|
||||
{
|
||||
|
||||
Vendored
+56
-6
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\UriInterface;
|
||||
@@ -66,7 +67,7 @@ class Uri implements UriInterface
|
||||
{
|
||||
// weak type check to also accept null until we can add scalar type hints
|
||||
if ($uri != '') {
|
||||
$parts = parse_url($uri);
|
||||
$parts = self::parse($uri);
|
||||
if ($parts === false) {
|
||||
throw new \InvalidArgumentException("Unable to parse URI: $uri");
|
||||
}
|
||||
@@ -74,6 +75,49 @@ class Uri implements UriInterface
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* UTF-8 aware \parse_url() replacement.
|
||||
*
|
||||
* The internal function produces broken output for non ASCII domain names
|
||||
* (IDN) when used with locales other than "C".
|
||||
*
|
||||
* On the other hand, cURL understands IDN correctly only when UTF-8 locale
|
||||
* is configured ("C.UTF-8", "en_US.UTF-8", etc.).
|
||||
*
|
||||
* @see https://bugs.php.net/bug.php?id=52923
|
||||
* @see https://www.php.net/manual/en/function.parse-url.php#114817
|
||||
* @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING
|
||||
*
|
||||
* @param string $url
|
||||
*
|
||||
* @return array|false
|
||||
*/
|
||||
private static function parse($url)
|
||||
{
|
||||
// If IPv6
|
||||
$prefix = '';
|
||||
if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) {
|
||||
$prefix = $matches[1];
|
||||
$url = $matches[2];
|
||||
}
|
||||
|
||||
$encodedUrl = preg_replace_callback(
|
||||
'%[^:/@?&=#]+%usD',
|
||||
static function ($matches) {
|
||||
return urlencode($matches[0]);
|
||||
},
|
||||
$url
|
||||
);
|
||||
|
||||
$result = parse_url($prefix . $encodedUrl);
|
||||
|
||||
if ($result === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return array_map('urldecode', $result);
|
||||
}
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return self::composeComponents(
|
||||
@@ -166,6 +210,7 @@ class Uri implements UriInterface
|
||||
* @param UriInterface $uri
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @see Uri::isNetworkPathReference
|
||||
* @see Uri::isAbsolutePathReference
|
||||
* @see Uri::isRelativePathReference
|
||||
@@ -184,6 +229,7 @@ class Uri implements UriInterface
|
||||
* @param UriInterface $uri
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @link https://tools.ietf.org/html/rfc3986#section-4.2
|
||||
*/
|
||||
public static function isNetworkPathReference(UriInterface $uri)
|
||||
@@ -199,6 +245,7 @@ class Uri implements UriInterface
|
||||
* @param UriInterface $uri
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @link https://tools.ietf.org/html/rfc3986#section-4.2
|
||||
*/
|
||||
public static function isAbsolutePathReference(UriInterface $uri)
|
||||
@@ -217,6 +264,7 @@ class Uri implements UriInterface
|
||||
* @param UriInterface $uri
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @link https://tools.ietf.org/html/rfc3986#section-4.2
|
||||
*/
|
||||
public static function isRelativePathReference(UriInterface $uri)
|
||||
@@ -237,6 +285,7 @@ class Uri implements UriInterface
|
||||
* @param UriInterface|null $base An optional base URI to compare against
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @link https://tools.ietf.org/html/rfc3986#section-4.4
|
||||
*/
|
||||
public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null)
|
||||
@@ -357,6 +406,7 @@ class Uri implements UriInterface
|
||||
* @param array $parts
|
||||
*
|
||||
* @return UriInterface
|
||||
*
|
||||
* @link http://php.net/manual/en/function.parse-url.php
|
||||
*
|
||||
* @throws \InvalidArgumentException If the components do not form a valid URI.
|
||||
@@ -575,7 +625,7 @@ class Uri implements UriInterface
|
||||
throw new \InvalidArgumentException('Scheme must be a string');
|
||||
}
|
||||
|
||||
return strtolower($scheme);
|
||||
return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -611,7 +661,7 @@ class Uri implements UriInterface
|
||||
throw new \InvalidArgumentException('Host must be a string');
|
||||
}
|
||||
|
||||
return strtolower($host);
|
||||
return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -640,7 +690,7 @@ class Uri implements UriInterface
|
||||
/**
|
||||
* @param UriInterface $uri
|
||||
* @param array $keys
|
||||
*
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private static function getFilteredQueryString(UriInterface $uri, array $keys)
|
||||
@@ -661,7 +711,7 @@ class Uri implements UriInterface
|
||||
/**
|
||||
* @param string $key
|
||||
* @param string|null $value
|
||||
*
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function generateQueryString($key, $value)
|
||||
@@ -753,7 +803,7 @@ class Uri implements UriInterface
|
||||
'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.',
|
||||
E_USER_DEPRECATED
|
||||
);
|
||||
$this->path = '/'. $this->path;
|
||||
$this->path = '/' . $this->path;
|
||||
//throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\UriInterface;
|
||||
@@ -114,6 +115,7 @@ final class UriNormalizer
|
||||
* @param int $flags A bitmask of normalizations to apply, see constants
|
||||
*
|
||||
* @return UriInterface The normalized URI
|
||||
*
|
||||
* @link https://tools.ietf.org/html/rfc3986#section-6.2
|
||||
*/
|
||||
public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS)
|
||||
@@ -170,6 +172,7 @@ final class UriNormalizer
|
||||
* @param int $normalizations A bitmask of normalizations to apply, see constants
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @link https://tools.ietf.org/html/rfc3986#section-6.1
|
||||
*/
|
||||
public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS)
|
||||
|
||||
+3
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\UriInterface;
|
||||
@@ -18,6 +19,7 @@ final class UriResolver
|
||||
* @param string $path
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @link http://tools.ietf.org/html/rfc3986#section-5.2.4
|
||||
*/
|
||||
public static function removeDotSegments($path)
|
||||
@@ -57,6 +59,7 @@ final class UriResolver
|
||||
* @param UriInterface $rel Relative URI
|
||||
*
|
||||
* @return UriInterface
|
||||
*
|
||||
* @link http://tools.ietf.org/html/rfc3986#section-5.2
|
||||
*/
|
||||
public static function resolve(UriInterface $base, UriInterface $rel)
|
||||
|
||||
Vendored
+428
@@ -0,0 +1,428 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
final class Utils
|
||||
{
|
||||
/**
|
||||
* Remove the items given by the keys, case insensitively from the data.
|
||||
*
|
||||
* @param iterable<string> $keys
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public static function caselessRemove($keys, array $data)
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($keys as &$key) {
|
||||
$key = strtolower($key);
|
||||
}
|
||||
|
||||
foreach ($data as $k => $v) {
|
||||
if (!in_array(strtolower($k), $keys)) {
|
||||
$result[$k] = $v;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the contents of a stream into another stream until the given number
|
||||
* of bytes have been read.
|
||||
*
|
||||
* @param StreamInterface $source Stream to read from
|
||||
* @param StreamInterface $dest Stream to write to
|
||||
* @param int $maxLen Maximum number of bytes to read. Pass -1
|
||||
* to read the entire stream.
|
||||
*
|
||||
* @throws \RuntimeException on error.
|
||||
*/
|
||||
public static function copyToStream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)
|
||||
{
|
||||
$bufferSize = 8192;
|
||||
|
||||
if ($maxLen === -1) {
|
||||
while (!$source->eof()) {
|
||||
if (!$dest->write($source->read($bufferSize))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$remaining = $maxLen;
|
||||
while ($remaining > 0 && !$source->eof()) {
|
||||
$buf = $source->read(min($bufferSize, $remaining));
|
||||
$len = strlen($buf);
|
||||
if (!$len) {
|
||||
break;
|
||||
}
|
||||
$remaining -= $len;
|
||||
$dest->write($buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the contents of a stream into a string until the given number of
|
||||
* bytes have been read.
|
||||
*
|
||||
* @param StreamInterface $stream Stream to read
|
||||
* @param int $maxLen Maximum number of bytes to read. Pass -1
|
||||
* to read the entire stream.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws \RuntimeException on error.
|
||||
*/
|
||||
public static function copyToString(StreamInterface $stream, $maxLen = -1)
|
||||
{
|
||||
$buffer = '';
|
||||
|
||||
if ($maxLen === -1) {
|
||||
while (!$stream->eof()) {
|
||||
$buf = $stream->read(1048576);
|
||||
// Using a loose equality here to match on '' and false.
|
||||
if ($buf == null) {
|
||||
break;
|
||||
}
|
||||
$buffer .= $buf;
|
||||
}
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
$len = 0;
|
||||
while (!$stream->eof() && $len < $maxLen) {
|
||||
$buf = $stream->read($maxLen - $len);
|
||||
// Using a loose equality here to match on '' and false.
|
||||
if ($buf == null) {
|
||||
break;
|
||||
}
|
||||
$buffer .= $buf;
|
||||
$len = strlen($buffer);
|
||||
}
|
||||
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate a hash of a stream.
|
||||
*
|
||||
* This method reads the entire stream to calculate a rolling hash, based
|
||||
* on PHP's `hash_init` functions.
|
||||
*
|
||||
* @param StreamInterface $stream Stream to calculate the hash for
|
||||
* @param string $algo Hash algorithm (e.g. md5, crc32, etc)
|
||||
* @param bool $rawOutput Whether or not to use raw output
|
||||
*
|
||||
* @return string Returns the hash of the stream
|
||||
*
|
||||
* @throws \RuntimeException on error.
|
||||
*/
|
||||
public static function hash(StreamInterface $stream, $algo, $rawOutput = false)
|
||||
{
|
||||
$pos = $stream->tell();
|
||||
|
||||
if ($pos > 0) {
|
||||
$stream->rewind();
|
||||
}
|
||||
|
||||
$ctx = hash_init($algo);
|
||||
while (!$stream->eof()) {
|
||||
hash_update($ctx, $stream->read(1048576));
|
||||
}
|
||||
|
||||
$out = hash_final($ctx, (bool) $rawOutput);
|
||||
$stream->seek($pos);
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone and modify a request with the given changes.
|
||||
*
|
||||
* This method is useful for reducing the number of clones needed to mutate
|
||||
* a message.
|
||||
*
|
||||
* The changes can be one of:
|
||||
* - method: (string) Changes the HTTP method.
|
||||
* - set_headers: (array) Sets the given headers.
|
||||
* - remove_headers: (array) Remove the given headers.
|
||||
* - body: (mixed) Sets the given body.
|
||||
* - uri: (UriInterface) Set the URI.
|
||||
* - query: (string) Set the query string value of the URI.
|
||||
* - version: (string) Set the protocol version.
|
||||
*
|
||||
* @param RequestInterface $request Request to clone and modify.
|
||||
* @param array $changes Changes to apply.
|
||||
*
|
||||
* @return RequestInterface
|
||||
*/
|
||||
public static function modifyRequest(RequestInterface $request, array $changes)
|
||||
{
|
||||
if (!$changes) {
|
||||
return $request;
|
||||
}
|
||||
|
||||
$headers = $request->getHeaders();
|
||||
|
||||
if (!isset($changes['uri'])) {
|
||||
$uri = $request->getUri();
|
||||
} else {
|
||||
// Remove the host header if one is on the URI
|
||||
if ($host = $changes['uri']->getHost()) {
|
||||
$changes['set_headers']['Host'] = $host;
|
||||
|
||||
if ($port = $changes['uri']->getPort()) {
|
||||
$standardPorts = ['http' => 80, 'https' => 443];
|
||||
$scheme = $changes['uri']->getScheme();
|
||||
if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
|
||||
$changes['set_headers']['Host'] .= ':' . $port;
|
||||
}
|
||||
}
|
||||
}
|
||||
$uri = $changes['uri'];
|
||||
}
|
||||
|
||||
if (!empty($changes['remove_headers'])) {
|
||||
$headers = self::caselessRemove($changes['remove_headers'], $headers);
|
||||
}
|
||||
|
||||
if (!empty($changes['set_headers'])) {
|
||||
$headers = self::caselessRemove(array_keys($changes['set_headers']), $headers);
|
||||
$headers = $changes['set_headers'] + $headers;
|
||||
}
|
||||
|
||||
if (isset($changes['query'])) {
|
||||
$uri = $uri->withQuery($changes['query']);
|
||||
}
|
||||
|
||||
if ($request instanceof ServerRequestInterface) {
|
||||
$new = (new ServerRequest(
|
||||
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
|
||||
$uri,
|
||||
$headers,
|
||||
isset($changes['body']) ? $changes['body'] : $request->getBody(),
|
||||
isset($changes['version'])
|
||||
? $changes['version']
|
||||
: $request->getProtocolVersion(),
|
||||
$request->getServerParams()
|
||||
))
|
||||
->withParsedBody($request->getParsedBody())
|
||||
->withQueryParams($request->getQueryParams())
|
||||
->withCookieParams($request->getCookieParams())
|
||||
->withUploadedFiles($request->getUploadedFiles());
|
||||
|
||||
foreach ($request->getAttributes() as $key => $value) {
|
||||
$new = $new->withAttribute($key, $value);
|
||||
}
|
||||
|
||||
return $new;
|
||||
}
|
||||
|
||||
return new Request(
|
||||
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
|
||||
$uri,
|
||||
$headers,
|
||||
isset($changes['body']) ? $changes['body'] : $request->getBody(),
|
||||
isset($changes['version'])
|
||||
? $changes['version']
|
||||
: $request->getProtocolVersion()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a line from the stream up to the maximum allowed buffer length.
|
||||
*
|
||||
* @param StreamInterface $stream Stream to read from
|
||||
* @param int|null $maxLength Maximum buffer length
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function readLine(StreamInterface $stream, $maxLength = null)
|
||||
{
|
||||
$buffer = '';
|
||||
$size = 0;
|
||||
|
||||
while (!$stream->eof()) {
|
||||
// Using a loose equality here to match on '' and false.
|
||||
if (null == ($byte = $stream->read(1))) {
|
||||
return $buffer;
|
||||
}
|
||||
$buffer .= $byte;
|
||||
// Break when a new line is found or the max length - 1 is reached
|
||||
if ($byte === "\n" || ++$size === $maxLength - 1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new stream based on the input type.
|
||||
*
|
||||
* Options is an associative array that can contain the following keys:
|
||||
* - metadata: Array of custom metadata.
|
||||
* - size: Size of the stream.
|
||||
*
|
||||
* This method accepts the following `$resource` types:
|
||||
* - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
|
||||
* - `string`: Creates a stream object that uses the given string as the contents.
|
||||
* - `resource`: Creates a stream object that wraps the given PHP stream resource.
|
||||
* - `Iterator`: If the provided value implements `Iterator`, then a read-only
|
||||
* stream object will be created that wraps the given iterable. Each time the
|
||||
* stream is read from, data from the iterator will fill a buffer and will be
|
||||
* continuously called until the buffer is equal to the requested read size.
|
||||
* Subsequent read calls will first read from the buffer and then call `next`
|
||||
* on the underlying iterator until it is exhausted.
|
||||
* - `object` with `__toString()`: If the object has the `__toString()` method,
|
||||
* the object will be cast to a string and then a stream will be returned that
|
||||
* uses the string value.
|
||||
* - `NULL`: When `null` is passed, an empty stream object is returned.
|
||||
* - `callable` When a callable is passed, a read-only stream object will be
|
||||
* created that invokes the given callable. The callable is invoked with the
|
||||
* number of suggested bytes to read. The callable can return any number of
|
||||
* bytes, but MUST return `false` when there is no more data to return. The
|
||||
* stream object that wraps the callable will invoke the callable until the
|
||||
* number of requested bytes are available. Any additional bytes will be
|
||||
* buffered and used in subsequent reads.
|
||||
*
|
||||
* @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
|
||||
* @param array $options Additional options
|
||||
*
|
||||
* @return StreamInterface
|
||||
*
|
||||
* @throws \InvalidArgumentException if the $resource arg is not valid.
|
||||
*/
|
||||
public static function streamFor($resource = '', array $options = [])
|
||||
{
|
||||
if (is_scalar($resource)) {
|
||||
$stream = self::tryFopen('php://temp', 'r+');
|
||||
if ($resource !== '') {
|
||||
fwrite($stream, $resource);
|
||||
fseek($stream, 0);
|
||||
}
|
||||
return new Stream($stream, $options);
|
||||
}
|
||||
|
||||
switch (gettype($resource)) {
|
||||
case 'resource':
|
||||
/*
|
||||
* The 'php://input' is a special stream with quirks and inconsistencies.
|
||||
* We avoid using that stream by reading it into php://temp
|
||||
*/
|
||||
$metaData = \stream_get_meta_data($resource);
|
||||
if (isset($metaData['uri']) && $metaData['uri'] === 'php://input') {
|
||||
$stream = self::tryFopen('php://temp', 'w+');
|
||||
fwrite($stream, stream_get_contents($resource));
|
||||
fseek($stream, 0);
|
||||
$resource = $stream;
|
||||
}
|
||||
return new Stream($resource, $options);
|
||||
case 'object':
|
||||
if ($resource instanceof StreamInterface) {
|
||||
return $resource;
|
||||
} elseif ($resource instanceof \Iterator) {
|
||||
return new PumpStream(function () use ($resource) {
|
||||
if (!$resource->valid()) {
|
||||
return false;
|
||||
}
|
||||
$result = $resource->current();
|
||||
$resource->next();
|
||||
return $result;
|
||||
}, $options);
|
||||
} elseif (method_exists($resource, '__toString')) {
|
||||
return Utils::streamFor((string) $resource, $options);
|
||||
}
|
||||
break;
|
||||
case 'NULL':
|
||||
return new Stream(self::tryFopen('php://temp', 'r+'), $options);
|
||||
}
|
||||
|
||||
if (is_callable($resource)) {
|
||||
return new PumpStream($resource, $options);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
|
||||
}
|
||||
|
||||
/**
|
||||
* Safely opens a PHP stream resource using a filename.
|
||||
*
|
||||
* When fopen fails, PHP normally raises a warning. This function adds an
|
||||
* error handler that checks for errors and throws an exception instead.
|
||||
*
|
||||
* @param string $filename File to open
|
||||
* @param string $mode Mode used to open the file
|
||||
*
|
||||
* @return resource
|
||||
*
|
||||
* @throws \RuntimeException if the file cannot be opened
|
||||
*/
|
||||
public static function tryFopen($filename, $mode)
|
||||
{
|
||||
$ex = null;
|
||||
set_error_handler(function () use ($filename, $mode, &$ex) {
|
||||
$ex = new \RuntimeException(sprintf(
|
||||
'Unable to open "%s" using mode "%s": %s',
|
||||
$filename,
|
||||
$mode,
|
||||
func_get_args()[1]
|
||||
));
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
try {
|
||||
$handle = fopen($filename, $mode);
|
||||
} catch (\Throwable $e) {
|
||||
$ex = new \RuntimeException(sprintf(
|
||||
'Unable to open "%s" using mode "%s": %s',
|
||||
$filename,
|
||||
$mode,
|
||||
$e->getMessage()
|
||||
), 0, $e);
|
||||
}
|
||||
|
||||
restore_error_handler();
|
||||
|
||||
if ($ex) {
|
||||
/** @var $ex \RuntimeException */
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
return $handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a UriInterface for the given value.
|
||||
*
|
||||
* This function accepts a string or UriInterface and returns a
|
||||
* UriInterface for the given value. If the value is already a
|
||||
* UriInterface, it is returned as-is.
|
||||
*
|
||||
* @param string|UriInterface $uri
|
||||
*
|
||||
* @return UriInterface
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*/
|
||||
public static function uriFor($uri)
|
||||
{
|
||||
if ($uri instanceof UriInterface) {
|
||||
return $uri;
|
||||
}
|
||||
|
||||
if (is_string($uri)) {
|
||||
return new Uri($uri);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('URI must be a string or UriInterface');
|
||||
}
|
||||
}
|
||||
+136
-613
@@ -1,10 +1,9 @@
|
||||
<?php
|
||||
|
||||
namespace GuzzleHttp\Psr7;
|
||||
|
||||
use Psr\Http\Message\MessageInterface;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Message\StreamInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
||||
@@ -14,52 +13,32 @@ use Psr\Http\Message\UriInterface;
|
||||
* @param MessageInterface $message Message to convert to a string.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @deprecated str will be removed in guzzlehttp/psr7:2.0. Use Message::toString instead.
|
||||
*/
|
||||
function str(MessageInterface $message)
|
||||
{
|
||||
if ($message instanceof RequestInterface) {
|
||||
$msg = trim($message->getMethod() . ' '
|
||||
. $message->getRequestTarget())
|
||||
. ' HTTP/' . $message->getProtocolVersion();
|
||||
if (!$message->hasHeader('host')) {
|
||||
$msg .= "\r\nHost: " . $message->getUri()->getHost();
|
||||
}
|
||||
} elseif ($message instanceof ResponseInterface) {
|
||||
$msg = 'HTTP/' . $message->getProtocolVersion() . ' '
|
||||
. $message->getStatusCode() . ' '
|
||||
. $message->getReasonPhrase();
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Unknown message type');
|
||||
}
|
||||
|
||||
foreach ($message->getHeaders() as $name => $values) {
|
||||
$msg .= "\r\n{$name}: " . implode(', ', $values);
|
||||
}
|
||||
|
||||
return "{$msg}\r\n\r\n" . $message->getBody();
|
||||
return Message::toString($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a UriInterface for the given value.
|
||||
*
|
||||
* This function accepts a string or {@see Psr\Http\Message\UriInterface} and
|
||||
* returns a UriInterface for the given value. If the value is already a
|
||||
* `UriInterface`, it is returned as-is.
|
||||
* This function accepts a string or UriInterface and returns a
|
||||
* UriInterface for the given value. If the value is already a
|
||||
* UriInterface, it is returned as-is.
|
||||
*
|
||||
* @param string|UriInterface $uri
|
||||
*
|
||||
* @return UriInterface
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
*
|
||||
* @deprecated uri_for will be removed in guzzlehttp/psr7:2.0. Use Utils::uriFor instead.
|
||||
*/
|
||||
function uri_for($uri)
|
||||
{
|
||||
if ($uri instanceof UriInterface) {
|
||||
return $uri;
|
||||
} elseif (is_string($uri)) {
|
||||
return new Uri($uri);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('URI must be a string or UriInterface');
|
||||
return Utils::uriFor($uri);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,86 +48,57 @@ function uri_for($uri)
|
||||
* - metadata: Array of custom metadata.
|
||||
* - size: Size of the stream.
|
||||
*
|
||||
* @param resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource Entity body data
|
||||
* This method accepts the following `$resource` types:
|
||||
* - `Psr\Http\Message\StreamInterface`: Returns the value as-is.
|
||||
* - `string`: Creates a stream object that uses the given string as the contents.
|
||||
* - `resource`: Creates a stream object that wraps the given PHP stream resource.
|
||||
* - `Iterator`: If the provided value implements `Iterator`, then a read-only
|
||||
* stream object will be created that wraps the given iterable. Each time the
|
||||
* stream is read from, data from the iterator will fill a buffer and will be
|
||||
* continuously called until the buffer is equal to the requested read size.
|
||||
* Subsequent read calls will first read from the buffer and then call `next`
|
||||
* on the underlying iterator until it is exhausted.
|
||||
* - `object` with `__toString()`: If the object has the `__toString()` method,
|
||||
* the object will be cast to a string and then a stream will be returned that
|
||||
* uses the string value.
|
||||
* - `NULL`: When `null` is passed, an empty stream object is returned.
|
||||
* - `callable` When a callable is passed, a read-only stream object will be
|
||||
* created that invokes the given callable. The callable is invoked with the
|
||||
* number of suggested bytes to read. The callable can return any number of
|
||||
* bytes, but MUST return `false` when there is no more data to return. The
|
||||
* stream object that wraps the callable will invoke the callable until the
|
||||
* number of requested bytes are available. Any additional bytes will be
|
||||
* buffered and used in subsequent reads.
|
||||
*
|
||||
* @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data
|
||||
* @param array $options Additional options
|
||||
*
|
||||
* @return StreamInterface
|
||||
*
|
||||
* @throws \InvalidArgumentException if the $resource arg is not valid.
|
||||
*
|
||||
* @deprecated stream_for will be removed in guzzlehttp/psr7:2.0. Use Utils::streamFor instead.
|
||||
*/
|
||||
function stream_for($resource = '', array $options = [])
|
||||
{
|
||||
if (is_scalar($resource)) {
|
||||
$stream = fopen('php://temp', 'r+');
|
||||
if ($resource !== '') {
|
||||
fwrite($stream, $resource);
|
||||
fseek($stream, 0);
|
||||
}
|
||||
return new Stream($stream, $options);
|
||||
}
|
||||
|
||||
switch (gettype($resource)) {
|
||||
case 'resource':
|
||||
return new Stream($resource, $options);
|
||||
case 'object':
|
||||
if ($resource instanceof StreamInterface) {
|
||||
return $resource;
|
||||
} elseif ($resource instanceof \Iterator) {
|
||||
return new PumpStream(function () use ($resource) {
|
||||
if (!$resource->valid()) {
|
||||
return false;
|
||||
}
|
||||
$result = $resource->current();
|
||||
$resource->next();
|
||||
return $result;
|
||||
}, $options);
|
||||
} elseif (method_exists($resource, '__toString')) {
|
||||
return stream_for((string) $resource, $options);
|
||||
}
|
||||
break;
|
||||
case 'NULL':
|
||||
return new Stream(fopen('php://temp', 'r+'), $options);
|
||||
}
|
||||
|
||||
if (is_callable($resource)) {
|
||||
return new PumpStream($resource, $options);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource));
|
||||
return Utils::streamFor($resource, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse an array of header values containing ";" separated data into an
|
||||
* array of associative arrays representing the header key value pair
|
||||
* data of the header. When a parameter does not contain a value, but just
|
||||
* array of associative arrays representing the header key value pair data
|
||||
* of the header. When a parameter does not contain a value, but just
|
||||
* contains a key, this function will inject a key with a '' string value.
|
||||
*
|
||||
* @param string|array $header Header to parse into components.
|
||||
*
|
||||
* @return array Returns the parsed header values.
|
||||
*
|
||||
* @deprecated parse_header will be removed in guzzlehttp/psr7:2.0. Use Header::parse instead.
|
||||
*/
|
||||
function parse_header($header)
|
||||
{
|
||||
static $trimmed = "\"' \n\t\r";
|
||||
$params = $matches = [];
|
||||
|
||||
foreach (normalize_header($header) as $val) {
|
||||
$part = [];
|
||||
foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) {
|
||||
if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) {
|
||||
$m = $matches[0];
|
||||
if (isset($m[1])) {
|
||||
$part[trim($m[0], $trimmed)] = trim($m[1], $trimmed);
|
||||
} else {
|
||||
$part[] = trim($m[0], $trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($part) {
|
||||
$params[] = $part;
|
||||
}
|
||||
}
|
||||
|
||||
return $params;
|
||||
return Header::parse($header);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,32 +108,20 @@ function parse_header($header)
|
||||
* @param string|array $header Header to normalize.
|
||||
*
|
||||
* @return array Returns the normalized header field values.
|
||||
*
|
||||
* @deprecated normalize_header will be removed in guzzlehttp/psr7:2.0. Use Header::normalize instead.
|
||||
*/
|
||||
function normalize_header($header)
|
||||
{
|
||||
if (!is_array($header)) {
|
||||
return array_map('trim', explode(',', $header));
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($header as $value) {
|
||||
foreach ((array) $value as $v) {
|
||||
if (strpos($v, ',') === false) {
|
||||
$result[] = $v;
|
||||
continue;
|
||||
}
|
||||
foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) {
|
||||
$result[] = trim($vv);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
return Header::normalize($header);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone and modify a request with the given changes.
|
||||
*
|
||||
* This method is useful for reducing the number of clones needed to mutate a
|
||||
* message.
|
||||
*
|
||||
* The changes can be one of:
|
||||
* - method: (string) Changes the HTTP method.
|
||||
* - set_headers: (array) Sets the given headers.
|
||||
@@ -197,72 +135,12 @@ function normalize_header($header)
|
||||
* @param array $changes Changes to apply.
|
||||
*
|
||||
* @return RequestInterface
|
||||
*
|
||||
* @deprecated modify_request will be removed in guzzlehttp/psr7:2.0. Use Utils::modifyRequest instead.
|
||||
*/
|
||||
function modify_request(RequestInterface $request, array $changes)
|
||||
{
|
||||
if (!$changes) {
|
||||
return $request;
|
||||
}
|
||||
|
||||
$headers = $request->getHeaders();
|
||||
|
||||
if (!isset($changes['uri'])) {
|
||||
$uri = $request->getUri();
|
||||
} else {
|
||||
// Remove the host header if one is on the URI
|
||||
if ($host = $changes['uri']->getHost()) {
|
||||
$changes['set_headers']['Host'] = $host;
|
||||
|
||||
if ($port = $changes['uri']->getPort()) {
|
||||
$standardPorts = ['http' => 80, 'https' => 443];
|
||||
$scheme = $changes['uri']->getScheme();
|
||||
if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) {
|
||||
$changes['set_headers']['Host'] .= ':'.$port;
|
||||
}
|
||||
}
|
||||
}
|
||||
$uri = $changes['uri'];
|
||||
}
|
||||
|
||||
if (!empty($changes['remove_headers'])) {
|
||||
$headers = _caseless_remove($changes['remove_headers'], $headers);
|
||||
}
|
||||
|
||||
if (!empty($changes['set_headers'])) {
|
||||
$headers = _caseless_remove(array_keys($changes['set_headers']), $headers);
|
||||
$headers = $changes['set_headers'] + $headers;
|
||||
}
|
||||
|
||||
if (isset($changes['query'])) {
|
||||
$uri = $uri->withQuery($changes['query']);
|
||||
}
|
||||
|
||||
if ($request instanceof ServerRequestInterface) {
|
||||
return (new ServerRequest(
|
||||
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
|
||||
$uri,
|
||||
$headers,
|
||||
isset($changes['body']) ? $changes['body'] : $request->getBody(),
|
||||
isset($changes['version'])
|
||||
? $changes['version']
|
||||
: $request->getProtocolVersion(),
|
||||
$request->getServerParams()
|
||||
))
|
||||
->withParsedBody($request->getParsedBody())
|
||||
->withQueryParams($request->getQueryParams())
|
||||
->withCookieParams($request->getCookieParams())
|
||||
->withUploadedFiles($request->getUploadedFiles());
|
||||
}
|
||||
|
||||
return new Request(
|
||||
isset($changes['method']) ? $changes['method'] : $request->getMethod(),
|
||||
$uri,
|
||||
$headers,
|
||||
isset($changes['body']) ? $changes['body'] : $request->getBody(),
|
||||
isset($changes['version'])
|
||||
? $changes['version']
|
||||
: $request->getProtocolVersion()
|
||||
);
|
||||
return Utils::modifyRequest($request, $changes);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,14 +152,12 @@ function modify_request(RequestInterface $request, array $changes)
|
||||
* @param MessageInterface $message Message to rewind
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*
|
||||
* @deprecated rewind_body will be removed in guzzlehttp/psr7:2.0. Use Message::rewindBody instead.
|
||||
*/
|
||||
function rewind_body(MessageInterface $message)
|
||||
{
|
||||
$body = $message->getBody();
|
||||
|
||||
if ($body->tell()) {
|
||||
$body->rewind();
|
||||
}
|
||||
Message::rewindBody($message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -294,29 +170,14 @@ function rewind_body(MessageInterface $message)
|
||||
* @param string $mode Mode used to open the file
|
||||
*
|
||||
* @return resource
|
||||
*
|
||||
* @throws \RuntimeException if the file cannot be opened
|
||||
*
|
||||
* @deprecated try_fopen will be removed in guzzlehttp/psr7:2.0. Use Utils::tryFopen instead.
|
||||
*/
|
||||
function try_fopen($filename, $mode)
|
||||
{
|
||||
$ex = null;
|
||||
set_error_handler(function () use ($filename, $mode, &$ex) {
|
||||
$ex = new \RuntimeException(sprintf(
|
||||
'Unable to open %s using mode %s: %s',
|
||||
$filename,
|
||||
$mode,
|
||||
func_get_args()[1]
|
||||
));
|
||||
});
|
||||
|
||||
$handle = fopen($filename, $mode);
|
||||
restore_error_handler();
|
||||
|
||||
if ($ex) {
|
||||
/** @var $ex \RuntimeException */
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
return $handle;
|
||||
return Utils::tryFopen($filename, $mode);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,37 +187,16 @@ function try_fopen($filename, $mode)
|
||||
* @param StreamInterface $stream Stream to read
|
||||
* @param int $maxLen Maximum number of bytes to read. Pass -1
|
||||
* to read the entire stream.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @throws \RuntimeException on error.
|
||||
*
|
||||
* @deprecated copy_to_string will be removed in guzzlehttp/psr7:2.0. Use Utils::copyToString instead.
|
||||
*/
|
||||
function copy_to_string(StreamInterface $stream, $maxLen = -1)
|
||||
{
|
||||
$buffer = '';
|
||||
|
||||
if ($maxLen === -1) {
|
||||
while (!$stream->eof()) {
|
||||
$buf = $stream->read(1048576);
|
||||
// Using a loose equality here to match on '' and false.
|
||||
if ($buf == null) {
|
||||
break;
|
||||
}
|
||||
$buffer .= $buf;
|
||||
}
|
||||
return $buffer;
|
||||
}
|
||||
|
||||
$len = 0;
|
||||
while (!$stream->eof() && $len < $maxLen) {
|
||||
$buf = $stream->read($maxLen - $len);
|
||||
// Using a loose equality here to match on '' and false.
|
||||
if ($buf == null) {
|
||||
break;
|
||||
}
|
||||
$buffer .= $buf;
|
||||
$len = strlen($buffer);
|
||||
}
|
||||
|
||||
return $buffer;
|
||||
return Utils::copyToString($stream, $maxLen);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -369,92 +209,48 @@ function copy_to_string(StreamInterface $stream, $maxLen = -1)
|
||||
* to read the entire stream.
|
||||
*
|
||||
* @throws \RuntimeException on error.
|
||||
*
|
||||
* @deprecated copy_to_stream will be removed in guzzlehttp/psr7:2.0. Use Utils::copyToStream instead.
|
||||
*/
|
||||
function copy_to_stream(
|
||||
StreamInterface $source,
|
||||
StreamInterface $dest,
|
||||
$maxLen = -1
|
||||
) {
|
||||
$bufferSize = 8192;
|
||||
|
||||
if ($maxLen === -1) {
|
||||
while (!$source->eof()) {
|
||||
if (!$dest->write($source->read($bufferSize))) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$remaining = $maxLen;
|
||||
while ($remaining > 0 && !$source->eof()) {
|
||||
$buf = $source->read(min($bufferSize, $remaining));
|
||||
$len = strlen($buf);
|
||||
if (!$len) {
|
||||
break;
|
||||
}
|
||||
$remaining -= $len;
|
||||
$dest->write($buf);
|
||||
}
|
||||
}
|
||||
function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)
|
||||
{
|
||||
return Utils::copyToStream($source, $dest, $maxLen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate a hash of a Stream
|
||||
* Calculate a hash of a stream.
|
||||
*
|
||||
* This method reads the entire stream to calculate a rolling hash, based on
|
||||
* PHP's `hash_init` functions.
|
||||
*
|
||||
* @param StreamInterface $stream Stream to calculate the hash for
|
||||
* @param string $algo Hash algorithm (e.g. md5, crc32, etc)
|
||||
* @param bool $rawOutput Whether or not to use raw output
|
||||
*
|
||||
* @return string Returns the hash of the stream
|
||||
*
|
||||
* @throws \RuntimeException on error.
|
||||
*
|
||||
* @deprecated hash will be removed in guzzlehttp/psr7:2.0. Use Utils::hash instead.
|
||||
*/
|
||||
function hash(
|
||||
StreamInterface $stream,
|
||||
$algo,
|
||||
$rawOutput = false
|
||||
) {
|
||||
$pos = $stream->tell();
|
||||
|
||||
if ($pos > 0) {
|
||||
$stream->rewind();
|
||||
}
|
||||
|
||||
$ctx = hash_init($algo);
|
||||
while (!$stream->eof()) {
|
||||
hash_update($ctx, $stream->read(1048576));
|
||||
}
|
||||
|
||||
$out = hash_final($ctx, (bool) $rawOutput);
|
||||
$stream->seek($pos);
|
||||
|
||||
return $out;
|
||||
function hash(StreamInterface $stream, $algo, $rawOutput = false)
|
||||
{
|
||||
return Utils::hash($stream, $algo, $rawOutput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a line from the stream up to the maximum allowed buffer length
|
||||
* Read a line from the stream up to the maximum allowed buffer length.
|
||||
*
|
||||
* @param StreamInterface $stream Stream to read from
|
||||
* @param int $maxLength Maximum buffer length
|
||||
* @param int|null $maxLength Maximum buffer length
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @deprecated readline will be removed in guzzlehttp/psr7:2.0. Use Utils::readLine instead.
|
||||
*/
|
||||
function readline(StreamInterface $stream, $maxLength = null)
|
||||
{
|
||||
$buffer = '';
|
||||
$size = 0;
|
||||
|
||||
while (!$stream->eof()) {
|
||||
// Using a loose equality here to match on '' and false.
|
||||
if (null == ($byte = $stream->read(1))) {
|
||||
return $buffer;
|
||||
}
|
||||
$buffer .= $byte;
|
||||
// Break when a new line is found or the max length - 1 is reached
|
||||
if ($byte === "\n" || ++$size === $maxLength - 1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $buffer;
|
||||
return Utils::readLine($stream, $maxLength);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -463,26 +259,12 @@ function readline(StreamInterface $stream, $maxLength = null)
|
||||
* @param string $message Request message string.
|
||||
*
|
||||
* @return Request
|
||||
*
|
||||
* @deprecated parse_request will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequest instead.
|
||||
*/
|
||||
function parse_request($message)
|
||||
{
|
||||
$data = _parse_message($message);
|
||||
$matches = [];
|
||||
if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) {
|
||||
throw new \InvalidArgumentException('Invalid request string');
|
||||
}
|
||||
$parts = explode(' ', $data['start-line'], 3);
|
||||
$version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
|
||||
|
||||
$request = new Request(
|
||||
$parts[0],
|
||||
$matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1],
|
||||
$data['headers'],
|
||||
$data['body'],
|
||||
$version
|
||||
);
|
||||
|
||||
return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
|
||||
return Message::parseRequest($message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -491,139 +273,67 @@ function parse_request($message)
|
||||
* @param string $message Response message string.
|
||||
*
|
||||
* @return Response
|
||||
*
|
||||
* @deprecated parse_response will be removed in guzzlehttp/psr7:2.0. Use Message::parseResponse instead.
|
||||
*/
|
||||
function parse_response($message)
|
||||
{
|
||||
$data = _parse_message($message);
|
||||
// According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space
|
||||
// between status-code and reason-phrase is required. But browsers accept
|
||||
// responses without space and reason as well.
|
||||
if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) {
|
||||
throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']);
|
||||
}
|
||||
$parts = explode(' ', $data['start-line'], 3);
|
||||
|
||||
return new Response(
|
||||
$parts[1],
|
||||
$data['headers'],
|
||||
$data['body'],
|
||||
explode('/', $parts[0])[1],
|
||||
isset($parts[2]) ? $parts[2] : null
|
||||
);
|
||||
return Message::parseResponse($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a query string into an associative array.
|
||||
*
|
||||
* If multiple values are found for the same key, the value of that key
|
||||
* value pair will become an array. This function does not parse nested
|
||||
* PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will
|
||||
* be parsed into ['foo[a]' => '1', 'foo[b]' => '2']).
|
||||
* If multiple values are found for the same key, the value of that key value
|
||||
* pair will become an array. This function does not parse nested PHP style
|
||||
* arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed
|
||||
* into `['foo[a]' => '1', 'foo[b]' => '2'])`.
|
||||
*
|
||||
* @param string $str Query string to parse
|
||||
* @param int|bool $urlEncoding How the query string is encoded
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @deprecated parse_query will be removed in guzzlehttp/psr7:2.0. Use Query::parse instead.
|
||||
*/
|
||||
function parse_query($str, $urlEncoding = true)
|
||||
{
|
||||
$result = [];
|
||||
|
||||
if ($str === '') {
|
||||
return $result;
|
||||
}
|
||||
|
||||
if ($urlEncoding === true) {
|
||||
$decoder = function ($value) {
|
||||
return rawurldecode(str_replace('+', ' ', $value));
|
||||
};
|
||||
} elseif ($urlEncoding === PHP_QUERY_RFC3986) {
|
||||
$decoder = 'rawurldecode';
|
||||
} elseif ($urlEncoding === PHP_QUERY_RFC1738) {
|
||||
$decoder = 'urldecode';
|
||||
} else {
|
||||
$decoder = function ($str) { return $str; };
|
||||
}
|
||||
|
||||
foreach (explode('&', $str) as $kvp) {
|
||||
$parts = explode('=', $kvp, 2);
|
||||
$key = $decoder($parts[0]);
|
||||
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
|
||||
if (!isset($result[$key])) {
|
||||
$result[$key] = $value;
|
||||
} else {
|
||||
if (!is_array($result[$key])) {
|
||||
$result[$key] = [$result[$key]];
|
||||
}
|
||||
$result[$key][] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
return Query::parse($str, $urlEncoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a query string from an array of key value pairs.
|
||||
*
|
||||
* This function can use the return value of parse_query() to build a query
|
||||
* This function can use the return value of `parse_query()` to build a query
|
||||
* string. This function does not modify the provided keys when an array is
|
||||
* encountered (like http_build_query would).
|
||||
* encountered (like `http_build_query()` would).
|
||||
*
|
||||
* @param array $params Query string parameters.
|
||||
* @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
|
||||
* to encode using RFC3986, or PHP_QUERY_RFC1738
|
||||
* to encode using RFC1738.
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @deprecated build_query will be removed in guzzlehttp/psr7:2.0. Use Query::build instead.
|
||||
*/
|
||||
function build_query(array $params, $encoding = PHP_QUERY_RFC3986)
|
||||
{
|
||||
if (!$params) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($encoding === false) {
|
||||
$encoder = function ($str) { return $str; };
|
||||
} elseif ($encoding === PHP_QUERY_RFC3986) {
|
||||
$encoder = 'rawurlencode';
|
||||
} elseif ($encoding === PHP_QUERY_RFC1738) {
|
||||
$encoder = 'urlencode';
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Invalid type');
|
||||
}
|
||||
|
||||
$qs = '';
|
||||
foreach ($params as $k => $v) {
|
||||
$k = $encoder($k);
|
||||
if (!is_array($v)) {
|
||||
$qs .= $k;
|
||||
if ($v !== null) {
|
||||
$qs .= '=' . $encoder($v);
|
||||
}
|
||||
$qs .= '&';
|
||||
} else {
|
||||
foreach ($v as $vv) {
|
||||
$qs .= $k;
|
||||
if ($vv !== null) {
|
||||
$qs .= '=' . $encoder($vv);
|
||||
}
|
||||
$qs .= '&';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $qs ? (string) substr($qs, 0, -1) : '';
|
||||
return Query::build($params, $encoding);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the mimetype of a file by looking at its extension.
|
||||
*
|
||||
* @param $filename
|
||||
* @param string $filename
|
||||
*
|
||||
* @return null|string
|
||||
* @return string|null
|
||||
*
|
||||
* @deprecated mimetype_from_filename will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromFilename instead.
|
||||
*/
|
||||
function mimetype_from_filename($filename)
|
||||
{
|
||||
return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION));
|
||||
return MimeType::fromFilename($filename);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -632,119 +342,13 @@ function mimetype_from_filename($filename)
|
||||
* @param $extension string The file extension.
|
||||
*
|
||||
* @return string|null
|
||||
*
|
||||
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
|
||||
* @deprecated mimetype_from_extension will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromExtension instead.
|
||||
*/
|
||||
function mimetype_from_extension($extension)
|
||||
{
|
||||
static $mimetypes = [
|
||||
'3gp' => 'video/3gpp',
|
||||
'7z' => 'application/x-7z-compressed',
|
||||
'aac' => 'audio/x-aac',
|
||||
'ai' => 'application/postscript',
|
||||
'aif' => 'audio/x-aiff',
|
||||
'asc' => 'text/plain',
|
||||
'asf' => 'video/x-ms-asf',
|
||||
'atom' => 'application/atom+xml',
|
||||
'avi' => 'video/x-msvideo',
|
||||
'bmp' => 'image/bmp',
|
||||
'bz2' => 'application/x-bzip2',
|
||||
'cer' => 'application/pkix-cert',
|
||||
'crl' => 'application/pkix-crl',
|
||||
'crt' => 'application/x-x509-ca-cert',
|
||||
'css' => 'text/css',
|
||||
'csv' => 'text/csv',
|
||||
'cu' => 'application/cu-seeme',
|
||||
'deb' => 'application/x-debian-package',
|
||||
'doc' => 'application/msword',
|
||||
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'dvi' => 'application/x-dvi',
|
||||
'eot' => 'application/vnd.ms-fontobject',
|
||||
'eps' => 'application/postscript',
|
||||
'epub' => 'application/epub+zip',
|
||||
'etx' => 'text/x-setext',
|
||||
'flac' => 'audio/flac',
|
||||
'flv' => 'video/x-flv',
|
||||
'gif' => 'image/gif',
|
||||
'gz' => 'application/gzip',
|
||||
'htm' => 'text/html',
|
||||
'html' => 'text/html',
|
||||
'ico' => 'image/x-icon',
|
||||
'ics' => 'text/calendar',
|
||||
'ini' => 'text/plain',
|
||||
'iso' => 'application/x-iso9660-image',
|
||||
'jar' => 'application/java-archive',
|
||||
'jpe' => 'image/jpeg',
|
||||
'jpeg' => 'image/jpeg',
|
||||
'jpg' => 'image/jpeg',
|
||||
'js' => 'text/javascript',
|
||||
'json' => 'application/json',
|
||||
'latex' => 'application/x-latex',
|
||||
'log' => 'text/plain',
|
||||
'm4a' => 'audio/mp4',
|
||||
'm4v' => 'video/mp4',
|
||||
'mid' => 'audio/midi',
|
||||
'midi' => 'audio/midi',
|
||||
'mov' => 'video/quicktime',
|
||||
'mkv' => 'video/x-matroska',
|
||||
'mp3' => 'audio/mpeg',
|
||||
'mp4' => 'video/mp4',
|
||||
'mp4a' => 'audio/mp4',
|
||||
'mp4v' => 'video/mp4',
|
||||
'mpe' => 'video/mpeg',
|
||||
'mpeg' => 'video/mpeg',
|
||||
'mpg' => 'video/mpeg',
|
||||
'mpg4' => 'video/mp4',
|
||||
'oga' => 'audio/ogg',
|
||||
'ogg' => 'audio/ogg',
|
||||
'ogv' => 'video/ogg',
|
||||
'ogx' => 'application/ogg',
|
||||
'pbm' => 'image/x-portable-bitmap',
|
||||
'pdf' => 'application/pdf',
|
||||
'pgm' => 'image/x-portable-graymap',
|
||||
'png' => 'image/png',
|
||||
'pnm' => 'image/x-portable-anymap',
|
||||
'ppm' => 'image/x-portable-pixmap',
|
||||
'ppt' => 'application/vnd.ms-powerpoint',
|
||||
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'ps' => 'application/postscript',
|
||||
'qt' => 'video/quicktime',
|
||||
'rar' => 'application/x-rar-compressed',
|
||||
'ras' => 'image/x-cmu-raster',
|
||||
'rss' => 'application/rss+xml',
|
||||
'rtf' => 'application/rtf',
|
||||
'sgm' => 'text/sgml',
|
||||
'sgml' => 'text/sgml',
|
||||
'svg' => 'image/svg+xml',
|
||||
'swf' => 'application/x-shockwave-flash',
|
||||
'tar' => 'application/x-tar',
|
||||
'tif' => 'image/tiff',
|
||||
'tiff' => 'image/tiff',
|
||||
'torrent' => 'application/x-bittorrent',
|
||||
'ttf' => 'application/x-font-ttf',
|
||||
'txt' => 'text/plain',
|
||||
'wav' => 'audio/x-wav',
|
||||
'webm' => 'video/webm',
|
||||
'webp' => 'image/webp',
|
||||
'wma' => 'audio/x-ms-wma',
|
||||
'wmv' => 'video/x-ms-wmv',
|
||||
'woff' => 'application/x-font-woff',
|
||||
'wsdl' => 'application/wsdl+xml',
|
||||
'xbm' => 'image/x-xbitmap',
|
||||
'xls' => 'application/vnd.ms-excel',
|
||||
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'xml' => 'application/xml',
|
||||
'xpm' => 'image/x-xpixmap',
|
||||
'xwd' => 'image/x-xwindowdump',
|
||||
'yaml' => 'text/yaml',
|
||||
'yml' => 'text/yaml',
|
||||
'zip' => 'application/zip',
|
||||
];
|
||||
|
||||
$extension = strtolower($extension);
|
||||
|
||||
return isset($mimetypes[$extension])
|
||||
? $mimetypes[$extension]
|
||||
: null;
|
||||
return MimeType::fromExtension($extension);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -757,61 +361,14 @@ function mimetype_from_extension($extension)
|
||||
* @param string $message HTTP request or response to parse.
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @deprecated _parse_message will be removed in guzzlehttp/psr7:2.0. Use Message::parseMessage instead.
|
||||
*/
|
||||
function _parse_message($message)
|
||||
{
|
||||
if (!$message) {
|
||||
throw new \InvalidArgumentException('Invalid message');
|
||||
}
|
||||
|
||||
$message = ltrim($message, "\r\n");
|
||||
|
||||
$messageParts = preg_split("/\r?\n\r?\n/", $message, 2);
|
||||
|
||||
if ($messageParts === false || count($messageParts) !== 2) {
|
||||
throw new \InvalidArgumentException('Invalid message: Missing header delimiter');
|
||||
}
|
||||
|
||||
list($rawHeaders, $body) = $messageParts;
|
||||
$rawHeaders .= "\r\n"; // Put back the delimiter we split previously
|
||||
$headerParts = preg_split("/\r?\n/", $rawHeaders, 2);
|
||||
|
||||
if ($headerParts === false || count($headerParts) !== 2) {
|
||||
throw new \InvalidArgumentException('Invalid message: Missing status line');
|
||||
}
|
||||
|
||||
list($startLine, $rawHeaders) = $headerParts;
|
||||
|
||||
if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') {
|
||||
// Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0
|
||||
$rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders);
|
||||
}
|
||||
|
||||
/** @var array[] $headerLines */
|
||||
$count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER);
|
||||
|
||||
// If these aren't the same, then one line didn't match and there's an invalid header.
|
||||
if ($count !== substr_count($rawHeaders, "\n")) {
|
||||
// Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4
|
||||
if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) {
|
||||
throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding');
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('Invalid header syntax');
|
||||
}
|
||||
|
||||
$headers = [];
|
||||
|
||||
foreach ($headerLines as $headerLine) {
|
||||
$headers[$headerLine[1]][] = $headerLine[2];
|
||||
}
|
||||
|
||||
return [
|
||||
'start-line' => $startLine,
|
||||
'headers' => $headers,
|
||||
'body' => $body,
|
||||
];
|
||||
return Message::parseMessage($message);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -821,79 +378,45 @@ function _parse_message($message)
|
||||
* @param array $headers Array of headers (each value an array).
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @deprecated _parse_request_uri will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequestUri instead.
|
||||
*/
|
||||
function _parse_request_uri($path, array $headers)
|
||||
{
|
||||
$hostKey = array_filter(array_keys($headers), function ($k) {
|
||||
return strtolower($k) === 'host';
|
||||
});
|
||||
|
||||
// If no host is found, then a full URI cannot be constructed.
|
||||
if (!$hostKey) {
|
||||
return $path;
|
||||
}
|
||||
|
||||
$host = $headers[reset($hostKey)][0];
|
||||
$scheme = substr($host, -4) === ':443' ? 'https' : 'http';
|
||||
|
||||
return $scheme . '://' . $host . '/' . ltrim($path, '/');
|
||||
return Message::parseRequestUri($path, $headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a short summary of the message body
|
||||
* Get a short summary of the message body.
|
||||
*
|
||||
* Will return `null` if the response is not printable.
|
||||
*
|
||||
* @param MessageInterface $message The message to get the body summary
|
||||
* @param int $truncateAt The maximum allowed size of the summary
|
||||
*
|
||||
* @return null|string
|
||||
* @return string|null
|
||||
*
|
||||
* @deprecated get_message_body_summary will be removed in guzzlehttp/psr7:2.0. Use Message::bodySummary instead.
|
||||
*/
|
||||
function get_message_body_summary(MessageInterface $message, $truncateAt = 120)
|
||||
{
|
||||
$body = $message->getBody();
|
||||
|
||||
if (!$body->isSeekable() || !$body->isReadable()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$size = $body->getSize();
|
||||
|
||||
if ($size === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$summary = $body->read($truncateAt);
|
||||
$body->rewind();
|
||||
|
||||
if ($size > $truncateAt) {
|
||||
$summary .= ' (truncated...)';
|
||||
}
|
||||
|
||||
// Matches any printable character, including unicode characters:
|
||||
// letters, marks, numbers, punctuation, spacing, and separators.
|
||||
if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/', $summary)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $summary;
|
||||
return Message::bodySummary($message, $truncateAt);
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
/**
|
||||
* Remove the items given by the keys, case insensitively from the data.
|
||||
*
|
||||
* @param iterable<string> $keys
|
||||
*
|
||||
* @return array
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @deprecated _caseless_remove will be removed in guzzlehttp/psr7:2.0. Use Utils::caselessRemove instead.
|
||||
*/
|
||||
function _caseless_remove($keys, array $data)
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach ($keys as &$key) {
|
||||
$key = strtolower($key);
|
||||
}
|
||||
|
||||
foreach ($data as $k => $v) {
|
||||
if (!in_array(strtolower($k), $keys)) {
|
||||
$result[$k] = $v;
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
return Utils::caselessRemove($keys, $data);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user