Essai au propre

This commit is contained in:
Gauvain Boiché
2020-04-01 16:45:39 +02:00
parent f282fd0d32
commit 745270ab61
1538 changed files with 80 additions and 351590 deletions

View File

@@ -1,148 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* Represents the result of a batch operation. This result container is
* iterable, countable, and you can can get a result by value using the
* getResult function.
*
* Successful results are anything other than exceptions. Failure results are
* exceptions.
*
* @package GuzzleHttp
*/
class BatchResults implements \Countable, \IteratorAggregate, \ArrayAccess
{
private $hash;
/**
* @param \SplObjectStorage $hash Hash of key objects to result values.
*/
public function __construct(\SplObjectStorage $hash)
{
$this->hash = $hash;
}
/**
* Get the keys that are available on the batch result.
*
* @return array
*/
public function getKeys()
{
return iterator_to_array($this->hash);
}
/**
* Gets a result from the container for the given object. When getting
* results for a batch of requests, provide the request object.
*
* @param object $forObject Object to retrieve the result for.
*
* @return mixed|null
*/
public function getResult($forObject)
{
return isset($this->hash[$forObject]) ? $this->hash[$forObject] : null;
}
/**
* Get an array of successful results.
*
* @return array
*/
public function getSuccessful()
{
$results = [];
foreach ($this->hash as $key) {
if (!($this->hash[$key] instanceof \Exception)) {
$results[] = $this->hash[$key];
}
}
return $results;
}
/**
* Get an array of failed results.
*
* @return array
*/
public function getFailures()
{
$results = [];
foreach ($this->hash as $key) {
if ($this->hash[$key] instanceof \Exception) {
$results[] = $this->hash[$key];
}
}
return $results;
}
/**
* Allows iteration over all batch result values.
*
* @return \ArrayIterator
*/
public function getIterator()
{
$results = [];
foreach ($this->hash as $key) {
$results[] = $this->hash[$key];
}
return new \ArrayIterator($results);
}
/**
* Counts the number of elements in the batch result.
*
* @return int
*/
public function count()
{
return count($this->hash);
}
/**
* Checks if the batch contains a specific numerical array index.
*
* @param int $key Index to access
*
* @return bool
*/
public function offsetExists($key)
{
return $key < count($this->hash);
}
/**
* Allows access of the batch using a numerical array index.
*
* @param int $key Index to access.
*
* @return mixed|null
*/
public function offsetGet($key)
{
$i = -1;
foreach ($this->hash as $obj) {
if ($key === ++$i) {
return $this->hash[$obj];
}
}
return null;
}
public function offsetUnset($key)
{
throw new \RuntimeException('Not implemented');
}
public function offsetSet($key, $value)
{
throw new \RuntimeException('Not implemented');
}
}

View File

@@ -1,236 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* Key value pair collection object
*/
class Collection implements
\ArrayAccess,
\IteratorAggregate,
\Countable,
ToArrayInterface
{
use HasDataTrait;
/**
* @param array $data Associative array of data to set
*/
public function __construct(array $data = [])
{
$this->data = $data;
}
/**
* Create a new collection from an array, validate the keys, and add default
* values where missing
*
* @param array $config Configuration values to apply.
* @param array $defaults Default parameters
* @param array $required Required parameter names
*
* @return self
* @throws \InvalidArgumentException if a parameter is missing
*/
public static function fromConfig(
array $config = [],
array $defaults = [],
array $required = []
) {
$data = $config + $defaults;
if ($missing = array_diff($required, array_keys($data))) {
throw new \InvalidArgumentException(
'Config is missing the following keys: ' .
implode(', ', $missing));
}
return new self($data);
}
/**
* Removes all key value pairs
*/
public function clear()
{
$this->data = [];
}
/**
* Get a specific key value.
*
* @param string $key Key to retrieve.
*
* @return mixed|null Value of the key or NULL
*/
public function get($key)
{
return isset($this->data[$key]) ? $this->data[$key] : null;
}
/**
* Set a key value pair
*
* @param string $key Key to set
* @param mixed $value Value to set
*/
public function set($key, $value)
{
$this->data[$key] = $value;
}
/**
* Add a value to a key. If a key of the same name has already been added,
* the key value will be converted into an array and the new value will be
* pushed to the end of the array.
*
* @param string $key Key to add
* @param mixed $value Value to add to the key
*/
public function add($key, $value)
{
if (!array_key_exists($key, $this->data)) {
$this->data[$key] = $value;
} elseif (is_array($this->data[$key])) {
$this->data[$key][] = $value;
} else {
$this->data[$key] = array($this->data[$key], $value);
}
}
/**
* Remove a specific key value pair
*
* @param string $key A key to remove
*/
public function remove($key)
{
unset($this->data[$key]);
}
/**
* Get all keys in the collection
*
* @return array
*/
public function getKeys()
{
return array_keys($this->data);
}
/**
* Returns whether or not the specified key is present.
*
* @param string $key The key for which to check the existence.
*
* @return bool
*/
public function hasKey($key)
{
return array_key_exists($key, $this->data);
}
/**
* Checks if any keys contains a certain value
*
* @param string $value Value to search for
*
* @return mixed Returns the key if the value was found FALSE if the value
* was not found.
*/
public function hasValue($value)
{
return array_search($value, $this->data, true);
}
/**
* Replace the data of the object with the value of an array
*
* @param array $data Associative array of data
*/
public function replace(array $data)
{
$this->data = $data;
}
/**
* Add and merge in a Collection or array of key value pair data.
*
* @param Collection|array $data Associative array of key value pair data
*/
public function merge($data)
{
foreach ($data as $key => $value) {
$this->add($key, $value);
}
}
/**
* Overwrite key value pairs in this collection with all of the data from
* an array or collection.
*
* @param array|\Traversable $data Values to override over this config
*/
public function overwriteWith($data)
{
if (is_array($data)) {
$this->data = $data + $this->data;
} elseif ($data instanceof Collection) {
$this->data = $data->toArray() + $this->data;
} else {
foreach ($data as $key => $value) {
$this->data[$key] = $value;
}
}
}
/**
* Returns a Collection containing all the elements of the collection after
* applying the callback function to each one.
*
* The callable should accept three arguments:
* - (string) $key
* - (string) $value
* - (array) $context
*
* The callable must return a the altered or unaltered value.
*
* @param callable $closure Map function to apply
* @param array $context Context to pass to the callable
*
* @return Collection
*/
public function map(callable $closure, array $context = [])
{
$collection = new static();
foreach ($this as $key => $value) {
$collection[$key] = $closure($key, $value, $context);
}
return $collection;
}
/**
* Iterates over each key value pair in the collection passing them to the
* callable. If the callable returns true, the current value from input is
* returned into the result Collection.
*
* The callable must accept two arguments:
* - (string) $key
* - (string) $value
*
* @param callable $closure Evaluation function
*
* @return Collection
*/
public function filter(callable $closure)
{
$collection = new static();
foreach ($this->data as $key => $value) {
if ($closure($key, $value)) {
$collection[$key] = $value;
}
}
return $collection;
}
}

View File

@@ -1,20 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Basic event class that can be extended.
*/
abstract class AbstractEvent implements EventInterface
{
private $propagationStopped = false;
public function isPropagationStopped()
{
return $this->propagationStopped;
}
public function stopPropagation()
{
$this->propagationStopped = true;
}
}

View File

@@ -1,61 +0,0 @@
<?php
namespace GuzzleHttp\Event;
use GuzzleHttp\Transaction;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Message\RequestInterface;
/**
* Base class for request events, providing a request and client getter.
*/
abstract class AbstractRequestEvent extends AbstractEvent
{
/** @var Transaction */
protected $transaction;
/**
* @param Transaction $transaction
*/
public function __construct(Transaction $transaction)
{
$this->transaction = $transaction;
}
/**
* Get the HTTP client associated with the event.
*
* @return ClientInterface
*/
public function getClient()
{
return $this->transaction->client;
}
/**
* Get the request object
*
* @return RequestInterface
*/
public function getRequest()
{
return $this->transaction->request;
}
/**
* Get the number of transaction retries.
*
* @return int
*/
public function getRetryCount()
{
return $this->transaction->retries;
}
/**
* @return Transaction
*/
public function getTransaction()
{
return $this->transaction;
}
}

View File

@@ -1,40 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Abstract request event that can be retried.
*/
class AbstractRetryableEvent extends AbstractTransferEvent
{
/**
* Mark the request as needing a retry and stop event propagation.
*
* This action allows you to retry a request without emitting the "end"
* event multiple times for a given request. When retried, the request
* emits a before event and is then sent again using the client that sent
* the original request.
*
* When retrying, it is important to limit the number of retries you allow
* to prevent infinite loops.
*
* This action can only be taken during the "complete" and "error" events.
*
* @param int $afterDelay If specified, the amount of time in milliseconds
* to delay before retrying. Note that this must
* be supported by the underlying RingPHP handler
* to work properly. Set to 0 or provide no value
* to retry immediately.
*/
public function retry($afterDelay = 0)
{
// Setting the transition state to 'retry' will cause the next state
// transition of the transaction to retry the request.
$this->transaction->state = 'retry';
if ($afterDelay) {
$this->transaction->request->getConfig()->set('delay', $afterDelay);
}
$this->stopPropagation();
}
}

View File

@@ -1,63 +0,0 @@
<?php
namespace GuzzleHttp\Event;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Ring\Future\FutureInterface;
/**
* Event that contains transfer statistics, and can be intercepted.
*/
abstract class AbstractTransferEvent extends AbstractRequestEvent
{
/**
* Get all transfer information as an associative array if no $name
* argument is supplied, or gets a specific transfer statistic if
* a $name attribute is supplied (e.g., 'total_time').
*
* @param string $name Name of the transfer stat to retrieve
*
* @return mixed|null|array
*/
public function getTransferInfo($name = null)
{
if (!$name) {
return $this->transaction->transferInfo;
}
return isset($this->transaction->transferInfo[$name])
? $this->transaction->transferInfo[$name]
: null;
}
/**
* Returns true/false if a response is available.
*
* @return bool
*/
public function hasResponse()
{
return !($this->transaction->response instanceof FutureInterface);
}
/**
* Get the response.
*
* @return ResponseInterface|null
*/
public function getResponse()
{
return $this->hasResponse() ? $this->transaction->response : null;
}
/**
* Intercept the request and associate a response
*
* @param ResponseInterface $response Response to set
*/
public function intercept(ResponseInterface $response)
{
$this->transaction->response = $response;
$this->transaction->exception = null;
$this->stopPropagation();
}
}

View File

@@ -1,26 +0,0 @@
<?php
namespace GuzzleHttp\Event;
use GuzzleHttp\Message\ResponseInterface;
/**
* Event object emitted before a request is sent.
*
* This event MAY be emitted multiple times (i.e., if a request is retried).
* You MAY change the Response associated with the request using the
* intercept() method of the event.
*/
class BeforeEvent extends AbstractRequestEvent
{
/**
* Intercept the request and associate a response
*
* @param ResponseInterface $response Response to set
*/
public function intercept(ResponseInterface $response)
{
$this->transaction->response = $response;
$this->transaction->exception = null;
$this->stopPropagation();
}
}

View File

@@ -1,14 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Event object emitted after a request has been completed.
*
* This event MAY be emitted multiple times for a single request. You MAY
* change the Response associated with the request using the intercept()
* method of the event.
*
* This event allows the request to be retried if necessary using the retry()
* method of the event.
*/
class CompleteEvent extends AbstractRetryableEvent {}

View File

@@ -1,145 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Guzzle event emitter.
*
* Some of this class is based on the Symfony EventDispatcher component, which
* ships with the following license:
*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @link https://github.com/symfony/symfony/tree/master/src/Symfony/Component/EventDispatcher
*/
class Emitter implements EmitterInterface
{
/** @var array */
private $listeners = [];
/** @var array */
private $sorted = [];
public function on($eventName, callable $listener, $priority = 0)
{
if ($priority === 'first') {
$priority = isset($this->listeners[$eventName])
? max(array_keys($this->listeners[$eventName])) + 1
: 1;
} elseif ($priority === 'last') {
$priority = isset($this->listeners[$eventName])
? min(array_keys($this->listeners[$eventName])) - 1
: -1;
}
$this->listeners[$eventName][$priority][] = $listener;
unset($this->sorted[$eventName]);
}
public function once($eventName, callable $listener, $priority = 0)
{
$onceListener = function (
EventInterface $event
) use (&$onceListener, $eventName, $listener, $priority) {
$this->removeListener($eventName, $onceListener);
$listener($event, $eventName);
};
$this->on($eventName, $onceListener, $priority);
}
public function removeListener($eventName, callable $listener)
{
if (empty($this->listeners[$eventName])) {
return;
}
foreach ($this->listeners[$eventName] as $priority => $listeners) {
if (false !== ($key = array_search($listener, $listeners, true))) {
unset(
$this->listeners[$eventName][$priority][$key],
$this->sorted[$eventName]
);
}
}
}
public function listeners($eventName = null)
{
// Return all events in a sorted priority order
if ($eventName === null) {
foreach (array_keys($this->listeners) as $eventName) {
if (empty($this->sorted[$eventName])) {
$this->listeners($eventName);
}
}
return $this->sorted;
}
// Return the listeners for a specific event, sorted in priority order
if (empty($this->sorted[$eventName])) {
$this->sorted[$eventName] = [];
if (isset($this->listeners[$eventName])) {
krsort($this->listeners[$eventName], SORT_NUMERIC);
foreach ($this->listeners[$eventName] as $listeners) {
foreach ($listeners as $listener) {
$this->sorted[$eventName][] = $listener;
}
}
}
}
return $this->sorted[$eventName];
}
public function hasListeners($eventName)
{
return !empty($this->listeners[$eventName]);
}
public function emit($eventName, EventInterface $event)
{
if (isset($this->listeners[$eventName])) {
foreach ($this->listeners($eventName) as $listener) {
$listener($event, $eventName);
if ($event->isPropagationStopped()) {
break;
}
}
}
return $event;
}
public function attach(SubscriberInterface $subscriber)
{
foreach ($subscriber->getEvents() as $eventName => $listeners) {
if (is_array($listeners[0])) {
foreach ($listeners as $listener) {
$this->on(
$eventName,
[$subscriber, $listener[0]],
isset($listener[1]) ? $listener[1] : 0
);
}
} else {
$this->on(
$eventName,
[$subscriber, $listeners[0]],
isset($listeners[1]) ? $listeners[1] : 0
);
}
}
}
public function detach(SubscriberInterface $subscriber)
{
foreach ($subscriber->getEvents() as $eventName => $listener) {
$this->removeListener($eventName, [$subscriber, $listener[0]]);
}
}
}

View File

@@ -1,96 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Guzzle event emitter.
*/
interface EmitterInterface
{
/**
* Binds a listener to a specific event.
*
* @param string $eventName Name of the event to bind to.
* @param callable $listener Listener to invoke when triggered.
* @param int|string $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0). You can
* pass "first" or "last" to dynamically specify the event priority
* based on the current event priorities associated with the given
* event name in the emitter. Use "first" to set the priority to the
* current highest priority plus one. Use "last" to set the priority to
* the current lowest event priority minus one.
*/
public function on($eventName, callable $listener, $priority = 0);
/**
* Binds a listener to a specific event. After the listener is triggered
* once, it is removed as a listener.
*
* @param string $eventName Name of the event to bind to.
* @param callable $listener Listener to invoke when triggered.
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function once($eventName, callable $listener, $priority = 0);
/**
* Removes an event listener from the specified event.
*
* @param string $eventName The event to remove a listener from
* @param callable $listener The listener to remove
*/
public function removeListener($eventName, callable $listener);
/**
* Gets the listeners of a specific event or all listeners if no event is
* specified.
*
* @param string $eventName The name of the event. Pass null (the default)
* to retrieve all listeners.
*
* @return array The event listeners for the specified event, or all event
* listeners by event name. The format of the array when retrieving a
* specific event list is an array of callables. The format of the array
* when retrieving all listeners is an associative array of arrays of
* callables.
*/
public function listeners($eventName = null);
/**
* Checks if the emitter has listeners by the given name.
*
* @param string $eventName The name of the event to check.
*
* @return bool
*/
public function hasListeners($eventName);
/**
* Emits an event to all registered listeners.
*
* Each event that is bound to the emitted eventName receives a
* EventInterface, the name of the event, and the event emitter.
*
* @param string $eventName The name of the event to dispatch.
* @param EventInterface $event The event to pass to the event handlers/listeners.
*
* @return EventInterface Returns the provided event object
*/
public function emit($eventName, EventInterface $event);
/**
* Attaches an event subscriber.
*
* The subscriber is asked for all the events it is interested in and added
* as an event listener for each event.
*
* @param SubscriberInterface $subscriber Subscriber to attach.
*/
public function attach(SubscriberInterface $subscriber);
/**
* Detaches an event subscriber.
*
* @param SubscriberInterface $subscriber Subscriber to detach.
*/
public function detach(SubscriberInterface $subscriber);
}

View File

@@ -1,28 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* A terminal event that is emitted when a request transaction has ended.
*
* This event is emitted for both successful responses and responses that
* encountered an exception. You need to check if an exception is present
* in your listener to know the difference.
*
* You MAY intercept the response associated with the event if needed, but keep
* in mind that the "complete" event will not be triggered as a result.
*/
class EndEvent extends AbstractTransferEvent
{
/**
* Get the exception that was encountered (if any).
*
* This method should be used to check if the request was sent successfully
* or if it encountered errors.
*
* @return \Exception|null
*/
public function getException()
{
return $this->transaction->exception;
}
}

View File

@@ -1,27 +0,0 @@
<?php
namespace GuzzleHttp\Event;
use GuzzleHttp\Exception\RequestException;
/**
* Event emitted when an error occurs while sending a request.
*
* This event MAY be emitted multiple times. You MAY intercept the exception
* and inject a response into the event to rescue the request using the
* intercept() method of the event.
*
* This event allows the request to be retried using the "retry" method of the
* event.
*/
class ErrorEvent extends AbstractRetryableEvent
{
/**
* Get the exception that was encountered
*
* @return RequestException
*/
public function getException()
{
return $this->transaction->exception;
}
}

View File

@@ -1,23 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Base event interface used when dispatching events to listeners using an
* event emitter.
*/
interface EventInterface
{
/**
* Returns whether or not stopPropagation was called on the event.
*
* @return bool
* @see Event::stopPropagation
*/
public function isPropagationStopped();
/**
* Stops the propagation of the event, preventing subsequent listeners
* registered to the same event from being invoked.
*/
public function stopPropagation();
}

View File

@@ -1,15 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Holds an event emitter
*/
interface HasEmitterInterface
{
/**
* Get the event emitter of the object
*
* @return EmitterInterface
*/
public function getEmitter();
}

View File

@@ -1,20 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Trait that implements the methods of HasEmitterInterface
*/
trait HasEmitterTrait
{
/** @var EmitterInterface */
private $emitter;
public function getEmitter()
{
if (!$this->emitter) {
$this->emitter = new Emitter();
}
return $this->emitter;
}
}

View File

@@ -1,88 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Trait that provides methods for extract event listeners specified in an array
* and attaching them to an emitter owned by the object or one of its direct
* dependencies.
*/
trait ListenerAttacherTrait
{
/**
* Attaches event listeners and properly sets their priorities and whether
* or not they are are only executed once.
*
* @param HasEmitterInterface $object Object that has the event emitter.
* @param array $listeners Array of hashes representing event
* event listeners. Each item contains
* "name", "fn", "priority", & "once".
*/
private function attachListeners(HasEmitterInterface $object, array $listeners)
{
$emitter = $object->getEmitter();
foreach ($listeners as $el) {
if ($el['once']) {
$emitter->once($el['name'], $el['fn'], $el['priority']);
} else {
$emitter->on($el['name'], $el['fn'], $el['priority']);
}
}
}
/**
* Extracts the allowed events from the provided array, and ignores anything
* else in the array. The event listener must be specified as a callable or
* as an array of event listener data ("name", "fn", "priority", "once").
*
* @param array $source Array containing callables or hashes of data to be
* prepared as event listeners.
* @param array $events Names of events to look for in the provided $source
* array. Other keys are ignored.
* @return array
*/
private function prepareListeners(array $source, array $events)
{
$listeners = [];
foreach ($events as $name) {
if (isset($source[$name])) {
$this->buildListener($name, $source[$name], $listeners);
}
}
return $listeners;
}
/**
* Creates a complete event listener definition from the provided array of
* listener data. Also works recursively if more than one listeners are
* contained in the provided array.
*
* @param string $name Name of the event the listener is for.
* @param array|callable $data Event listener data to prepare.
* @param array $listeners Array of listeners, passed by reference.
*
* @throws \InvalidArgumentException if the event data is malformed.
*/
private function buildListener($name, $data, &$listeners)
{
static $defaults = ['priority' => 0, 'once' => false];
// If a callable is provided, normalize it to the array format.
if (is_callable($data)) {
$data = ['fn' => $data];
}
// Prepare the listener and add it to the array, recursively.
if (isset($data['fn'])) {
$data['name'] = $name;
$listeners[] = $data + $defaults;
} elseif (is_array($data)) {
foreach ($data as $listenerData) {
$this->buildListener($name, $listenerData, $listeners);
}
} else {
throw new \InvalidArgumentException('Each event listener must be a '
. 'callable or an associative array containing a "fn" key.');
}
}
}

View File

@@ -1,51 +0,0 @@
<?php
namespace GuzzleHttp\Event;
use GuzzleHttp\Transaction;
/**
* Event object emitted when upload or download progress is made.
*
* You can access the progress values using their corresponding public
* properties:
*
* - $downloadSize: The number of bytes that will be downloaded (if known)
* - $downloaded: The number of bytes that have been downloaded
* - $uploadSize: The number of bytes that will be uploaded (if known)
* - $uploaded: The number of bytes that have been uploaded
*/
class ProgressEvent extends AbstractRequestEvent
{
/** @var int Amount of data to be downloaded */
public $downloadSize;
/** @var int Amount of data that has been downloaded */
public $downloaded;
/** @var int Amount of data to upload */
public $uploadSize;
/** @var int Amount of data that has been uploaded */
public $uploaded;
/**
* @param Transaction $transaction Transaction being sent.
* @param int $downloadSize Amount of data to download (if known)
* @param int $downloaded Amount of data that has been downloaded
* @param int $uploadSize Amount of data to upload (if known)
* @param int $uploaded Amount of data that had been uploaded
*/
public function __construct(
Transaction $transaction,
$downloadSize,
$downloaded,
$uploadSize,
$uploaded
) {
parent::__construct($transaction);
$this->downloadSize = $downloadSize;
$this->downloaded = $downloaded;
$this->uploadSize = $uploadSize;
$this->uploaded = $uploaded;
}
}

View File

@@ -1,56 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* Contains methods used to manage the request event lifecycle.
*/
final class RequestEvents
{
// Generic event priorities
const EARLY = 10000;
const LATE = -10000;
// "before" priorities
const PREPARE_REQUEST = -100;
const SIGN_REQUEST = -10000;
// "complete" and "error" response priorities
const VERIFY_RESPONSE = 100;
const REDIRECT_RESPONSE = 200;
/**
* Converts an array of event options into a formatted array of valid event
* configuration.
*
* @param array $options Event array to convert
* @param array $events Event names to convert in the options array.
* @param mixed $handler Event handler to utilize
*
* @return array
* @throws \InvalidArgumentException if the event config is invalid
* @internal
*/
public static function convertEventArray(
array $options,
array $events,
$handler
) {
foreach ($events as $name) {
if (!isset($options[$name])) {
$options[$name] = [$handler];
} elseif (is_callable($options[$name])) {
$options[$name] = [$options[$name], $handler];
} elseif (is_array($options[$name])) {
if (isset($options[$name]['fn'])) {
$options[$name] = [$options[$name], $handler];
} else {
$options[$name][] = $handler;
}
} else {
throw new \InvalidArgumentException('Invalid event format');
}
}
return $options;
}
}

View File

@@ -1,34 +0,0 @@
<?php
namespace GuzzleHttp\Event;
/**
* SubscriberInterface provides an array of events to an
* EventEmitterInterface when it is registered. The emitter then binds the
* listeners specified by the EventSubscriber.
*
* This interface is based on the SubscriberInterface of the Symfony.
* @link https://github.com/symfony/symfony/tree/master/src/Symfony/Component/EventDispatcher
*/
interface SubscriberInterface
{
/**
* Returns an array of event names this subscriber wants to listen to.
*
* The returned array keys MUST map to an event name. Each array value
* MUST be an array in which the first element is the name of a function
* on the EventSubscriber OR an array of arrays in the aforementioned
* format. The second element in the array is optional, and if specified,
* designates the event priority.
*
* For example, the following are all valid:
*
* - ['eventName' => ['methodName']]
* - ['eventName' => ['methodName', $priority]]
* - ['eventName' => [['methodName'], ['otherMethod']]
* - ['eventName' => [['methodName'], ['otherMethod', $priority]]
* - ['eventName' => [['methodName', $priority], ['otherMethod', $priority]]
*
* @return array
*/
public function getEvents();
}

View File

@@ -1,4 +0,0 @@
<?php
namespace GuzzleHttp\Exception;
class CouldNotRewindStreamException extends RequestException {}

View File

@@ -1,31 +0,0 @@
<?php
namespace GuzzleHttp\Exception;
use GuzzleHttp\Message\ResponseInterface;
/**
* Exception when a client is unable to parse the response body as XML or JSON
*/
class ParseException extends TransferException
{
/** @var ResponseInterface */
private $response;
public function __construct(
$message = '',
ResponseInterface $response = null,
\Exception $previous = null
) {
parent::__construct($message, 0, $previous);
$this->response = $response;
}
/**
* Get the associated response
*
* @return ResponseInterface|null
*/
public function getResponse()
{
return $this->response;
}
}

View File

@@ -1,4 +0,0 @@
<?php
namespace GuzzleHttp\Exception;
class StateException extends TransferException {};

View File

@@ -1,34 +0,0 @@
<?php
namespace GuzzleHttp\Exception;
use GuzzleHttp\Message\ResponseInterface;
/**
* Exception when a client is unable to parse the response body as XML
*/
class XmlParseException extends ParseException
{
/** @var \LibXMLError */
protected $error;
public function __construct(
$message = '',
ResponseInterface $response = null,
\Exception $previous = null,
\LibXMLError $error = null
) {
parent::__construct($message, $response, $previous);
$this->error = $error;
}
/**
* Get the associated error
*
* @return \LibXMLError|null
*/
public function getError()
{
return $this->error;
}
}

View File

@@ -1,75 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* Trait implementing ToArrayInterface, \ArrayAccess, \Countable,
* \IteratorAggregate, and some path style methods.
*/
trait HasDataTrait
{
/** @var array */
protected $data = [];
public function getIterator()
{
return new \ArrayIterator($this->data);
}
public function offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
public function toArray()
{
return $this->data;
}
public function count()
{
return count($this->data);
}
/**
* Get a value from the collection using a path syntax to retrieve nested
* data.
*
* @param string $path Path to traverse and retrieve a value from
*
* @return mixed|null
*/
public function getPath($path)
{
return Utils::getPath($this->data, $path);
}
/**
* Set a value into a nested array key. Keys will be created as needed to
* set the value.
*
* @param string $path Path to set
* @param mixed $value Value to set at the key
*
* @throws \RuntimeException when trying to setPath using a nested path
* that travels through a scalar value
*/
public function setPath($path, $value)
{
Utils::setPath($this->data, $path, $value);
}
}

View File

@@ -1,253 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Stream\StreamInterface;
abstract class AbstractMessage implements MessageInterface
{
/** @var array HTTP header collection */
private $headers = [];
/** @var array mapping a lowercase header name to its name over the wire */
private $headerNames = [];
/** @var StreamInterface Message body */
private $body;
/** @var string HTTP protocol version of the message */
private $protocolVersion = '1.1';
public function __toString()
{
return static::getStartLineAndHeaders($this)
. "\r\n\r\n" . $this->getBody();
}
public function getProtocolVersion()
{
return $this->protocolVersion;
}
public function getBody()
{
return $this->body;
}
public function setBody(StreamInterface $body = null)
{
if ($body === null) {
// Setting a null body will remove the body of the request
$this->removeHeader('Content-Length');
$this->removeHeader('Transfer-Encoding');
}
$this->body = $body;
}
public function addHeader($header, $value)
{
if (is_array($value)) {
$current = array_merge($this->getHeaderAsArray($header), $value);
} else {
$current = $this->getHeaderAsArray($header);
$current[] = (string) $value;
}
$this->setHeader($header, $current);
}
public function addHeaders(array $headers)
{
foreach ($headers as $name => $header) {
$this->addHeader($name, $header);
}
}
public function getHeader($header)
{
$name = strtolower($header);
return isset($this->headers[$name])
? implode(', ', $this->headers[$name])
: '';
}
public function getHeaderAsArray($header)
{
$name = strtolower($header);
return isset($this->headers[$name]) ? $this->headers[$name] : [];
}
public function getHeaders()
{
$headers = [];
foreach ($this->headers as $name => $values) {
$headers[$this->headerNames[$name]] = $values;
}
return $headers;
}
public function setHeader($header, $value)
{
$header = trim($header);
$name = strtolower($header);
$this->headerNames[$name] = $header;
if (is_array($value)) {
foreach ($value as &$v) {
$v = trim($v);
}
$this->headers[$name] = $value;
} else {
$this->headers[$name] = [trim($value)];
}
}
public function setHeaders(array $headers)
{
$this->headers = $this->headerNames = [];
foreach ($headers as $key => $value) {
$this->addHeader($key, $value);
}
}
public function hasHeader($header)
{
return isset($this->headers[strtolower($header)]);
}
public function removeHeader($header)
{
$name = strtolower($header);
unset($this->headers[$name], $this->headerNames[$name]);
}
/**
* 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 MessageInterface $message That contains the header
* @param string $header Header to retrieve from the message
*
* @return array Returns the parsed header values.
*/
public static function parseHeader(MessageInterface $message, $header)
{
static $trimmed = "\"' \n\t\r";
$params = $matches = [];
foreach (self::normalizeHeader($message, $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 MessageInterface $message That contains the header
* @param string $header Header to retrieve from the message
*
* @return array Returns the normalized header field values.
*/
public static function normalizeHeader(MessageInterface $message, $header)
{
$h = $message->getHeaderAsArray($header);
for ($i = 0, $total = count($h); $i < $total; $i++) {
if (strpos($h[$i], ',') === false) {
continue;
}
foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $h[$i]) as $v) {
$h[] = trim($v);
}
unset($h[$i]);
}
return $h;
}
/**
* Gets the start-line and headers of a message as a string
*
* @param MessageInterface $message
*
* @return string
*/
public static function getStartLineAndHeaders(MessageInterface $message)
{
return static::getStartLine($message)
. self::getHeadersAsString($message);
}
/**
* Gets the headers of a message as a string
*
* @param MessageInterface $message
*
* @return string
*/
public static function getHeadersAsString(MessageInterface $message)
{
$result = '';
foreach ($message->getHeaders() as $name => $values) {
$result .= "\r\n{$name}: " . implode(', ', $values);
}
return $result;
}
/**
* Gets the start line of a message
*
* @param MessageInterface $message
*
* @return string
* @throws \InvalidArgumentException
*/
public static function getStartLine(MessageInterface $message)
{
if ($message instanceof RequestInterface) {
return trim($message->getMethod() . ' '
. $message->getResource())
. ' HTTP/' . $message->getProtocolVersion();
} elseif ($message instanceof ResponseInterface) {
return 'HTTP/' . $message->getProtocolVersion() . ' '
. $message->getStatusCode() . ' '
. $message->getReasonPhrase();
} else {
throw new \InvalidArgumentException('Unknown message type');
}
}
/**
* Accepts and modifies the options provided to the message in the
* constructor.
*
* Can be overridden in subclasses as necessary.
*
* @param array $options Options array passed by reference.
*/
protected function handleOptions(array &$options)
{
if (isset($options['protocol_version'])) {
$this->protocolVersion = $options['protocol_version'];
}
}
}

View File

@@ -1,24 +0,0 @@
<?php
namespace GuzzleHttp\Message;
/**
* Applies headers to a request.
*
* This interface can be used with Guzzle streams to apply body specific
* headers to a request during the PREPARE_REQUEST priority of the before event
*
* NOTE: a body that implements this interface will prevent a default
* content-type from being added to a request during the before event. If you
* want a default content-type to be added, then it will need to be done
* manually (e.g., using {@see GuzzleHttp\Mimetypes}).
*/
interface AppliesHeadersInterface
{
/**
* Apply headers to a request appropriate for the current state of the
* object.
*
* @param RequestInterface $request Request
*/
public function applyRequestHeaders(RequestInterface $request);
}

View File

@@ -1,158 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Ring\Future\MagicFutureTrait;
use GuzzleHttp\Ring\Future\FutureInterface;
use GuzzleHttp\Stream\StreamInterface;
/**
* Represents a response that has not been fulfilled.
*
* When created, you must provide a function that is used to dereference the
* future result and return it's value. The function has no arguments and MUST
* return an instance of a {@see GuzzleHttp\Message\ResponseInterface} object.
*
* You can optionally provide a function in the constructor that can be used to
* cancel the future from completing if possible. This function has no
* arguments and returns a boolean value representing whether or not the
* response could be cancelled.
*
* @property ResponseInterface $_value
*/
class FutureResponse implements ResponseInterface, FutureInterface
{
use MagicFutureTrait;
/**
* Returns a FutureResponse that wraps another future.
*
* @param FutureInterface $future Future to wrap with a new future
* @param callable $onFulfilled Invoked when the future fulfilled
* @param callable $onRejected Invoked when the future rejected
* @param callable $onProgress Invoked when the future progresses
*
* @return FutureResponse
*/
public static function proxy(
FutureInterface $future,
callable $onFulfilled = null,
callable $onRejected = null,
callable $onProgress = null
) {
return new FutureResponse(
$future->then($onFulfilled, $onRejected, $onProgress),
[$future, 'wait'],
[$future, 'cancel']
);
}
public function getStatusCode()
{
return $this->_value->getStatusCode();
}
public function setStatusCode($code)
{
$this->_value->setStatusCode($code);
}
public function getReasonPhrase()
{
return $this->_value->getReasonPhrase();
}
public function setReasonPhrase($phrase)
{
$this->_value->setReasonPhrase($phrase);
}
public function getEffectiveUrl()
{
return $this->_value->getEffectiveUrl();
}
public function setEffectiveUrl($url)
{
$this->_value->setEffectiveUrl($url);
}
public function json(array $config = [])
{
return $this->_value->json($config);
}
public function xml(array $config = [])
{
return $this->_value->xml($config);
}
public function __toString()
{
try {
return $this->_value->__toString();
} catch (\Exception $e) {
trigger_error($e->getMessage(), E_USER_WARNING);
return '';
}
}
public function getProtocolVersion()
{
return $this->_value->getProtocolVersion();
}
public function setBody(StreamInterface $body = null)
{
$this->_value->setBody($body);
}
public function getBody()
{
return $this->_value->getBody();
}
public function getHeaders()
{
return $this->_value->getHeaders();
}
public function getHeader($header)
{
return $this->_value->getHeader($header);
}
public function getHeaderAsArray($header)
{
return $this->_value->getHeaderAsArray($header);
}
public function hasHeader($header)
{
return $this->_value->hasHeader($header);
}
public function removeHeader($header)
{
$this->_value->removeHeader($header);
}
public function addHeader($header, $value)
{
$this->_value->addHeader($header, $value);
}
public function addHeaders(array $headers)
{
$this->_value->addHeaders($headers);
}
public function setHeader($header, $value)
{
$this->_value->setHeader($header, $value);
}
public function setHeaders(array $headers)
{
$this->_value->setHeaders($headers);
}
}

View File

@@ -1,364 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Event\ListenerAttacherTrait;
use GuzzleHttp\Post\PostBody;
use GuzzleHttp\Post\PostFile;
use GuzzleHttp\Post\PostFileInterface;
use GuzzleHttp\Query;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Subscriber\Cookie;
use GuzzleHttp\Subscriber\HttpError;
use GuzzleHttp\Subscriber\Redirect;
use GuzzleHttp\Url;
use \InvalidArgumentException as Iae;
/**
* Default HTTP request factory used to create Request and Response objects.
*/
class MessageFactory implements MessageFactoryInterface
{
use ListenerAttacherTrait;
/** @var HttpError */
private $errorPlugin;
/** @var Redirect */
private $redirectPlugin;
/** @var array */
private $customOptions;
/** @var array Request options passed through to request Config object */
private static $configMap = [
'connect_timeout' => 1, 'timeout' => 1, 'verify' => 1, 'ssl_key' => 1,
'cert' => 1, 'proxy' => 1, 'debug' => 1, 'save_to' => 1, 'stream' => 1,
'expect' => 1, 'future' => 1
];
/** @var array Default allow_redirects request option settings */
private static $defaultRedirect = [
'max' => 5,
'strict' => false,
'referer' => false,
'protocols' => ['http', 'https']
];
/**
* @param array $customOptions Associative array of custom request option
* names mapping to functions used to apply
* the option. The function accepts the request
* and the option value to apply.
*/
public function __construct(array $customOptions = [])
{
$this->errorPlugin = new HttpError();
$this->redirectPlugin = new Redirect();
$this->customOptions = $customOptions;
}
public function createResponse(
$statusCode,
array $headers = [],
$body = null,
array $options = []
) {
if (null !== $body) {
$body = Stream::factory($body);
}
return new Response($statusCode, $headers, $body, $options);
}
public function createRequest($method, $url, array $options = [])
{
// Handle the request protocol version option that needs to be
// specified in the request constructor.
if (isset($options['version'])) {
$options['config']['protocol_version'] = $options['version'];
unset($options['version']);
}
$request = new Request($method, $url, [], null,
isset($options['config']) ? $options['config'] : []);
unset($options['config']);
// Use a POST body by default
if (strtoupper($method) == 'POST'
&& !isset($options['body'])
&& !isset($options['json'])
) {
$options['body'] = [];
}
if ($options) {
$this->applyOptions($request, $options);
}
return $request;
}
/**
* Create a request or response object from an HTTP message string
*
* @param string $message Message to parse
*
* @return RequestInterface|ResponseInterface
* @throws \InvalidArgumentException if unable to parse a message
*/
public function fromMessage($message)
{
static $parser;
if (!$parser) {
$parser = new MessageParser();
}
// Parse a response
if (strtoupper(substr($message, 0, 4)) == 'HTTP') {
$data = $parser->parseResponse($message);
return $this->createResponse(
$data['code'],
$data['headers'],
$data['body'] === '' ? null : $data['body'],
$data
);
}
// Parse a request
if (!($data = ($parser->parseRequest($message)))) {
throw new \InvalidArgumentException('Unable to parse request');
}
return $this->createRequest(
$data['method'],
Url::buildUrl($data['request_url']),
[
'headers' => $data['headers'],
'body' => $data['body'] === '' ? null : $data['body'],
'config' => [
'protocol_version' => $data['protocol_version']
]
]
);
}
/**
* Apply POST fields and files to a request to attempt to give an accurate
* representation.
*
* @param RequestInterface $request Request to update
* @param array $body Body to apply
*/
protected function addPostData(RequestInterface $request, array $body)
{
static $fields = ['string' => true, 'array' => true, 'NULL' => true,
'boolean' => true, 'double' => true, 'integer' => true];
$post = new PostBody();
foreach ($body as $key => $value) {
if (isset($fields[gettype($value)])) {
$post->setField($key, $value);
} elseif ($value instanceof PostFileInterface) {
$post->addFile($value);
} else {
$post->addFile(new PostFile($key, $value));
}
}
if ($request->getHeader('Content-Type') == 'multipart/form-data') {
$post->forceMultipartUpload(true);
}
$request->setBody($post);
}
protected function applyOptions(
RequestInterface $request,
array $options = []
) {
$config = $request->getConfig();
$emitter = $request->getEmitter();
foreach ($options as $key => $value) {
if (isset(self::$configMap[$key])) {
$config[$key] = $value;
continue;
}
switch ($key) {
case 'allow_redirects':
if ($value === false) {
continue 2;
}
if ($value === true) {
$value = self::$defaultRedirect;
} elseif (!is_array($value)) {
throw new Iae('allow_redirects must be true, false, or array');
} else {
// Merge the default settings with the provided settings
$value += self::$defaultRedirect;
}
$config['redirect'] = $value;
$emitter->attach($this->redirectPlugin);
break;
case 'decode_content':
if ($value === false) {
continue 2;
}
$config['decode_content'] = true;
if ($value !== true) {
$request->setHeader('Accept-Encoding', $value);
}
break;
case 'headers':
if (!is_array($value)) {
throw new Iae('header value must be an array');
}
foreach ($value as $k => $v) {
$request->setHeader($k, $v);
}
break;
case 'exceptions':
if ($value === true) {
$emitter->attach($this->errorPlugin);
}
break;
case 'body':
if (is_array($value)) {
$this->addPostData($request, $value);
} elseif ($value !== null) {
$request->setBody(Stream::factory($value));
}
break;
case 'auth':
if (!$value) {
continue 2;
}
if (is_array($value)) {
$type = isset($value[2]) ? strtolower($value[2]) : 'basic';
} else {
$type = strtolower($value);
}
$config['auth'] = $value;
if ($type == 'basic') {
$request->setHeader(
'Authorization',
'Basic ' . base64_encode("$value[0]:$value[1]")
);
} elseif ($type == 'digest') {
// @todo: Do not rely on curl
$config->setPath('curl/' . CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$config->setPath('curl/' . CURLOPT_USERPWD, "$value[0]:$value[1]");
}
break;
case 'query':
if ($value instanceof Query) {
$original = $request->getQuery();
// Do not overwrite existing query string variables by
// overwriting the object with the query string data passed
// in the URL
$value->overwriteWith($original->toArray());
$request->setQuery($value);
} elseif (is_array($value)) {
// Do not overwrite existing query string variables
$query = $request->getQuery();
foreach ($value as $k => $v) {
if (!isset($query[$k])) {
$query[$k] = $v;
}
}
} else {
throw new Iae('query must be an array or Query object');
}
break;
case 'cookies':
if ($value === true) {
static $cookie = null;
if (!$cookie) {
$cookie = new Cookie();
}
$emitter->attach($cookie);
} elseif (is_array($value)) {
$emitter->attach(
new Cookie(CookieJar::fromArray($value, $request->getHost()))
);
} elseif ($value instanceof CookieJarInterface) {
$emitter->attach(new Cookie($value));
} elseif ($value !== false) {
throw new Iae('cookies must be an array, true, or CookieJarInterface');
}
break;
case 'events':
if (!is_array($value)) {
throw new Iae('events must be an array');
}
$this->attachListeners($request,
$this->prepareListeners(
$value,
['before', 'complete', 'error', 'progress', 'end']
)
);
break;
case 'subscribers':
if (!is_array($value)) {
throw new Iae('subscribers must be an array');
}
foreach ($value as $subscribers) {
$emitter->attach($subscribers);
}
break;
case 'json':
$request->setBody(Stream::factory(json_encode($value)));
if (!$request->hasHeader('Content-Type')) {
$request->setHeader('Content-Type', 'application/json');
}
break;
default:
// Check for custom handler functions.
if (isset($this->customOptions[$key])) {
$fn = $this->customOptions[$key];
$fn($request, $value);
continue 2;
}
throw new Iae("No method can handle the {$key} config key");
}
}
}
}

View File

@@ -1,71 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Url;
/**
* Request and response factory
*/
interface MessageFactoryInterface
{
/**
* Creates a response
*
* @param string $statusCode HTTP status code
* @param array $headers Response headers
* @param mixed $body Response body
* @param array $options Response options
* - protocol_version: HTTP protocol version
* - header_factory: Factory used to create headers
* - And any other options used by a concrete message implementation
*
* @return ResponseInterface
*/
public function createResponse(
$statusCode,
array $headers = [],
$body = null,
array $options = []
);
/**
* Create a new request based on the HTTP method.
*
* This method accepts an associative array of request options. Below is a
* brief description of each parameter. See
* http://docs.guzzlephp.org/en/latest/clients.html#request-options for a much more
* in-depth description of each parameter.
*
* - headers: Associative array of headers to add to the request
* - body: string|resource|array|StreamInterface request body to send
* - json: mixed Uploads JSON encoded data using an application/json Content-Type header.
* - query: Associative array of query string values to add to the request
* - auth: array|string HTTP auth settings (user, pass[, type="basic"])
* - version: The HTTP protocol version to use with the request
* - cookies: true|false|CookieJarInterface To enable or disable cookies
* - allow_redirects: true|false|array Controls HTTP redirects
* - save_to: string|resource|StreamInterface Where the response is saved
* - events: Associative array of event names to callables or arrays
* - subscribers: Array of event subscribers to add to the request
* - exceptions: Specifies whether or not exceptions are thrown for HTTP protocol errors
* - timeout: Timeout of the request in seconds. Use 0 to wait indefinitely
* - connect_timeout: Number of seconds to wait while trying to connect. (0 to wait indefinitely)
* - verify: SSL validation. True/False or the path to a PEM file
* - cert: Path a SSL cert or array of (path, pwd)
* - ssl_key: Path to a private SSL key or array of (path, pwd)
* - proxy: Specify an HTTP proxy or hash of protocols to proxies
* - debug: Set to true or a resource to view handler specific debug info
* - stream: Set to true to stream a response body rather than download it all up front
* - expect: true/false/integer Controls the "Expect: 100-Continue" header
* - config: Associative array of request config collection options
* - decode_content: true/false/string to control decoding content-encoding responses
*
* @param string $method HTTP method (GET, POST, PUT, etc.)
* @param string|Url $url HTTP URL to connect to
* @param array $options Array of options to apply to the request
*
* @return RequestInterface
* @link http://docs.guzzlephp.org/en/latest/clients.html#request-options
*/
public function createRequest($method, $url, array $options = []);
}

View File

@@ -1,136 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Stream\StreamInterface;
/**
* Request and response message interface
*/
interface MessageInterface
{
/**
* Get a string representation of the message
*
* @return string
*/
public function __toString();
/**
* Get the HTTP protocol version of the message
*
* @return string
*/
public function getProtocolVersion();
/**
* Sets the body of the message.
*
* The body MUST be a StreamInterface object. Setting the body to null MUST
* remove the existing body.
*
* @param StreamInterface|null $body Body.
*/
public function setBody(StreamInterface $body = null);
/**
* Get the body of the message
*
* @return StreamInterface|null
*/
public function getBody();
/**
* Gets all message headers.
*
* The keys represent the header name as it will be sent over the wire, and
* each value is an array of strings associated with the header.
*
* // Represent the headers as a string
* foreach ($message->getHeaders() as $name => $values) {
* echo $name . ": " . implode(", ", $values);
* }
*
* @return array Returns an associative array of the message's headers.
*/
public function getHeaders();
/**
* Retrieve a header by the given case-insensitive name.
*
* @param string $header Case-insensitive header name.
*
* @return string
*/
public function getHeader($header);
/**
* Retrieves a header by the given case-insensitive name as an array of strings.
*
* @param string $header Case-insensitive header name.
*
* @return string[]
*/
public function getHeaderAsArray($header);
/**
* Checks if a header exists by the given case-insensitive name.
*
* @param string $header Case-insensitive header name.
*
* @return bool Returns true if any header names match the given header
* name using a case-insensitive string comparison. Returns false if
* no matching header name is found in the message.
*/
public function hasHeader($header);
/**
* Remove a specific header by case-insensitive name.
*
* @param string $header Case-insensitive header name.
*/
public function removeHeader($header);
/**
* Appends a header value to any existing values associated with the
* given header name.
*
* @param string $header Header name to add
* @param string $value Value of the header
*/
public function addHeader($header, $value);
/**
* Merges in an associative array of headers.
*
* Each array key MUST be a string representing the case-insensitive name
* of a header. Each value MUST be either a string or an array of strings.
* For each value, the value is appended to any existing header of the same
* name, or, if a header does not already exist by the given name, then the
* header is added.
*
* @param array $headers Associative array of headers to add to the message
*/
public function addHeaders(array $headers);
/**
* Sets a header, replacing any existing values of any headers with the
* same case-insensitive name.
*
* The header values MUST be a string or an array of strings.
*
* @param string $header Header name
* @param string|array $value Header value(s)
*/
public function setHeader($header, $value);
/**
* Sets headers, replacing any headers that have already been set on the
* message.
*
* The array keys MUST be a string. The array values must be either a
* string or an array of strings.
*
* @param array $headers Headers to set.
*/
public function setHeaders(array $headers);
}

View File

@@ -1,171 +0,0 @@
<?php
namespace GuzzleHttp\Message;
/**
* Request and response parser used by Guzzle
*/
class MessageParser
{
/**
* Parse an HTTP request message into an associative array of parts.
*
* @param string $message HTTP request to parse
*
* @return array|bool Returns false if the message is invalid
*/
public function parseRequest($message)
{
if (!($parts = $this->parseMessage($message))) {
return false;
}
// Parse the protocol and protocol version
if (isset($parts['start_line'][2])) {
$startParts = explode('/', $parts['start_line'][2]);
$protocol = strtoupper($startParts[0]);
$version = isset($startParts[1]) ? $startParts[1] : '1.1';
} else {
$protocol = 'HTTP';
$version = '1.1';
}
$parsed = [
'method' => strtoupper($parts['start_line'][0]),
'protocol' => $protocol,
'protocol_version' => $version,
'headers' => $parts['headers'],
'body' => $parts['body']
];
$parsed['request_url'] = $this->getUrlPartsFromMessage(
(isset($parts['start_line'][1]) ? $parts['start_line'][1] : ''), $parsed);
return $parsed;
}
/**
* Parse an HTTP response message into an associative array of parts.
*
* @param string $message HTTP response to parse
*
* @return array|bool Returns false if the message is invalid
*/
public function parseResponse($message)
{
if (!($parts = $this->parseMessage($message))) {
return false;
}
list($protocol, $version) = explode('/', trim($parts['start_line'][0]));
return [
'protocol' => $protocol,
'protocol_version' => $version,
'code' => $parts['start_line'][1],
'reason_phrase' => isset($parts['start_line'][2]) ? $parts['start_line'][2] : '',
'headers' => $parts['headers'],
'body' => $parts['body']
];
}
/**
* Parse a message into parts
*
* @param string $message Message to parse
*
* @return array|bool
*/
private function parseMessage($message)
{
if (!$message) {
return false;
}
$startLine = null;
$headers = [];
$body = '';
// Iterate over each line in the message, accounting for line endings
$lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) {
$line = $lines[$i];
// If two line breaks were encountered, then this is the end of body
if (empty($line)) {
if ($i < $totalLines - 1) {
$body = implode('', array_slice($lines, $i + 2));
}
break;
}
// Parse message headers
if (!$startLine) {
$startLine = explode(' ', $line, 3);
} elseif (strpos($line, ':')) {
$parts = explode(':', $line, 2);
$key = trim($parts[0]);
$value = isset($parts[1]) ? trim($parts[1]) : '';
if (!isset($headers[$key])) {
$headers[$key] = $value;
} elseif (!is_array($headers[$key])) {
$headers[$key] = [$headers[$key], $value];
} else {
$headers[$key][] = $value;
}
}
}
return [
'start_line' => $startLine,
'headers' => $headers,
'body' => $body
];
}
/**
* Create URL parts from HTTP message parts
*
* @param string $requestUrl Associated URL
* @param array $parts HTTP message parts
*
* @return array
*/
private function getUrlPartsFromMessage($requestUrl, array $parts)
{
// Parse the URL information from the message
$urlParts = ['path' => $requestUrl, 'scheme' => 'http'];
// Check for the Host header
if (isset($parts['headers']['Host'])) {
$urlParts['host'] = $parts['headers']['Host'];
} elseif (isset($parts['headers']['host'])) {
$urlParts['host'] = $parts['headers']['host'];
} else {
$urlParts['host'] = null;
}
if (false === strpos($urlParts['host'], ':')) {
$urlParts['port'] = '';
} else {
$hostParts = explode(':', $urlParts['host']);
$urlParts['host'] = trim($hostParts[0]);
$urlParts['port'] = (int) trim($hostParts[1]);
if ($urlParts['port'] == 443) {
$urlParts['scheme'] = 'https';
}
}
// Check if a query is present
$path = $urlParts['path'];
$qpos = strpos($path, '?');
if ($qpos) {
$urlParts['query'] = substr($path, $qpos + 1);
$urlParts['path'] = substr($path, 0, $qpos);
} else {
$urlParts['query'] = '';
}
return $urlParts;
}
}

View File

@@ -1,195 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Collection;
use GuzzleHttp\Event\HasEmitterTrait;
use GuzzleHttp\Subscriber\Prepare;
use GuzzleHttp\Url;
/**
* HTTP request class to send requests
*/
class Request extends AbstractMessage implements RequestInterface
{
use HasEmitterTrait;
/** @var Url HTTP Url */
private $url;
/** @var string HTTP method */
private $method;
/** @var Collection Transfer options */
private $transferOptions;
/**
* @param string $method HTTP method
* @param string|Url $url HTTP URL to connect to. The URI scheme,
* host header, and URI are parsed from the full URL. If query string
* parameters are present they will be parsed as well.
* @param array|Collection $headers HTTP headers
* @param mixed $body Body to send with the request
* @param array $options Array of options to use with the request
* - emitter: Event emitter to use with the request
*/
public function __construct(
$method,
$url,
$headers = [],
$body = null,
array $options = []
) {
$this->setUrl($url);
$this->method = strtoupper($method);
$this->handleOptions($options);
$this->transferOptions = new Collection($options);
$this->addPrepareEvent();
if ($body !== null) {
$this->setBody($body);
}
if ($headers) {
foreach ($headers as $key => $value) {
$this->addHeader($key, $value);
}
}
}
public function __clone()
{
if ($this->emitter) {
$this->emitter = clone $this->emitter;
}
$this->transferOptions = clone $this->transferOptions;
$this->url = clone $this->url;
}
public function setUrl($url)
{
$this->url = $url instanceof Url ? $url : Url::fromString($url);
$this->updateHostHeaderFromUrl();
}
public function getUrl()
{
return (string) $this->url;
}
public function setQuery($query)
{
$this->url->setQuery($query);
}
public function getQuery()
{
return $this->url->getQuery();
}
public function setMethod($method)
{
$this->method = strtoupper($method);
}
public function getMethod()
{
return $this->method;
}
public function getScheme()
{
return $this->url->getScheme();
}
public function setScheme($scheme)
{
$this->url->setScheme($scheme);
}
public function getPort()
{
return $this->url->getPort();
}
public function setPort($port)
{
$this->url->setPort($port);
$this->updateHostHeaderFromUrl();
}
public function getHost()
{
return $this->url->getHost();
}
public function setHost($host)
{
$this->url->setHost($host);
$this->updateHostHeaderFromUrl();
}
public function getPath()
{
return '/' . ltrim($this->url->getPath(), '/');
}
public function setPath($path)
{
$this->url->setPath($path);
}
public function getResource()
{
$resource = $this->getPath();
if ($query = (string) $this->url->getQuery()) {
$resource .= '?' . $query;
}
return $resource;
}
public function getConfig()
{
return $this->transferOptions;
}
protected function handleOptions(array &$options)
{
parent::handleOptions($options);
// Use a custom emitter if one is specified, and remove it from
// options that are exposed through getConfig()
if (isset($options['emitter'])) {
$this->emitter = $options['emitter'];
unset($options['emitter']);
}
}
/**
* Adds a subscriber that ensures a request's body is prepared before
* sending.
*/
private function addPrepareEvent()
{
static $subscriber;
if (!$subscriber) {
$subscriber = new Prepare();
}
$this->getEmitter()->attach($subscriber);
}
private function updateHostHeaderFromUrl()
{
$port = $this->url->getPort();
$scheme = $this->url->getScheme();
if ($host = $this->url->getHost()) {
if (($port == 80 && $scheme == 'http') ||
($port == 443 && $scheme == 'https')
) {
$this->setHeader('Host', $host);
} else {
$this->setHeader('Host', "{$host}:{$port}");
}
}
}
}

View File

@@ -1,136 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Event\HasEmitterInterface;
use GuzzleHttp\Query;
/**
* Generic HTTP request interface
*/
interface RequestInterface extends MessageInterface, HasEmitterInterface
{
/**
* Sets the request URL.
*
* The URL MUST be a string, or an object that implements the
* `__toString()` method.
*
* @param string $url Request URL.
*
* @throws \InvalidArgumentException If the URL is invalid.
*/
public function setUrl($url);
/**
* Gets the request URL as a string.
*
* @return string Returns the URL as a string.
*/
public function getUrl();
/**
* Get the resource part of the the request, including the path, query
* string, and fragment.
*
* @return string
*/
public function getResource();
/**
* Get the collection of key value pairs that will be used as the query
* string in the request.
*
* @return Query
*/
public function getQuery();
/**
* Set the query string used by the request
*
* @param array|Query $query Query to set
*/
public function setQuery($query);
/**
* Get the HTTP method of the request.
*
* @return string
*/
public function getMethod();
/**
* Set the HTTP method of the request.
*
* @param string $method HTTP method
*/
public function setMethod($method);
/**
* Get the URI scheme of the request (http, https, etc.).
*
* @return string
*/
public function getScheme();
/**
* Set the URI scheme of the request (http, https, etc.).
*
* @param string $scheme Scheme to set
*/
public function setScheme($scheme);
/**
* Get the port scheme of the request (e.g., 80, 443, etc.).
*
* @return int
*/
public function getPort();
/**
* Set the port of the request.
*
* Setting a port modifies the Host header of a request as necessary.
*
* @param int $port Port to set
*/
public function setPort($port);
/**
* Get the host of the request.
*
* @return string
*/
public function getHost();
/**
* Set the host of the request including an optional port.
*
* Including a port in the host argument will explicitly change the port of
* the request. If no port is found, the default port of the current
* request scheme will be utilized.
*
* @param string $host Host to set (e.g. www.yahoo.com, www.yahoo.com:80)
*/
public function setHost($host);
/**
* Get the path of the request (e.g. '/', '/index.html').
*
* @return string
*/
public function getPath();
/**
* Set the path of the request (e.g. '/', '/index.html').
*
* @param string|array $path Path to set or array of segments to implode
*/
public function setPath($path);
/**
* Get the request's configuration options.
*
* @return \GuzzleHttp\Collection
*/
public function getConfig();
}

View File

@@ -1,208 +0,0 @@
<?php
namespace GuzzleHttp\Message;
use GuzzleHttp\Exception\ParseException;
use GuzzleHttp\Exception\XmlParseException;
use GuzzleHttp\Stream\StreamInterface;
use GuzzleHttp\Utils;
/**
* Guzzle HTTP response object
*/
class Response extends AbstractMessage implements ResponseInterface
{
/** @var array Mapping of status codes to reason phrases */
private static $statusTexts = [
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
208 => 'Already Reported',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
425 => 'Reserved for WebDAV advanced collections expired proposal',
426 => 'Upgrade required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates (Experimental)',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
510 => 'Not Extended',
511 => 'Network Authentication Required',
];
/** @var string The reason phrase of the response (human readable code) */
private $reasonPhrase;
/** @var string The status code of the response */
private $statusCode;
/** @var string The effective URL that returned this response */
private $effectiveUrl;
/**
* @param int|string $statusCode The response status code (e.g. 200)
* @param array $headers The response headers
* @param StreamInterface $body The body of the response
* @param array $options Response message options
* - reason_phrase: Set a custom reason phrase
* - protocol_version: Set a custom protocol version
*/
public function __construct(
$statusCode,
array $headers = [],
StreamInterface $body = null,
array $options = []
) {
$this->statusCode = (int) $statusCode;
$this->handleOptions($options);
// Assume a reason phrase if one was not applied as an option
if (!$this->reasonPhrase &&
isset(self::$statusTexts[$this->statusCode])
) {
$this->reasonPhrase = self::$statusTexts[$this->statusCode];
}
if ($headers) {
$this->setHeaders($headers);
}
if ($body) {
$this->setBody($body);
}
}
public function getStatusCode()
{
return $this->statusCode;
}
public function setStatusCode($code)
{
return $this->statusCode = (int) $code;
}
public function getReasonPhrase()
{
return $this->reasonPhrase;
}
public function setReasonPhrase($phrase)
{
return $this->reasonPhrase = $phrase;
}
public function json(array $config = [])
{
try {
return Utils::jsonDecode(
(string) $this->getBody(),
isset($config['object']) ? !$config['object'] : true,
512,
isset($config['big_int_strings']) ? JSON_BIGINT_AS_STRING : 0
);
} catch (\InvalidArgumentException $e) {
throw new ParseException(
$e->getMessage(),
$this
);
}
}
public function xml(array $config = [])
{
$disableEntities = libxml_disable_entity_loader(true);
$internalErrors = libxml_use_internal_errors(true);
try {
// Allow XML to be retrieved even if there is no response body
$xml = new \SimpleXMLElement(
(string) $this->getBody() ?: '<root />',
isset($config['libxml_options']) ? $config['libxml_options'] : LIBXML_NONET,
false,
isset($config['ns']) ? $config['ns'] : '',
isset($config['ns_is_prefix']) ? $config['ns_is_prefix'] : false
);
libxml_disable_entity_loader($disableEntities);
libxml_use_internal_errors($internalErrors);
} catch (\Exception $e) {
libxml_disable_entity_loader($disableEntities);
libxml_use_internal_errors($internalErrors);
throw new XmlParseException(
'Unable to parse response body into XML: ' . $e->getMessage(),
$this,
$e,
(libxml_get_last_error()) ?: null
);
}
return $xml;
}
public function getEffectiveUrl()
{
return $this->effectiveUrl;
}
public function setEffectiveUrl($url)
{
$this->effectiveUrl = $url;
}
/**
* Accepts and modifies the options provided to the response in the
* constructor.
*
* @param array $options Options array passed by reference.
*/
protected function handleOptions(array &$options = [])
{
parent::handleOptions($options);
if (isset($options['reason_phrase'])) {
$this->reasonPhrase = $options['reason_phrase'];
}
}
}

View File

@@ -1,111 +0,0 @@
<?php
namespace GuzzleHttp\Message;
/**
* Represents an HTTP response message.
*/
interface ResponseInterface extends MessageInterface
{
/**
* Gets the response Status-Code.
*
* The Status-Code is a 3-digit integer result code of the server's attempt
* to understand and satisfy the request.
*
* @return int Status code.
*/
public function getStatusCode();
/**
* Sets the status code of this response.
*
* @param int $code The 3-digit integer result code to set.
*/
public function setStatusCode($code);
/**
* Gets the response Reason-Phrase, a short textual description of the
* Status-Code.
*
* Because a Reason-Phrase is not a required element in response
* Status-Line, the Reason-Phrase value MAY be null. Implementations MAY
* choose to return the default RFC 2616 recommended reason phrase for the
* response's Status-Code.
*
* @return string|null Reason phrase, or null if unknown.
*/
public function getReasonPhrase();
/**
* Sets the Reason-Phrase of the response.
*
* If no Reason-Phrase is specified, implementations MAY choose to default
* to the RFC 2616 recommended reason phrase for the response's Status-Code.
*
* @param string $phrase The Reason-Phrase to set.
*/
public function setReasonPhrase($phrase);
/**
* Get the effective URL that resulted in this response (e.g. the last
* redirect URL).
*
* @return string
*/
public function getEffectiveUrl();
/**
* Set the effective URL that resulted in this response (e.g. the last
* redirect URL).
*
* @param string $url Effective URL
*/
public function setEffectiveUrl($url);
/**
* Parse the JSON response body and return the JSON decoded data.
*
* @param array $config Associative array of configuration settings used
* to control how the JSON data is parsed. Concrete implementations MAY
* add further configuration settings as needed, but they MUST implement
* functionality for the following options:
*
* - object: Set to true to parse JSON objects as PHP objects rather
* than associative arrays. Defaults to false.
* - big_int_strings: When set to true, large integers are converted to
* strings rather than floats. Defaults to false.
*
* Implementations are free to add further configuration settings as
* needed.
*
* @return mixed Returns the JSON decoded data based on the provided
* parse settings.
* @throws \RuntimeException if the response body is not in JSON format
*/
public function json(array $config = []);
/**
* Parse the XML response body and return a \SimpleXMLElement.
*
* In order to prevent XXE attacks, this method disables loading external
* entities. If you rely on external entities, then you must parse the
* XML response manually by accessing the response body directly.
*
* @param array $config Associative array of configuration settings used
* to control how the XML is parsed. Concrete implementations MAY add
* further configuration settings as needed, but they MUST implement
* functionality for the following options:
*
* - ns: Set to a string to represent the namespace prefix or URI
* - ns_is_prefix: Set to true to specify that the NS is a prefix rather
* than a URI (defaults to false).
* - libxml_options: Bitwise OR of the libxml option constants
* listed at http://php.net/manual/en/libxml.constants.php
* (defaults to LIBXML_NONET)
*
* @return \SimpleXMLElement
* @throws \RuntimeException if the response body is not in XML format
* @link http://websec.io/2012/08/27/Preventing-XXE-in-PHP.html
*/
public function xml(array $config = []);
}

View File

@@ -1,963 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* Provides mappings of file extensions to mimetypes
* @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types
*/
class Mimetypes
{
/** @var self */
protected static $instance;
/** @var array Mapping of extension to mimetype */
protected $mimetypes = array(
'3dml' => 'text/vnd.in3d.3dml',
'3g2' => 'video/3gpp2',
'3gp' => 'video/3gpp',
'7z' => 'application/x-7z-compressed',
'aab' => 'application/x-authorware-bin',
'aac' => 'audio/x-aac',
'aam' => 'application/x-authorware-map',
'aas' => 'application/x-authorware-seg',
'abw' => 'application/x-abiword',
'ac' => 'application/pkix-attr-cert',
'acc' => 'application/vnd.americandynamics.acc',
'ace' => 'application/x-ace-compressed',
'acu' => 'application/vnd.acucobol',
'acutc' => 'application/vnd.acucorp',
'adp' => 'audio/adpcm',
'aep' => 'application/vnd.audiograph',
'afm' => 'application/x-font-type1',
'afp' => 'application/vnd.ibm.modcap',
'ahead' => 'application/vnd.ahead.space',
'ai' => 'application/postscript',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'air' => 'application/vnd.adobe.air-application-installer-package+zip',
'ait' => 'application/vnd.dvb.ait',
'ami' => 'application/vnd.amiga.ami',
'apk' => 'application/vnd.android.package-archive',
'application' => 'application/x-ms-application',
'apr' => 'application/vnd.lotus-approach',
'asa' => 'text/plain',
'asax' => 'application/octet-stream',
'asc' => 'application/pgp-signature',
'ascx' => 'text/plain',
'asf' => 'video/x-ms-asf',
'ashx' => 'text/plain',
'asm' => 'text/x-asm',
'asmx' => 'text/plain',
'aso' => 'application/vnd.accpac.simply.aso',
'asp' => 'text/plain',
'aspx' => 'text/plain',
'asx' => 'video/x-ms-asf',
'atc' => 'application/vnd.acucorp',
'atom' => 'application/atom+xml',
'atomcat' => 'application/atomcat+xml',
'atomsvc' => 'application/atomsvc+xml',
'atx' => 'application/vnd.antix.game-component',
'au' => 'audio/basic',
'avi' => 'video/x-msvideo',
'aw' => 'application/applixware',
'axd' => 'text/plain',
'azf' => 'application/vnd.airzip.filesecure.azf',
'azs' => 'application/vnd.airzip.filesecure.azs',
'azw' => 'application/vnd.amazon.ebook',
'bat' => 'application/x-msdownload',
'bcpio' => 'application/x-bcpio',
'bdf' => 'application/x-font-bdf',
'bdm' => 'application/vnd.syncml.dm+wbxml',
'bed' => 'application/vnd.realvnc.bed',
'bh2' => 'application/vnd.fujitsu.oasysprs',
'bin' => 'application/octet-stream',
'bmi' => 'application/vnd.bmi',
'bmp' => 'image/bmp',
'book' => 'application/vnd.framemaker',
'box' => 'application/vnd.previewsystems.box',
'boz' => 'application/x-bzip2',
'bpk' => 'application/octet-stream',
'btif' => 'image/prs.btif',
'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2',
'c' => 'text/x-c',
'c11amc' => 'application/vnd.cluetrust.cartomobile-config',
'c11amz' => 'application/vnd.cluetrust.cartomobile-config-pkg',
'c4d' => 'application/vnd.clonk.c4group',
'c4f' => 'application/vnd.clonk.c4group',
'c4g' => 'application/vnd.clonk.c4group',
'c4p' => 'application/vnd.clonk.c4group',
'c4u' => 'application/vnd.clonk.c4group',
'cab' => 'application/vnd.ms-cab-compressed',
'car' => 'application/vnd.curl.car',
'cat' => 'application/vnd.ms-pki.seccat',
'cc' => 'text/x-c',
'cct' => 'application/x-director',
'ccxml' => 'application/ccxml+xml',
'cdbcmsg' => 'application/vnd.contact.cmsg',
'cdf' => 'application/x-netcdf',
'cdkey' => 'application/vnd.mediastation.cdkey',
'cdmia' => 'application/cdmi-capability',
'cdmic' => 'application/cdmi-container',
'cdmid' => 'application/cdmi-domain',
'cdmio' => 'application/cdmi-object',
'cdmiq' => 'application/cdmi-queue',
'cdx' => 'chemical/x-cdx',
'cdxml' => 'application/vnd.chemdraw+xml',
'cdy' => 'application/vnd.cinderella',
'cer' => 'application/pkix-cert',
'cfc' => 'application/x-coldfusion',
'cfm' => 'application/x-coldfusion',
'cgm' => 'image/cgm',
'chat' => 'application/x-chat',
'chm' => 'application/vnd.ms-htmlhelp',
'chrt' => 'application/vnd.kde.kchart',
'cif' => 'chemical/x-cif',
'cii' => 'application/vnd.anser-web-certificate-issue-initiation',
'cil' => 'application/vnd.ms-artgalry',
'cla' => 'application/vnd.claymore',
'class' => 'application/java-vm',
'clkk' => 'application/vnd.crick.clicker.keyboard',
'clkp' => 'application/vnd.crick.clicker.palette',
'clkt' => 'application/vnd.crick.clicker.template',
'clkw' => 'application/vnd.crick.clicker.wordbank',
'clkx' => 'application/vnd.crick.clicker',
'clp' => 'application/x-msclip',
'cmc' => 'application/vnd.cosmocaller',
'cmdf' => 'chemical/x-cmdf',
'cml' => 'chemical/x-cml',
'cmp' => 'application/vnd.yellowriver-custom-menu',
'cmx' => 'image/x-cmx',
'cod' => 'application/vnd.rim.cod',
'com' => 'application/x-msdownload',
'conf' => 'text/plain',
'cpio' => 'application/x-cpio',
'cpp' => 'text/x-c',
'cpt' => 'application/mac-compactpro',
'crd' => 'application/x-mscardfile',
'crl' => 'application/pkix-crl',
'crt' => 'application/x-x509-ca-cert',
'cryptonote' => 'application/vnd.rig.cryptonote',
'cs' => 'text/plain',
'csh' => 'application/x-csh',
'csml' => 'chemical/x-csml',
'csp' => 'application/vnd.commonspace',
'css' => 'text/css',
'cst' => 'application/x-director',
'csv' => 'text/csv',
'cu' => 'application/cu-seeme',
'curl' => 'text/vnd.curl',
'cww' => 'application/prs.cww',
'cxt' => 'application/x-director',
'cxx' => 'text/x-c',
'dae' => 'model/vnd.collada+xml',
'daf' => 'application/vnd.mobius.daf',
'dataless' => 'application/vnd.fdsn.seed',
'davmount' => 'application/davmount+xml',
'dcr' => 'application/x-director',
'dcurl' => 'text/vnd.curl.dcurl',
'dd2' => 'application/vnd.oma.dd2+xml',
'ddd' => 'application/vnd.fujixerox.ddd',
'deb' => 'application/x-debian-package',
'def' => 'text/plain',
'deploy' => 'application/octet-stream',
'der' => 'application/x-x509-ca-cert',
'dfac' => 'application/vnd.dreamfactory',
'dic' => 'text/x-c',
'dir' => 'application/x-director',
'dis' => 'application/vnd.mobius.dis',
'dist' => 'application/octet-stream',
'distz' => 'application/octet-stream',
'djv' => 'image/vnd.djvu',
'djvu' => 'image/vnd.djvu',
'dll' => 'application/x-msdownload',
'dmg' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'dna' => 'application/vnd.dna',
'doc' => 'application/msword',
'docm' => 'application/vnd.ms-word.document.macroenabled.12',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dot' => 'application/msword',
'dotm' => 'application/vnd.ms-word.template.macroenabled.12',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'dp' => 'application/vnd.osgi.dp',
'dpg' => 'application/vnd.dpgraph',
'dra' => 'audio/vnd.dra',
'dsc' => 'text/prs.lines.tag',
'dssc' => 'application/dssc+der',
'dtb' => 'application/x-dtbook+xml',
'dtd' => 'application/xml-dtd',
'dts' => 'audio/vnd.dts',
'dtshd' => 'audio/vnd.dts.hd',
'dump' => 'application/octet-stream',
'dvi' => 'application/x-dvi',
'dwf' => 'model/vnd.dwf',
'dwg' => 'image/vnd.dwg',
'dxf' => 'image/vnd.dxf',
'dxp' => 'application/vnd.spotfire.dxp',
'dxr' => 'application/x-director',
'ecelp4800' => 'audio/vnd.nuera.ecelp4800',
'ecelp7470' => 'audio/vnd.nuera.ecelp7470',
'ecelp9600' => 'audio/vnd.nuera.ecelp9600',
'ecma' => 'application/ecmascript',
'edm' => 'application/vnd.novadigm.edm',
'edx' => 'application/vnd.novadigm.edx',
'efif' => 'application/vnd.picsel',
'ei6' => 'application/vnd.pg.osasli',
'elc' => 'application/octet-stream',
'eml' => 'message/rfc822',
'emma' => 'application/emma+xml',
'eol' => 'audio/vnd.digital-winds',
'eot' => 'application/vnd.ms-fontobject',
'eps' => 'application/postscript',
'epub' => 'application/epub+zip',
'es3' => 'application/vnd.eszigno3+xml',
'esf' => 'application/vnd.epson.esf',
'et3' => 'application/vnd.eszigno3+xml',
'etx' => 'text/x-setext',
'exe' => 'application/x-msdownload',
'exi' => 'application/exi',
'ext' => 'application/vnd.novadigm.ext',
'ez' => 'application/andrew-inset',
'ez2' => 'application/vnd.ezpix-album',
'ez3' => 'application/vnd.ezpix-package',
'f' => 'text/x-fortran',
'f4v' => 'video/x-f4v',
'f77' => 'text/x-fortran',
'f90' => 'text/x-fortran',
'fbs' => 'image/vnd.fastbidsheet',
'fcs' => 'application/vnd.isac.fcs',
'fdf' => 'application/vnd.fdf',
'fe_launch' => 'application/vnd.denovo.fcselayout-link',
'fg5' => 'application/vnd.fujitsu.oasysgp',
'fgd' => 'application/x-director',
'fh' => 'image/x-freehand',
'fh4' => 'image/x-freehand',
'fh5' => 'image/x-freehand',
'fh7' => 'image/x-freehand',
'fhc' => 'image/x-freehand',
'fig' => 'application/x-xfig',
'fli' => 'video/x-fli',
'flo' => 'application/vnd.micrografx.flo',
'flv' => 'video/x-flv',
'flw' => 'application/vnd.kde.kivio',
'flx' => 'text/vnd.fmi.flexstor',
'fly' => 'text/vnd.fly',
'fm' => 'application/vnd.framemaker',
'fnc' => 'application/vnd.frogans.fnc',
'for' => 'text/x-fortran',
'fpx' => 'image/vnd.fpx',
'frame' => 'application/vnd.framemaker',
'fsc' => 'application/vnd.fsc.weblaunch',
'fst' => 'image/vnd.fst',
'ftc' => 'application/vnd.fluxtime.clip',
'fti' => 'application/vnd.anser-web-funds-transfer-initiation',
'fvt' => 'video/vnd.fvt',
'fxp' => 'application/vnd.adobe.fxp',
'fxpl' => 'application/vnd.adobe.fxp',
'fzs' => 'application/vnd.fuzzysheet',
'g2w' => 'application/vnd.geoplan',
'g3' => 'image/g3fax',
'g3w' => 'application/vnd.geospace',
'gac' => 'application/vnd.groove-account',
'gdl' => 'model/vnd.gdl',
'geo' => 'application/vnd.dynageo',
'gex' => 'application/vnd.geometry-explorer',
'ggb' => 'application/vnd.geogebra.file',
'ggt' => 'application/vnd.geogebra.tool',
'ghf' => 'application/vnd.groove-help',
'gif' => 'image/gif',
'gim' => 'application/vnd.groove-identity-message',
'gmx' => 'application/vnd.gmx',
'gnumeric' => 'application/x-gnumeric',
'gph' => 'application/vnd.flographit',
'gqf' => 'application/vnd.grafeq',
'gqs' => 'application/vnd.grafeq',
'gram' => 'application/srgs',
'gre' => 'application/vnd.geometry-explorer',
'grv' => 'application/vnd.groove-injector',
'grxml' => 'application/srgs+xml',
'gsf' => 'application/x-font-ghostscript',
'gtar' => 'application/x-gtar',
'gtm' => 'application/vnd.groove-tool-message',
'gtw' => 'model/vnd.gtw',
'gv' => 'text/vnd.graphviz',
'gxt' => 'application/vnd.geonext',
'h' => 'text/x-c',
'h261' => 'video/h261',
'h263' => 'video/h263',
'h264' => 'video/h264',
'hal' => 'application/vnd.hal+xml',
'hbci' => 'application/vnd.hbci',
'hdf' => 'application/x-hdf',
'hh' => 'text/x-c',
'hlp' => 'application/winhlp',
'hpgl' => 'application/vnd.hp-hpgl',
'hpid' => 'application/vnd.hp-hpid',
'hps' => 'application/vnd.hp-hps',
'hqx' => 'application/mac-binhex40',
'hta' => 'application/octet-stream',
'htc' => 'text/html',
'htke' => 'application/vnd.kenameaapp',
'htm' => 'text/html',
'html' => 'text/html',
'hvd' => 'application/vnd.yamaha.hv-dic',
'hvp' => 'application/vnd.yamaha.hv-voice',
'hvs' => 'application/vnd.yamaha.hv-script',
'i2g' => 'application/vnd.intergeo',
'icc' => 'application/vnd.iccprofile',
'ice' => 'x-conference/x-cooltalk',
'icm' => 'application/vnd.iccprofile',
'ico' => 'image/x-icon',
'ics' => 'text/calendar',
'ief' => 'image/ief',
'ifb' => 'text/calendar',
'ifm' => 'application/vnd.shana.informed.formdata',
'iges' => 'model/iges',
'igl' => 'application/vnd.igloader',
'igm' => 'application/vnd.insors.igm',
'igs' => 'model/iges',
'igx' => 'application/vnd.micrografx.igx',
'iif' => 'application/vnd.shana.informed.interchange',
'imp' => 'application/vnd.accpac.simply.imp',
'ims' => 'application/vnd.ms-ims',
'in' => 'text/plain',
'ini' => 'text/plain',
'ipfix' => 'application/ipfix',
'ipk' => 'application/vnd.shana.informed.package',
'irm' => 'application/vnd.ibm.rights-management',
'irp' => 'application/vnd.irepository.package+xml',
'iso' => 'application/octet-stream',
'itp' => 'application/vnd.shana.informed.formtemplate',
'ivp' => 'application/vnd.immervision-ivp',
'ivu' => 'application/vnd.immervision-ivu',
'jad' => 'text/vnd.sun.j2me.app-descriptor',
'jam' => 'application/vnd.jam',
'jar' => 'application/java-archive',
'java' => 'text/x-java-source',
'jisp' => 'application/vnd.jisp',
'jlt' => 'application/vnd.hp-jlyt',
'jnlp' => 'application/x-java-jnlp-file',
'joda' => 'application/vnd.joost.joda-archive',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpgm' => 'video/jpm',
'jpgv' => 'video/jpeg',
'jpm' => 'video/jpm',
'js' => 'text/javascript',
'json' => 'application/json',
'kar' => 'audio/midi',
'karbon' => 'application/vnd.kde.karbon',
'kfo' => 'application/vnd.kde.kformula',
'kia' => 'application/vnd.kidspiration',
'kml' => 'application/vnd.google-earth.kml+xml',
'kmz' => 'application/vnd.google-earth.kmz',
'kne' => 'application/vnd.kinar',
'knp' => 'application/vnd.kinar',
'kon' => 'application/vnd.kde.kontour',
'kpr' => 'application/vnd.kde.kpresenter',
'kpt' => 'application/vnd.kde.kpresenter',
'ksp' => 'application/vnd.kde.kspread',
'ktr' => 'application/vnd.kahootz',
'ktx' => 'image/ktx',
'ktz' => 'application/vnd.kahootz',
'kwd' => 'application/vnd.kde.kword',
'kwt' => 'application/vnd.kde.kword',
'lasxml' => 'application/vnd.las.las+xml',
'latex' => 'application/x-latex',
'lbd' => 'application/vnd.llamagraphics.life-balance.desktop',
'lbe' => 'application/vnd.llamagraphics.life-balance.exchange+xml',
'les' => 'application/vnd.hhe.lesson-player',
'lha' => 'application/octet-stream',
'link66' => 'application/vnd.route66.link66+xml',
'list' => 'text/plain',
'list3820' => 'application/vnd.ibm.modcap',
'listafp' => 'application/vnd.ibm.modcap',
'log' => 'text/plain',
'lostxml' => 'application/lost+xml',
'lrf' => 'application/octet-stream',
'lrm' => 'application/vnd.ms-lrm',
'ltf' => 'application/vnd.frogans.ltf',
'lvp' => 'audio/vnd.lucent.voice',
'lwp' => 'application/vnd.lotus-wordpro',
'lzh' => 'application/octet-stream',
'm13' => 'application/x-msmediaview',
'm14' => 'application/x-msmediaview',
'm1v' => 'video/mpeg',
'm21' => 'application/mp21',
'm2a' => 'audio/mpeg',
'm2v' => 'video/mpeg',
'm3a' => 'audio/mpeg',
'm3u' => 'audio/x-mpegurl',
'm3u8' => 'application/vnd.apple.mpegurl',
'm4a' => 'audio/mp4',
'm4u' => 'video/vnd.mpegurl',
'm4v' => 'video/mp4',
'ma' => 'application/mathematica',
'mads' => 'application/mads+xml',
'mag' => 'application/vnd.ecowin.chart',
'maker' => 'application/vnd.framemaker',
'man' => 'text/troff',
'mathml' => 'application/mathml+xml',
'mb' => 'application/mathematica',
'mbk' => 'application/vnd.mobius.mbk',
'mbox' => 'application/mbox',
'mc1' => 'application/vnd.medcalcdata',
'mcd' => 'application/vnd.mcd',
'mcurl' => 'text/vnd.curl.mcurl',
'mdb' => 'application/x-msaccess',
'mdi' => 'image/vnd.ms-modi',
'me' => 'text/troff',
'mesh' => 'model/mesh',
'meta4' => 'application/metalink4+xml',
'mets' => 'application/mets+xml',
'mfm' => 'application/vnd.mfmp',
'mgp' => 'application/vnd.osgeo.mapguide.package',
'mgz' => 'application/vnd.proteus.magazine',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mif' => 'application/vnd.mif',
'mime' => 'message/rfc822',
'mj2' => 'video/mj2',
'mjp2' => 'video/mj2',
'mlp' => 'application/vnd.dolby.mlp',
'mmd' => 'application/vnd.chipnuts.karaoke-mmd',
'mmf' => 'application/vnd.smaf',
'mmr' => 'image/vnd.fujixerox.edmics-mmr',
'mny' => 'application/x-msmoney',
'mobi' => 'application/x-mobipocket-ebook',
'mods' => 'application/mods+xml',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mp2' => 'audio/mpeg',
'mp21' => 'application/mp21',
'mp2a' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mp4a' => 'audio/mp4',
'mp4s' => 'application/mp4',
'mp4v' => 'video/mp4',
'mpc' => 'application/vnd.mophun.certificate',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpg4' => 'video/mp4',
'mpga' => 'audio/mpeg',
'mpkg' => 'application/vnd.apple.installer+xml',
'mpm' => 'application/vnd.blueice.multipass',
'mpn' => 'application/vnd.mophun.application',
'mpp' => 'application/vnd.ms-project',
'mpt' => 'application/vnd.ms-project',
'mpy' => 'application/vnd.ibm.minipay',
'mqy' => 'application/vnd.mobius.mqy',
'mrc' => 'application/marc',
'mrcx' => 'application/marcxml+xml',
'ms' => 'text/troff',
'mscml' => 'application/mediaservercontrol+xml',
'mseed' => 'application/vnd.fdsn.mseed',
'mseq' => 'application/vnd.mseq',
'msf' => 'application/vnd.epson.msf',
'msh' => 'model/mesh',
'msi' => 'application/x-msdownload',
'msl' => 'application/vnd.mobius.msl',
'msty' => 'application/vnd.muvee.style',
'mts' => 'model/vnd.mts',
'mus' => 'application/vnd.musician',
'musicxml' => 'application/vnd.recordare.musicxml+xml',
'mvb' => 'application/x-msmediaview',
'mwf' => 'application/vnd.mfer',
'mxf' => 'application/mxf',
'mxl' => 'application/vnd.recordare.musicxml',
'mxml' => 'application/xv+xml',
'mxs' => 'application/vnd.triscape.mxs',
'mxu' => 'video/vnd.mpegurl',
'n-gage' => 'application/vnd.nokia.n-gage.symbian.install',
'n3' => 'text/n3',
'nb' => 'application/mathematica',
'nbp' => 'application/vnd.wolfram.player',
'nc' => 'application/x-netcdf',
'ncx' => 'application/x-dtbncx+xml',
'ngdat' => 'application/vnd.nokia.n-gage.data',
'nlu' => 'application/vnd.neurolanguage.nlu',
'nml' => 'application/vnd.enliven',
'nnd' => 'application/vnd.noblenet-directory',
'nns' => 'application/vnd.noblenet-sealer',
'nnw' => 'application/vnd.noblenet-web',
'npx' => 'image/vnd.net-fpx',
'nsf' => 'application/vnd.lotus-notes',
'oa2' => 'application/vnd.fujitsu.oasys2',
'oa3' => 'application/vnd.fujitsu.oasys3',
'oas' => 'application/vnd.fujitsu.oasys',
'obd' => 'application/x-msbinder',
'oda' => 'application/oda',
'odb' => 'application/vnd.oasis.opendocument.database',
'odc' => 'application/vnd.oasis.opendocument.chart',
'odf' => 'application/vnd.oasis.opendocument.formula',
'odft' => 'application/vnd.oasis.opendocument.formula-template',
'odg' => 'application/vnd.oasis.opendocument.graphics',
'odi' => 'application/vnd.oasis.opendocument.image',
'odm' => 'application/vnd.oasis.opendocument.text-master',
'odp' => 'application/vnd.oasis.opendocument.presentation',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
'odt' => 'application/vnd.oasis.opendocument.text',
'oga' => 'audio/ogg',
'ogg' => 'audio/ogg',
'ogv' => 'video/ogg',
'ogx' => 'application/ogg',
'onepkg' => 'application/onenote',
'onetmp' => 'application/onenote',
'onetoc' => 'application/onenote',
'onetoc2' => 'application/onenote',
'opf' => 'application/oebps-package+xml',
'oprc' => 'application/vnd.palm',
'org' => 'application/vnd.lotus-organizer',
'osf' => 'application/vnd.yamaha.openscoreformat',
'osfpvg' => 'application/vnd.yamaha.openscoreformat.osfpvg+xml',
'otc' => 'application/vnd.oasis.opendocument.chart-template',
'otf' => 'application/x-font-otf',
'otg' => 'application/vnd.oasis.opendocument.graphics-template',
'oth' => 'application/vnd.oasis.opendocument.text-web',
'oti' => 'application/vnd.oasis.opendocument.image-template',
'otp' => 'application/vnd.oasis.opendocument.presentation-template',
'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template',
'ott' => 'application/vnd.oasis.opendocument.text-template',
'oxt' => 'application/vnd.openofficeorg.extension',
'p' => 'text/x-pascal',
'p10' => 'application/pkcs10',
'p12' => 'application/x-pkcs12',
'p7b' => 'application/x-pkcs7-certificates',
'p7c' => 'application/pkcs7-mime',
'p7m' => 'application/pkcs7-mime',
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'p8' => 'application/pkcs8',
'pas' => 'text/x-pascal',
'paw' => 'application/vnd.pawaafile',
'pbd' => 'application/vnd.powerbuilder6',
'pbm' => 'image/x-portable-bitmap',
'pcf' => 'application/x-font-pcf',
'pcl' => 'application/vnd.hp-pcl',
'pclxl' => 'application/vnd.hp-pclxl',
'pct' => 'image/x-pict',
'pcurl' => 'application/vnd.curl.pcurl',
'pcx' => 'image/x-pcx',
'pdb' => 'application/vnd.palm',
'pdf' => 'application/pdf',
'pfa' => 'application/x-font-type1',
'pfb' => 'application/x-font-type1',
'pfm' => 'application/x-font-type1',
'pfr' => 'application/font-tdpfr',
'pfx' => 'application/x-pkcs12',
'pgm' => 'image/x-portable-graymap',
'pgn' => 'application/x-chess-pgn',
'pgp' => 'application/pgp-encrypted',
'php' => 'text/x-php',
'phps' => 'application/x-httpd-phps',
'pic' => 'image/x-pict',
'pkg' => 'application/octet-stream',
'pki' => 'application/pkixcmp',
'pkipath' => 'application/pkix-pkipath',
'plb' => 'application/vnd.3gpp.pic-bw-large',
'plc' => 'application/vnd.mobius.plc',
'plf' => 'application/vnd.pocketlearn',
'pls' => 'application/pls+xml',
'pml' => 'application/vnd.ctc-posml',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'portpkg' => 'application/vnd.macports.portpkg',
'pot' => 'application/vnd.ms-powerpoint',
'potm' => 'application/vnd.ms-powerpoint.template.macroenabled.12',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppam' => 'application/vnd.ms-powerpoint.addin.macroenabled.12',
'ppd' => 'application/vnd.cups-ppd',
'ppm' => 'image/x-portable-pixmap',
'pps' => 'application/vnd.ms-powerpoint',
'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroenabled.12',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'ppt' => 'application/vnd.ms-powerpoint',
'pptm' => 'application/vnd.ms-powerpoint.presentation.macroenabled.12',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'pqa' => 'application/vnd.palm',
'prc' => 'application/x-mobipocket-ebook',
'pre' => 'application/vnd.lotus-freelance',
'prf' => 'application/pics-rules',
'ps' => 'application/postscript',
'psb' => 'application/vnd.3gpp.pic-bw-small',
'psd' => 'image/vnd.adobe.photoshop',
'psf' => 'application/x-font-linux-psf',
'pskcxml' => 'application/pskc+xml',
'ptid' => 'application/vnd.pvi.ptid1',
'pub' => 'application/x-mspublisher',
'pvb' => 'application/vnd.3gpp.pic-bw-var',
'pwn' => 'application/vnd.3m.post-it-notes',
'pya' => 'audio/vnd.ms-playready.media.pya',
'pyv' => 'video/vnd.ms-playready.media.pyv',
'qam' => 'application/vnd.epson.quickanime',
'qbo' => 'application/vnd.intu.qbo',
'qfx' => 'application/vnd.intu.qfx',
'qps' => 'application/vnd.publishare-delta-tree',
'qt' => 'video/quicktime',
'qwd' => 'application/vnd.quark.quarkxpress',
'qwt' => 'application/vnd.quark.quarkxpress',
'qxb' => 'application/vnd.quark.quarkxpress',
'qxd' => 'application/vnd.quark.quarkxpress',
'qxl' => 'application/vnd.quark.quarkxpress',
'qxt' => 'application/vnd.quark.quarkxpress',
'ra' => 'audio/x-pn-realaudio',
'ram' => 'audio/x-pn-realaudio',
'rar' => 'application/x-rar-compressed',
'ras' => 'image/x-cmu-raster',
'rb' => 'text/plain',
'rcprofile' => 'application/vnd.ipunplugged.rcprofile',
'rdf' => 'application/rdf+xml',
'rdz' => 'application/vnd.data-vision.rdz',
'rep' => 'application/vnd.businessobjects',
'res' => 'application/x-dtbresource+xml',
'resx' => 'text/xml',
'rgb' => 'image/x-rgb',
'rif' => 'application/reginfo+xml',
'rip' => 'audio/vnd.rip',
'rl' => 'application/resource-lists+xml',
'rlc' => 'image/vnd.fujixerox.edmics-rlc',
'rld' => 'application/resource-lists-diff+xml',
'rm' => 'application/vnd.rn-realmedia',
'rmi' => 'audio/midi',
'rmp' => 'audio/x-pn-realaudio-plugin',
'rms' => 'application/vnd.jcp.javame.midlet-rms',
'rnc' => 'application/relax-ng-compact-syntax',
'roff' => 'text/troff',
'rp9' => 'application/vnd.cloanto.rp9',
'rpss' => 'application/vnd.nokia.radio-presets',
'rpst' => 'application/vnd.nokia.radio-preset',
'rq' => 'application/sparql-query',
'rs' => 'application/rls-services+xml',
'rsd' => 'application/rsd+xml',
'rss' => 'application/rss+xml',
'rtf' => 'application/rtf',
'rtx' => 'text/richtext',
's' => 'text/x-asm',
'saf' => 'application/vnd.yamaha.smaf-audio',
'sbml' => 'application/sbml+xml',
'sc' => 'application/vnd.ibm.secure-container',
'scd' => 'application/x-msschedule',
'scm' => 'application/vnd.lotus-screencam',
'scq' => 'application/scvp-cv-request',
'scs' => 'application/scvp-cv-response',
'scurl' => 'text/vnd.curl.scurl',
'sda' => 'application/vnd.stardivision.draw',
'sdc' => 'application/vnd.stardivision.calc',
'sdd' => 'application/vnd.stardivision.impress',
'sdkd' => 'application/vnd.solent.sdkm+xml',
'sdkm' => 'application/vnd.solent.sdkm+xml',
'sdp' => 'application/sdp',
'sdw' => 'application/vnd.stardivision.writer',
'see' => 'application/vnd.seemail',
'seed' => 'application/vnd.fdsn.seed',
'sema' => 'application/vnd.sema',
'semd' => 'application/vnd.semd',
'semf' => 'application/vnd.semf',
'ser' => 'application/java-serialized-object',
'setpay' => 'application/set-payment-initiation',
'setreg' => 'application/set-registration-initiation',
'sfd-hdstx' => 'application/vnd.hydrostatix.sof-data',
'sfs' => 'application/vnd.spotfire.sfs',
'sgl' => 'application/vnd.stardivision.writer-global',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'shf' => 'application/shf+xml',
'sig' => 'application/pgp-signature',
'silo' => 'model/mesh',
'sis' => 'application/vnd.symbian.install',
'sisx' => 'application/vnd.symbian.install',
'sit' => 'application/x-stuffit',
'sitx' => 'application/x-stuffitx',
'skd' => 'application/vnd.koan',
'skm' => 'application/vnd.koan',
'skp' => 'application/vnd.koan',
'skt' => 'application/vnd.koan',
'sldm' => 'application/vnd.ms-powerpoint.slide.macroenabled.12',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'slt' => 'application/vnd.epson.salt',
'sm' => 'application/vnd.stepmania.stepchart',
'smf' => 'application/vnd.stardivision.math',
'smi' => 'application/smil+xml',
'smil' => 'application/smil+xml',
'snd' => 'audio/basic',
'snf' => 'application/x-font-snf',
'so' => 'application/octet-stream',
'spc' => 'application/x-pkcs7-certificates',
'spf' => 'application/vnd.yamaha.smaf-phrase',
'spl' => 'application/x-futuresplash',
'spot' => 'text/vnd.in3d.spot',
'spp' => 'application/scvp-vp-response',
'spq' => 'application/scvp-vp-request',
'spx' => 'audio/ogg',
'src' => 'application/x-wais-source',
'sru' => 'application/sru+xml',
'srx' => 'application/sparql-results+xml',
'sse' => 'application/vnd.kodak-descriptor',
'ssf' => 'application/vnd.epson.ssf',
'ssml' => 'application/ssml+xml',
'st' => 'application/vnd.sailingtracker.track',
'stc' => 'application/vnd.sun.xml.calc.template',
'std' => 'application/vnd.sun.xml.draw.template',
'stf' => 'application/vnd.wt.stf',
'sti' => 'application/vnd.sun.xml.impress.template',
'stk' => 'application/hyperstudio',
'stl' => 'application/vnd.ms-pki.stl',
'str' => 'application/vnd.pg.format',
'stw' => 'application/vnd.sun.xml.writer.template',
'sub' => 'image/vnd.dvb.subtitle',
'sus' => 'application/vnd.sus-calendar',
'susp' => 'application/vnd.sus-calendar',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'svc' => 'application/vnd.dvb.service',
'svd' => 'application/vnd.svd',
'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml',
'swa' => 'application/x-director',
'swf' => 'application/x-shockwave-flash',
'swi' => 'application/vnd.aristanetworks.swi',
'sxc' => 'application/vnd.sun.xml.calc',
'sxd' => 'application/vnd.sun.xml.draw',
'sxg' => 'application/vnd.sun.xml.writer.global',
'sxi' => 'application/vnd.sun.xml.impress',
'sxm' => 'application/vnd.sun.xml.math',
'sxw' => 'application/vnd.sun.xml.writer',
't' => 'text/troff',
'tao' => 'application/vnd.tao.intent-module-archive',
'tar' => 'application/x-tar',
'tcap' => 'application/vnd.3gpp2.tcap',
'tcl' => 'application/x-tcl',
'teacher' => 'application/vnd.smart.teacher',
'tei' => 'application/tei+xml',
'teicorpus' => 'application/tei+xml',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'text' => 'text/plain',
'tfi' => 'application/thraud+xml',
'tfm' => 'application/x-tex-tfm',
'thmx' => 'application/vnd.ms-officetheme',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'tmo' => 'application/vnd.tmobile-livetv',
'torrent' => 'application/x-bittorrent',
'tpl' => 'application/vnd.groove-tool-template',
'tpt' => 'application/vnd.trid.tpt',
'tr' => 'text/troff',
'tra' => 'application/vnd.trueapp',
'trm' => 'application/x-msterminal',
'tsd' => 'application/timestamped-data',
'tsv' => 'text/tab-separated-values',
'ttc' => 'application/x-font-ttf',
'ttf' => 'application/x-font-ttf',
'ttl' => 'text/turtle',
'twd' => 'application/vnd.simtech-mindmapper',
'twds' => 'application/vnd.simtech-mindmapper',
'txd' => 'application/vnd.genomatix.tuxedo',
'txf' => 'application/vnd.mobius.txf',
'txt' => 'text/plain',
'u32' => 'application/x-authorware-bin',
'udeb' => 'application/x-debian-package',
'ufd' => 'application/vnd.ufdl',
'ufdl' => 'application/vnd.ufdl',
'umj' => 'application/vnd.umajin',
'unityweb' => 'application/vnd.unity',
'uoml' => 'application/vnd.uoml+xml',
'uri' => 'text/uri-list',
'uris' => 'text/uri-list',
'urls' => 'text/uri-list',
'ustar' => 'application/x-ustar',
'utz' => 'application/vnd.uiq.theme',
'uu' => 'text/x-uuencode',
'uva' => 'audio/vnd.dece.audio',
'uvd' => 'application/vnd.dece.data',
'uvf' => 'application/vnd.dece.data',
'uvg' => 'image/vnd.dece.graphic',
'uvh' => 'video/vnd.dece.hd',
'uvi' => 'image/vnd.dece.graphic',
'uvm' => 'video/vnd.dece.mobile',
'uvp' => 'video/vnd.dece.pd',
'uvs' => 'video/vnd.dece.sd',
'uvt' => 'application/vnd.dece.ttml+xml',
'uvu' => 'video/vnd.uvvu.mp4',
'uvv' => 'video/vnd.dece.video',
'uvva' => 'audio/vnd.dece.audio',
'uvvd' => 'application/vnd.dece.data',
'uvvf' => 'application/vnd.dece.data',
'uvvg' => 'image/vnd.dece.graphic',
'uvvh' => 'video/vnd.dece.hd',
'uvvi' => 'image/vnd.dece.graphic',
'uvvm' => 'video/vnd.dece.mobile',
'uvvp' => 'video/vnd.dece.pd',
'uvvs' => 'video/vnd.dece.sd',
'uvvt' => 'application/vnd.dece.ttml+xml',
'uvvu' => 'video/vnd.uvvu.mp4',
'uvvv' => 'video/vnd.dece.video',
'uvvx' => 'application/vnd.dece.unspecified',
'uvx' => 'application/vnd.dece.unspecified',
'vcd' => 'application/x-cdlink',
'vcf' => 'text/x-vcard',
'vcg' => 'application/vnd.groove-vcard',
'vcs' => 'text/x-vcalendar',
'vcx' => 'application/vnd.vcx',
'vis' => 'application/vnd.visionary',
'viv' => 'video/vnd.vivo',
'vor' => 'application/vnd.stardivision.writer',
'vox' => 'application/x-authorware-bin',
'vrml' => 'model/vrml',
'vsd' => 'application/vnd.visio',
'vsf' => 'application/vnd.vsf',
'vss' => 'application/vnd.visio',
'vst' => 'application/vnd.visio',
'vsw' => 'application/vnd.visio',
'vtu' => 'model/vnd.vtu',
'vxml' => 'application/voicexml+xml',
'w3d' => 'application/x-director',
'wad' => 'application/x-doom',
'wav' => 'audio/x-wav',
'wax' => 'audio/x-ms-wax',
'wbmp' => 'image/vnd.wap.wbmp',
'wbs' => 'application/vnd.criticaltools.wbs+xml',
'wbxml' => 'application/vnd.wap.wbxml',
'wcm' => 'application/vnd.ms-works',
'wdb' => 'application/vnd.ms-works',
'weba' => 'audio/webm',
'webm' => 'video/webm',
'webp' => 'image/webp',
'wg' => 'application/vnd.pmi.widget',
'wgt' => 'application/widget',
'wks' => 'application/vnd.ms-works',
'wm' => 'video/x-ms-wm',
'wma' => 'audio/x-ms-wma',
'wmd' => 'application/x-ms-wmd',
'wmf' => 'application/x-msmetafile',
'wml' => 'text/vnd.wap.wml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmls' => 'text/vnd.wap.wmlscript',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'wmv' => 'video/x-ms-wmv',
'wmx' => 'video/x-ms-wmx',
'wmz' => 'application/x-ms-wmz',
'woff' => 'application/x-font-woff',
'wpd' => 'application/vnd.wordperfect',
'wpl' => 'application/vnd.ms-wpl',
'wps' => 'application/vnd.ms-works',
'wqd' => 'application/vnd.wqd',
'wri' => 'application/x-mswrite',
'wrl' => 'model/vrml',
'wsdl' => 'application/wsdl+xml',
'wspolicy' => 'application/wspolicy+xml',
'wtb' => 'application/vnd.webturbo',
'wvx' => 'video/x-ms-wvx',
'x32' => 'application/x-authorware-bin',
'x3d' => 'application/vnd.hzn-3d-crossword',
'xap' => 'application/x-silverlight-app',
'xar' => 'application/vnd.xara',
'xbap' => 'application/x-ms-xbap',
'xbd' => 'application/vnd.fujixerox.docuworks.binder',
'xbm' => 'image/x-xbitmap',
'xdf' => 'application/xcap-diff+xml',
'xdm' => 'application/vnd.syncml.dm+xml',
'xdp' => 'application/vnd.adobe.xdp+xml',
'xdssc' => 'application/dssc+xml',
'xdw' => 'application/vnd.fujixerox.docuworks',
'xenc' => 'application/xenc+xml',
'xer' => 'application/patch-ops-error+xml',
'xfdf' => 'application/vnd.adobe.xfdf',
'xfdl' => 'application/vnd.xfdl',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xhvml' => 'application/xv+xml',
'xif' => 'image/vnd.xiff',
'xla' => 'application/vnd.ms-excel',
'xlam' => 'application/vnd.ms-excel.addin.macroenabled.12',
'xlc' => 'application/vnd.ms-excel',
'xlm' => 'application/vnd.ms-excel',
'xls' => 'application/vnd.ms-excel',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroenabled.12',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xlt' => 'application/vnd.ms-excel',
'xltm' => 'application/vnd.ms-excel.template.macroenabled.12',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'xlw' => 'application/vnd.ms-excel',
'xml' => 'application/xml',
'xo' => 'application/vnd.olpc-sugar',
'xop' => 'application/xop+xml',
'xpi' => 'application/x-xpinstall',
'xpm' => 'image/x-xpixmap',
'xpr' => 'application/vnd.is-xpr',
'xps' => 'application/vnd.ms-xpsdocument',
'xpw' => 'application/vnd.intercon.formnet',
'xpx' => 'application/vnd.intercon.formnet',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xsm' => 'application/vnd.syncml+xml',
'xspf' => 'application/xspf+xml',
'xul' => 'application/vnd.mozilla.xul+xml',
'xvm' => 'application/xv+xml',
'xvml' => 'application/xv+xml',
'xwd' => 'image/x-xwindowdump',
'xyz' => 'chemical/x-xyz',
'yaml' => 'text/yaml',
'yang' => 'application/yang',
'yin' => 'application/yin+xml',
'yml' => 'text/yaml',
'zaz' => 'application/vnd.zzazz.deck+xml',
'zip' => 'application/zip',
'zir' => 'application/vnd.zul',
'zirz' => 'application/vnd.zul',
'zmm' => 'application/vnd.handheld-entertainment+xml'
);
/**
* Get a singleton instance of the class
*
* @return self
* @codeCoverageIgnore
*/
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Get a mimetype value from a file extension
*
* @param string $extension File extension
*
* @return string|null
*
*/
public function fromExtension($extension)
{
$extension = strtolower($extension);
return isset($this->mimetypes[$extension])
? $this->mimetypes[$extension]
: null;
}
/**
* Get a mimetype from a filename
*
* @param string $filename Filename to generate a mimetype from
*
* @return string|null
*/
public function fromFilename($filename)
{
return $this->fromExtension(pathinfo($filename, PATHINFO_EXTENSION));
}
}

View File

@@ -1,109 +0,0 @@
<?php
namespace GuzzleHttp\Post;
use GuzzleHttp\Stream\AppendStream;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Stream\StreamDecoratorTrait;
use GuzzleHttp\Stream\StreamInterface;
/**
* Stream that when read returns bytes for a streaming multipart/form-data body
*/
class MultipartBody implements StreamInterface
{
use StreamDecoratorTrait;
private $boundary;
/**
* @param array $fields Associative array of field names to values where
* each value is a string or array of strings.
* @param array $files Associative array of PostFileInterface objects
* @param string $boundary You can optionally provide a specific boundary
* @throws \InvalidArgumentException
*/
public function __construct(
array $fields = [],
array $files = [],
$boundary = null
) {
$this->boundary = $boundary ?: uniqid();
$this->stream = $this->createStream($fields, $files);
}
/**
* Get the boundary
*
* @return string
*/
public function getBoundary()
{
return $this->boundary;
}
public function isWritable()
{
return false;
}
/**
* Get the string needed to transfer a POST field
*/
private function getFieldString($name, $value)
{
return sprintf(
"--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n",
$this->boundary,
$name,
$value
);
}
/**
* Get the headers needed before transferring the content of a POST file
*/
private function getFileHeaders(PostFileInterface $file)
{
$headers = '';
foreach ($file->getHeaders() as $key => $value) {
$headers .= "{$key}: {$value}\r\n";
}
return "--{$this->boundary}\r\n" . trim($headers) . "\r\n\r\n";
}
/**
* Create the aggregate stream that will be used to upload the POST data
*/
protected function createStream(array $fields, array $files)
{
$stream = new AppendStream();
foreach ($fields as $name => $fieldValues) {
foreach ((array) $fieldValues as $value) {
$stream->addStream(
Stream::factory($this->getFieldString($name, $value))
);
}
}
foreach ($files as $file) {
if (!$file instanceof PostFileInterface) {
throw new \InvalidArgumentException('All POST fields must '
. 'implement PostFieldInterface');
}
$stream->addStream(
Stream::factory($this->getFileHeaders($file))
);
$stream->addStream($file->getContent());
$stream->addStream(Stream::factory("\r\n"));
}
// Add the trailing boundary with CRLF
$stream->addStream(Stream::factory("--{$this->boundary}--\r\n"));
return $stream;
}
}

View File

@@ -1,287 +0,0 @@
<?php
namespace GuzzleHttp\Post;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Stream\Exception\CannotAttachException;
use GuzzleHttp\Stream\StreamInterface;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Query;
/**
* Holds POST fields and files and creates a streaming body when read methods
* are called on the object.
*/
class PostBody implements PostBodyInterface
{
/** @var StreamInterface */
private $body;
/** @var callable */
private $aggregator;
private $fields = [];
/** @var PostFileInterface[] */
private $files = [];
private $forceMultipart = false;
private $detached = false;
/**
* Applies request headers to a request based on the POST state
*
* @param RequestInterface $request Request to update
*/
public function applyRequestHeaders(RequestInterface $request)
{
if ($this->files || $this->forceMultipart) {
$request->setHeader(
'Content-Type',
'multipart/form-data; boundary=' . $this->getBody()->getBoundary()
);
} elseif ($this->fields && !$request->hasHeader('Content-Type')) {
$request->setHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
}
if ($size = $this->getSize()) {
$request->setHeader('Content-Length', $size);
}
}
public function forceMultipartUpload($force)
{
$this->forceMultipart = $force;
}
public function setAggregator(callable $aggregator)
{
$this->aggregator = $aggregator;
}
public function setField($name, $value)
{
$this->fields[$name] = $value;
$this->mutate();
}
public function replaceFields(array $fields)
{
$this->fields = $fields;
$this->mutate();
}
public function getField($name)
{
return isset($this->fields[$name]) ? $this->fields[$name] : null;
}
public function removeField($name)
{
unset($this->fields[$name]);
$this->mutate();
}
public function getFields($asString = false)
{
if (!$asString) {
return $this->fields;
}
$query = new Query($this->fields);
$query->setEncodingType(Query::RFC1738);
$query->setAggregator($this->getAggregator());
return (string) $query;
}
public function hasField($name)
{
return isset($this->fields[$name]);
}
public function getFile($name)
{
foreach ($this->files as $file) {
if ($file->getName() == $name) {
return $file;
}
}
return null;
}
public function getFiles()
{
return $this->files;
}
public function addFile(PostFileInterface $file)
{
$this->files[] = $file;
$this->mutate();
}
public function clearFiles()
{
$this->files = [];
$this->mutate();
}
/**
* Returns the numbers of fields + files
*
* @return int
*/
public function count()
{
return count($this->files) + count($this->fields);
}
public function __toString()
{
return (string) $this->getBody();
}
public function getContents($maxLength = -1)
{
return $this->getBody()->getContents();
}
public function close()
{
$this->detach();
}
public function detach()
{
$this->detached = true;
$this->fields = $this->files = [];
if ($this->body) {
$this->body->close();
$this->body = null;
}
}
public function attach($stream)
{
throw new CannotAttachException();
}
public function eof()
{
return $this->getBody()->eof();
}
public function tell()
{
return $this->body ? $this->body->tell() : 0;
}
public function isSeekable()
{
return true;
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return false;
}
public function getSize()
{
return $this->getBody()->getSize();
}
public function seek($offset, $whence = SEEK_SET)
{
return $this->getBody()->seek($offset, $whence);
}
public function read($length)
{
return $this->getBody()->read($length);
}
public function write($string)
{
return false;
}
public function getMetadata($key = null)
{
return $key ? null : [];
}
/**
* Return a stream object that is built from the POST fields and files.
*
* If one has already been created, the previously created stream will be
* returned.
*/
private function getBody()
{
if ($this->body) {
return $this->body;
} elseif ($this->files || $this->forceMultipart) {
return $this->body = $this->createMultipart();
} elseif ($this->fields) {
return $this->body = $this->createUrlEncoded();
} else {
return $this->body = Stream::factory();
}
}
/**
* Get the aggregator used to join multi-valued field parameters
*
* @return callable
*/
final protected function getAggregator()
{
if (!$this->aggregator) {
$this->aggregator = Query::phpAggregator();
}
return $this->aggregator;
}
/**
* Creates a multipart/form-data body stream
*
* @return MultipartBody
*/
private function createMultipart()
{
// Flatten the nested query string values using the correct aggregator
return new MultipartBody(
call_user_func($this->getAggregator(), $this->fields),
$this->files
);
}
/**
* Creates an application/x-www-form-urlencoded stream body
*
* @return StreamInterface
*/
private function createUrlEncoded()
{
return Stream::factory($this->getFields(true));
}
/**
* Get rid of any cached data
*/
private function mutate()
{
$this->body = null;
}
}

View File

@@ -1,109 +0,0 @@
<?php
namespace GuzzleHttp\Post;
use GuzzleHttp\Message\AppliesHeadersInterface;
use GuzzleHttp\Stream\StreamInterface;
/**
* Represents a POST body that is sent as either a multipart/form-data stream
* or application/x-www-urlencoded stream.
*/
interface PostBodyInterface extends StreamInterface, \Countable, AppliesHeadersInterface
{
/**
* Set a specific field
*
* @param string $name Name of the field to set
* @param string|array $value Value to set
*/
public function setField($name, $value);
/**
* Set the aggregation strategy that will be used to turn multi-valued
* fields into a string.
*
* The aggregation function accepts a deeply nested array of query string
* values and returns a flattened associative array of key value pairs.
*
* @param callable $aggregator
*/
public function setAggregator(callable $aggregator);
/**
* Set to true to force a multipart upload even if there are no files.
*
* @param bool $force Set to true to force multipart uploads or false to
* remove this flag.
*/
public function forceMultipartUpload($force);
/**
* Replace all existing form fields with an array of fields
*
* @param array $fields Associative array of fields to set
*/
public function replaceFields(array $fields);
/**
* Get a specific field by name
*
* @param string $name Name of the POST field to retrieve
*
* @return string|null
*/
public function getField($name);
/**
* Remove a field by name
*
* @param string $name Name of the field to remove
*/
public function removeField($name);
/**
* Returns an associative array of names to values or a query string.
*
* @param bool $asString Set to true to retrieve the fields as a query
* string.
*
* @return array|string
*/
public function getFields($asString = false);
/**
* Returns true if a field is set
*
* @param string $name Name of the field to set
*
* @return bool
*/
public function hasField($name);
/**
* Get all of the files
*
* @return array Returns an array of PostFileInterface objects
*/
public function getFiles();
/**
* Get a POST file by name.
*
* @param string $name Name of the POST file to retrieve
*
* @return PostFileInterface|null
*/
public function getFile($name);
/**
* Add a file to the POST
*
* @param PostFileInterface $file File to add
*/
public function addFile(PostFileInterface $file);
/**
* Remove all files from the collection
*/
public function clearFiles();
}

View File

@@ -1,135 +0,0 @@
<?php
namespace GuzzleHttp\Post;
use GuzzleHttp\Mimetypes;
use GuzzleHttp\Stream\StreamInterface;
use GuzzleHttp\Stream\Stream;
/**
* Post file upload
*/
class PostFile implements PostFileInterface
{
private $name;
private $filename;
private $content;
private $headers = [];
/**
* @param string $name Name of the form field
* @param mixed $content Data to send
* @param string|null $filename Filename content-disposition attribute
* @param array $headers Array of headers to set on the file
* (can override any default headers)
* @throws \RuntimeException when filename is not passed or can't be determined
*/
public function __construct(
$name,
$content,
$filename = null,
array $headers = []
) {
$this->headers = $headers;
$this->name = $name;
$this->prepareContent($content);
$this->prepareFilename($filename);
$this->prepareDefaultHeaders();
}
public function getName()
{
return $this->name;
}
public function getFilename()
{
return $this->filename;
}
public function getContent()
{
return $this->content;
}
public function getHeaders()
{
return $this->headers;
}
/**
* Prepares the contents of a POST file.
*
* @param mixed $content Content of the POST file
*/
private function prepareContent($content)
{
$this->content = $content;
if (!($this->content instanceof StreamInterface)) {
$this->content = Stream::factory($this->content);
} elseif ($this->content instanceof MultipartBody) {
if (!$this->hasHeader('Content-Disposition')) {
$disposition = 'form-data; name="' . $this->name .'"';
$this->headers['Content-Disposition'] = $disposition;
}
if (!$this->hasHeader('Content-Type')) {
$this->headers['Content-Type'] = sprintf(
"multipart/form-data; boundary=%s",
$this->content->getBoundary()
);
}
}
}
/**
* Applies a file name to the POST file based on various checks.
*
* @param string|null $filename Filename to apply (or null to guess)
*/
private function prepareFilename($filename)
{
$this->filename = $filename;
if (!$this->filename) {
$this->filename = $this->content->getMetadata('uri');
}
if (!$this->filename || substr($this->filename, 0, 6) === 'php://') {
$this->filename = $this->name;
}
}
/**
* Applies default Content-Disposition and Content-Type headers if needed.
*/
private function prepareDefaultHeaders()
{
// Set a default content-disposition header if one was no provided
if (!$this->hasHeader('Content-Disposition')) {
$this->headers['Content-Disposition'] = sprintf(
'form-data; name="%s"; filename="%s"',
$this->name,
basename($this->filename)
);
}
// Set a default Content-Type if one was not supplied
if (!$this->hasHeader('Content-Type')) {
$this->headers['Content-Type'] = Mimetypes::getInstance()
->fromFilename($this->filename) ?: 'text/plain';
}
}
/**
* Check if a specific header exists on the POST file by name.
*
* @param string $name Case-insensitive header to check
*
* @return bool
*/
private function hasHeader($name)
{
return isset(array_change_key_case($this->headers)[strtolower($name)]);
}
}

View File

@@ -1,41 +0,0 @@
<?php
namespace GuzzleHttp\Post;
use GuzzleHttp\Stream\StreamInterface;
/**
* Post file upload interface
*/
interface PostFileInterface
{
/**
* Get the name of the form field
*
* @return string
*/
public function getName();
/**
* Get the full path to the file
*
* @return string
*/
public function getFilename();
/**
* Get the content
*
* @return StreamInterface
*/
public function getContent();
/**
* Gets all POST file headers.
*
* The keys represent the header name as it will be sent over the wire, and
* each value is a string.
*
* @return array Returns an associative array of the file's headers.
*/
public function getHeaders();
}

View File

@@ -1,204 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* Manages query string variables and can aggregate them into a string
*/
class Query extends Collection
{
const RFC3986 = 'RFC3986';
const RFC1738 = 'RFC1738';
/** @var callable Encoding function */
private $encoding = 'rawurlencode';
/** @var callable */
private $aggregator;
/**
* Parse a query string into a Query object
*
* $urlEncoding is used to control how the query string is parsed and how
* it is ultimately serialized. The value can be set to one of the
* following:
*
* - true: (default) Parse query strings using RFC 3986 while still
* converting "+" to " ".
* - false: Disables URL decoding of the input string and URL encoding when
* the query string is serialized.
* - 'RFC3986': Use RFC 3986 URL encoding/decoding
* - 'RFC1738': Use RFC 1738 URL encoding/decoding
*
* @param string $query Query string to parse
* @param bool|string $urlEncoding Controls how the input string is decoded
* and encoded.
* @return self
*/
public static function fromString($query, $urlEncoding = true)
{
static $qp;
if (!$qp) {
$qp = new QueryParser();
}
$q = new static();
if ($urlEncoding !== true) {
$q->setEncodingType($urlEncoding);
}
$qp->parseInto($q, $query, $urlEncoding);
return $q;
}
/**
* Convert the query string parameters to a query string string
*
* @return string
*/
public function __toString()
{
if (!$this->data) {
return '';
}
// The default aggregator is statically cached
static $defaultAggregator;
if (!$this->aggregator) {
if (!$defaultAggregator) {
$defaultAggregator = self::phpAggregator();
}
$this->aggregator = $defaultAggregator;
}
$result = '';
$aggregator = $this->aggregator;
$encoder = $this->encoding;
foreach ($aggregator($this->data) as $key => $values) {
foreach ($values as $value) {
if ($result) {
$result .= '&';
}
$result .= $encoder($key);
if ($value !== null) {
$result .= '=' . $encoder($value);
}
}
}
return $result;
}
/**
* Controls how multi-valued query string parameters are aggregated into a
* string.
*
* $query->setAggregator($query::duplicateAggregator());
*
* @param callable $aggregator Callable used to convert a deeply nested
* array of query string variables into a flattened array of key value
* pairs. The callable accepts an array of query data and returns a
* flattened array of key value pairs where each value is an array of
* strings.
*/
public function setAggregator(callable $aggregator)
{
$this->aggregator = $aggregator;
}
/**
* Specify how values are URL encoded
*
* @param string|bool $type One of 'RFC1738', 'RFC3986', or false to disable encoding
*
* @throws \InvalidArgumentException
*/
public function setEncodingType($type)
{
switch ($type) {
case self::RFC3986:
$this->encoding = 'rawurlencode';
break;
case self::RFC1738:
$this->encoding = 'urlencode';
break;
case false:
$this->encoding = function ($v) { return $v; };
break;
default:
throw new \InvalidArgumentException('Invalid URL encoding type');
}
}
/**
* Query string aggregator that does not aggregate nested query string
* values and allows duplicates in the resulting array.
*
* Example: http://test.com?q=1&q=2
*
* @return callable
*/
public static function duplicateAggregator()
{
return function (array $data) {
return self::walkQuery($data, '', function ($key, $prefix) {
return is_int($key) ? $prefix : "{$prefix}[{$key}]";
});
};
}
/**
* Aggregates nested query string variables using the same technique as
* ``http_build_query()``.
*
* @param bool $numericIndices Pass false to not include numeric indices
* when multi-values query string parameters are present.
*
* @return callable
*/
public static function phpAggregator($numericIndices = true)
{
return function (array $data) use ($numericIndices) {
return self::walkQuery(
$data,
'',
function ($key, $prefix) use ($numericIndices) {
return !$numericIndices && is_int($key)
? "{$prefix}[]"
: "{$prefix}[{$key}]";
}
);
};
}
/**
* Easily create query aggregation functions by providing a key prefix
* function to this query string array walker.
*
* @param array $query Query string to walk
* @param string $keyPrefix Key prefix (start with '')
* @param callable $prefixer Function used to create a key prefix
*
* @return array
*/
public static function walkQuery(array $query, $keyPrefix, callable $prefixer)
{
$result = [];
foreach ($query as $key => $value) {
if ($keyPrefix) {
$key = $prefixer($key, $keyPrefix);
}
if (is_array($value)) {
$result += self::walkQuery($value, $key, $prefixer);
} elseif (isset($result[$key])) {
$result[$key][] = $value;
} else {
$result[$key] = array($value);
}
}
return $result;
}
}

View File

@@ -1,163 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* Parses query strings into a Query object.
*
* While parsing, the parser will attempt to determine the most appropriate
* query string aggregator to use when serializing the parsed query string
* object back into a string. The hope is that parsing then serializing a
* query string should be a lossless operation.
*
* @internal Use Query::fromString()
*/
class QueryParser
{
private $duplicates;
private $numericIndices;
/**
* Parse a query string into a Query object.
*
* @param Query $query Query object to populate
* @param string $str Query string to parse
* @param bool|string $urlEncoding How the query string is encoded
*/
public function parseInto(Query $query, $str, $urlEncoding = true)
{
if ($str === '') {
return;
}
$result = [];
$this->duplicates = false;
$this->numericIndices = true;
$decoder = self::getDecoder($urlEncoding);
foreach (explode('&', $str) as $kvp) {
$parts = explode('=', $kvp, 2);
$key = $decoder($parts[0]);
$value = isset($parts[1]) ? $decoder($parts[1]) : null;
// Special handling needs to be taken for PHP nested array syntax
if (strpos($key, '[') !== false) {
$this->parsePhpValue($key, $value, $result);
continue;
}
if (!isset($result[$key])) {
$result[$key] = $value;
} else {
$this->duplicates = true;
if (!is_array($result[$key])) {
$result[$key] = [$result[$key]];
}
$result[$key][] = $value;
}
}
$query->replace($result);
if (!$this->numericIndices) {
$query->setAggregator(Query::phpAggregator(false));
} elseif ($this->duplicates) {
$query->setAggregator(Query::duplicateAggregator());
}
}
/**
* Returns a callable that is used to URL decode query keys and values.
*
* @param string|bool $type One of true, false, RFC3986, and RFC1738
*
* @return callable|string
*/
private static function getDecoder($type)
{
if ($type === true) {
return function ($value) {
return rawurldecode(str_replace('+', ' ', $value));
};
} elseif ($type == Query::RFC3986) {
return 'rawurldecode';
} elseif ($type == Query::RFC1738) {
return 'urldecode';
} else {
return function ($str) { return $str; };
}
}
/**
* Parses a PHP style key value pair.
*
* @param string $key Key to parse (e.g., "foo[a][b]")
* @param string|null $value Value to set
* @param array $result Result to modify by reference
*/
private function parsePhpValue($key, $value, array &$result)
{
$node =& $result;
$keyBuffer = '';
for ($i = 0, $t = strlen($key); $i < $t; $i++) {
switch ($key[$i]) {
case '[':
if ($keyBuffer) {
$this->prepareNode($node, $keyBuffer);
$node =& $node[$keyBuffer];
$keyBuffer = '';
}
break;
case ']':
$k = $this->cleanKey($node, $keyBuffer);
$this->prepareNode($node, $k);
$node =& $node[$k];
$keyBuffer = '';
break;
default:
$keyBuffer .= $key[$i];
break;
}
}
if (isset($node)) {
$this->duplicates = true;
$node[] = $value;
} else {
$node = $value;
}
}
/**
* Prepares a value in the array at the given key.
*
* If the key already exists, the key value is converted into an array.
*
* @param array $node Result node to modify
* @param string $key Key to add or modify in the node
*/
private function prepareNode(&$node, $key)
{
if (!isset($node[$key])) {
$node[$key] = null;
} elseif (!is_array($node[$key])) {
$node[$key] = [$node[$key]];
}
}
/**
* Returns the appropriate key based on the node and key.
*/
private function cleanKey($node, $key)
{
if ($key === '') {
$key = $node ? (string) count($node) : 0;
// Found a [] key, so track this to ensure that we disable numeric
// indexing of keys in the resolved query aggregator.
$this->numericIndices = false;
}
return $key;
}
}

View File

@@ -1,153 +0,0 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\ErrorEvent;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\EndEvent;
use GuzzleHttp\Exception\StateException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\FutureResponse;
use GuzzleHttp\Message\MessageFactoryInterface;
use GuzzleHttp\Ring\Future\FutureInterface;
/**
* Responsible for transitioning requests through lifecycle events.
*/
class RequestFsm
{
private $handler;
private $mf;
private $maxTransitions;
public function __construct(
callable $handler,
MessageFactoryInterface $messageFactory,
$maxTransitions = 200
) {
$this->mf = $messageFactory;
$this->maxTransitions = $maxTransitions;
$this->handler = $handler;
}
/**
* Runs the state machine until a terminal state is entered or the
* optionally supplied $finalState is entered.
*
* @param Transaction $trans Transaction being transitioned.
*
* @throws \Exception if a terminal state throws an exception.
*/
public function __invoke(Transaction $trans)
{
$trans->_transitionCount = 0;
if (!$trans->state) {
$trans->state = 'before';
}
transition:
if (++$trans->_transitionCount > $this->maxTransitions) {
throw new StateException("Too many state transitions were "
. "encountered ({$trans->_transitionCount}). This likely "
. "means that a combination of event listeners are in an "
. "infinite loop.");
}
switch ($trans->state) {
case 'before': goto before;
case 'complete': goto complete;
case 'error': goto error;
case 'retry': goto retry;
case 'send': goto send;
case 'end': goto end;
default: throw new StateException("Invalid state: {$trans->state}");
}
before: {
try {
$trans->request->getEmitter()->emit('before', new BeforeEvent($trans));
$trans->state = 'send';
if ((bool) $trans->response) {
$trans->state = 'complete';
}
} catch (\Exception $e) {
$trans->state = 'error';
$trans->exception = $e;
}
goto transition;
}
complete: {
try {
if ($trans->response instanceof FutureInterface) {
// Futures will have their own end events emitted when
// dereferenced.
return;
}
$trans->state = 'end';
$trans->response->setEffectiveUrl($trans->request->getUrl());
$trans->request->getEmitter()->emit('complete', new CompleteEvent($trans));
} catch (\Exception $e) {
$trans->state = 'error';
$trans->exception = $e;
}
goto transition;
}
error: {
try {
// Convert non-request exception to a wrapped exception
$trans->exception = RequestException::wrapException(
$trans->request, $trans->exception
);
$trans->state = 'end';
$trans->request->getEmitter()->emit('error', new ErrorEvent($trans));
// An intercepted request (not retried) transitions to complete
if (!$trans->exception && $trans->state !== 'retry') {
$trans->state = 'complete';
}
} catch (\Exception $e) {
$trans->state = 'end';
$trans->exception = $e;
}
goto transition;
}
retry: {
$trans->retries++;
$trans->response = null;
$trans->exception = null;
$trans->state = 'before';
goto transition;
}
send: {
$fn = $this->handler;
$trans->response = FutureResponse::proxy(
$fn(RingBridge::prepareRingRequest($trans)),
function ($value) use ($trans) {
RingBridge::completeRingResponse($trans, $value, $this->mf, $this);
$this($trans);
return $trans->response;
}
);
return;
}
end: {
$trans->request->getEmitter()->emit('end', new EndEvent($trans));
// Throw exceptions in the terminal event if the exception
// was not handled by an "end" event listener.
if ($trans->exception) {
if (!($trans->exception instanceof RequestException)) {
$trans->exception = RequestException::wrapException(
$trans->request, $trans->exception
);
}
throw $trans->exception;
}
}
}
}

View File

@@ -1,165 +0,0 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Message\MessageFactoryInterface;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Event\ProgressEvent;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Exception\RequestException;
/**
* Provides the bridge between Guzzle requests and responses and Guzzle Ring.
*/
class RingBridge
{
/**
* Creates a Ring request from a request object.
*
* This function does not hook up the "then" and "progress" events that
* would be required for actually sending a Guzzle request through a
* RingPHP handler.
*
* @param RequestInterface $request Request to convert.
*
* @return array Converted Guzzle Ring request.
*/
public static function createRingRequest(RequestInterface $request)
{
$options = $request->getConfig()->toArray();
$url = $request->getUrl();
// No need to calculate the query string twice (in URL and query).
$qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null;
return [
'scheme' => $request->getScheme(),
'http_method' => $request->getMethod(),
'url' => $url,
'uri' => $request->getPath(),
'headers' => $request->getHeaders(),
'body' => $request->getBody(),
'version' => $request->getProtocolVersion(),
'client' => $options,
'query_string' => $qs,
'future' => isset($options['future']) ? $options['future'] : false
];
}
/**
* Creates a Ring request from a request object AND prepares the callbacks.
*
* @param Transaction $trans Transaction to update.
*
* @return array Converted Guzzle Ring request.
*/
public static function prepareRingRequest(Transaction $trans)
{
// Clear out the transaction state when initiating.
$trans->exception = null;
$request = self::createRingRequest($trans->request);
// Emit progress events if any progress listeners are registered.
if ($trans->request->getEmitter()->hasListeners('progress')) {
$emitter = $trans->request->getEmitter();
$request['client']['progress'] = function ($a, $b, $c, $d) use ($trans, $emitter) {
$emitter->emit('progress', new ProgressEvent($trans, $a, $b, $c, $d));
};
}
return $request;
}
/**
* Handles the process of processing a response received from a ring
* handler. The created response is added to the transaction, and the
* transaction stat is set appropriately.
*
* @param Transaction $trans Owns request and response.
* @param array $response Ring response array
* @param MessageFactoryInterface $messageFactory Creates response objects.
*/
public static function completeRingResponse(
Transaction $trans,
array $response,
MessageFactoryInterface $messageFactory
) {
$trans->state = 'complete';
$trans->transferInfo = isset($response['transfer_stats'])
? $response['transfer_stats'] : [];
if (!empty($response['status'])) {
$options = [];
if (isset($response['version'])) {
$options['protocol_version'] = $response['version'];
}
if (isset($response['reason'])) {
$options['reason_phrase'] = $response['reason'];
}
$trans->response = $messageFactory->createResponse(
$response['status'],
isset($response['headers']) ? $response['headers'] : [],
isset($response['body']) ? $response['body'] : null,
$options
);
if (isset($response['effective_url'])) {
$trans->response->setEffectiveUrl($response['effective_url']);
}
} elseif (empty($response['error'])) {
// When nothing was returned, then we need to add an error.
$response['error'] = self::getNoRingResponseException($trans->request);
}
if (isset($response['error'])) {
$trans->state = 'error';
$trans->exception = $response['error'];
}
}
/**
* Creates a Guzzle request object using a ring request array.
*
* @param array $request Ring request
*
* @return Request
* @throws \InvalidArgumentException for incomplete requests.
*/
public static function fromRingRequest(array $request)
{
$options = [];
if (isset($request['version'])) {
$options['protocol_version'] = $request['version'];
}
if (!isset($request['http_method'])) {
throw new \InvalidArgumentException('No http_method');
}
return new Request(
$request['http_method'],
Core::url($request),
isset($request['headers']) ? $request['headers'] : [],
isset($request['body']) ? Stream::factory($request['body']) : null,
$options
);
}
/**
* Get an exception that can be used when a RingPHP handler does not
* populate a response.
*
* @param RequestInterface $request
*
* @return RequestException
*/
public static function getNoRingResponseException(RequestInterface $request)
{
$message = <<<EOT
Sending the request did not return a response, exception, or populate the
transaction with a response. This is most likely due to an incorrectly
implemented RingPHP handler. If you are simply trying to mock responses,
then it is recommended to use the GuzzleHttp\Ring\Client\MockHandler.
EOT;
return new RequestException($message, $request);
}
}

View File

@@ -1,58 +0,0 @@
<?php
namespace GuzzleHttp\Subscriber;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
/**
* Adds, extracts, and persists cookies between HTTP requests
*/
class Cookie implements SubscriberInterface
{
/** @var CookieJarInterface */
private $cookieJar;
/**
* @param CookieJarInterface $cookieJar Cookie jar used to hold cookies
*/
public function __construct(CookieJarInterface $cookieJar = null)
{
$this->cookieJar = $cookieJar ?: new CookieJar();
}
public function getEvents()
{
// Fire the cookie plugin complete event before redirecting
return [
'before' => ['onBefore'],
'complete' => ['onComplete', RequestEvents::REDIRECT_RESPONSE + 10]
];
}
/**
* Get the cookie cookieJar
*
* @return CookieJarInterface
*/
public function getCookieJar()
{
return $this->cookieJar;
}
public function onBefore(BeforeEvent $event)
{
$this->cookieJar->addCookieHeader($event->getRequest());
}
public function onComplete(CompleteEvent $event)
{
$this->cookieJar->extractCookies(
$event->getRequest(),
$event->getResponse()
);
}
}

View File

@@ -1,172 +0,0 @@
<?php
namespace GuzzleHttp\Subscriber;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\ErrorEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
/**
* Maintains a list of requests and responses sent using a request or client
*/
class History implements SubscriberInterface, \IteratorAggregate, \Countable
{
/** @var int The maximum number of requests to maintain in the history */
private $limit;
/** @var array Requests and responses that have passed through the plugin */
private $transactions = [];
public function __construct($limit = 10)
{
$this->limit = $limit;
}
public function getEvents()
{
return [
'complete' => ['onComplete', RequestEvents::EARLY],
'error' => ['onError', RequestEvents::EARLY],
];
}
/**
* Convert to a string that contains all request and response headers
*
* @return string
*/
public function __toString()
{
$lines = array();
foreach ($this->transactions as $entry) {
$response = isset($entry['response']) ? $entry['response'] : '';
$lines[] = '> ' . trim($entry['sent_request'])
. "\n\n< " . trim($response) . "\n";
}
return implode("\n", $lines);
}
public function onComplete(CompleteEvent $event)
{
$this->add($event->getRequest(), $event->getResponse());
}
public function onError(ErrorEvent $event)
{
// Only track when no response is present, meaning this didn't ever
// emit a complete event
if (!$event->getResponse()) {
$this->add($event->getRequest());
}
}
/**
* Returns an Iterator that yields associative array values where each
* associative array contains the following key value pairs:
*
* - request: Representing the actual request that was received.
* - sent_request: A clone of the request that will not be mutated.
* - response: The response that was received (if available).
*
* @return \Iterator
*/
public function getIterator()
{
return new \ArrayIterator($this->transactions);
}
/**
* Get all of the requests sent through the plugin.
*
* Requests can be modified after they are logged by the history
* subscriber. By default this method will return the actual request
* instances that were received. Pass true to this method if you wish to
* get copies of the requests that represent the request state when it was
* initially logged by the history subscriber.
*
* @param bool $asSent Set to true to get clones of the requests that have
* not been mutated since the request was received by
* the history subscriber.
*
* @return RequestInterface[]
*/
public function getRequests($asSent = false)
{
return array_map(function ($t) use ($asSent) {
return $asSent ? $t['sent_request'] : $t['request'];
}, $this->transactions);
}
/**
* Get the number of requests in the history
*
* @return int
*/
public function count()
{
return count($this->transactions);
}
/**
* Get the last request sent.
*
* Requests can be modified after they are logged by the history
* subscriber. By default this method will return the actual request
* instance that was received. Pass true to this method if you wish to get
* a copy of the request that represents the request state when it was
* initially logged by the history subscriber.
*
* @param bool $asSent Set to true to get a clone of the last request that
* has not been mutated since the request was received
* by the history subscriber.
*
* @return RequestInterface
*/
public function getLastRequest($asSent = false)
{
return $asSent
? end($this->transactions)['sent_request']
: end($this->transactions)['request'];
}
/**
* Get the last response in the history
*
* @return ResponseInterface|null
*/
public function getLastResponse()
{
return end($this->transactions)['response'];
}
/**
* Clears the history
*/
public function clear()
{
$this->transactions = array();
}
/**
* Add a request to the history
*
* @param RequestInterface $request Request to add
* @param ResponseInterface $response Response of the request
*/
private function add(
RequestInterface $request,
ResponseInterface $response = null
) {
$this->transactions[] = [
'request' => $request,
'sent_request' => clone $request,
'response' => $response
];
if (count($this->transactions) > $this->limit) {
array_shift($this->transactions);
}
}
}

View File

@@ -1,36 +0,0 @@
<?php
namespace GuzzleHttp\Subscriber;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Exception\RequestException;
/**
* Throws exceptions when a 4xx or 5xx response is received
*/
class HttpError implements SubscriberInterface
{
public function getEvents()
{
return ['complete' => ['onComplete', RequestEvents::VERIFY_RESPONSE]];
}
/**
* Throw a RequestException on an HTTP protocol error
*
* @param CompleteEvent $event Emitted event
* @throws RequestException
*/
public function onComplete(CompleteEvent $event)
{
$code = (string) $event->getResponse()->getStatusCode();
// Throw an exception for an unsuccessful response
if ($code[0] >= 4) {
throw RequestException::create(
$event->getRequest(),
$event->getResponse()
);
}
}
}

View File

@@ -1,147 +0,0 @@
<?php
namespace GuzzleHttp\Subscriber;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\MessageFactory;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Stream\StreamInterface;
/**
* Queues mock responses or exceptions and delivers mock responses or
* exceptions in a fifo order.
*/
class Mock implements SubscriberInterface, \Countable
{
/** @var array Array of mock responses / exceptions */
private $queue = [];
/** @var bool Whether or not to consume an entity body when mocking */
private $readBodies;
/** @var MessageFactory */
private $factory;
/**
* @param array $items Array of responses or exceptions to queue
* @param bool $readBodies Set to false to not consume the entity body of
* a request when a mock is served.
*/
public function __construct(array $items = [], $readBodies = true)
{
$this->factory = new MessageFactory();
$this->readBodies = $readBodies;
$this->addMultiple($items);
}
public function getEvents()
{
// Fire the event last, after signing
return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST - 10]];
}
/**
* @throws \OutOfBoundsException|\Exception
*/
public function onBefore(BeforeEvent $event)
{
if (!$item = array_shift($this->queue)) {
throw new \OutOfBoundsException('Mock queue is empty');
} elseif ($item instanceof RequestException) {
throw $item;
}
// Emulate reading a response body
$request = $event->getRequest();
if ($this->readBodies && $request->getBody()) {
while (!$request->getBody()->eof()) {
$request->getBody()->read(8096);
}
}
$saveTo = $event->getRequest()->getConfig()->get('save_to');
if (null !== $saveTo) {
$body = $item->getBody();
if (is_resource($saveTo)) {
fwrite($saveTo, $body);
} elseif (is_string($saveTo)) {
file_put_contents($saveTo, $body);
} elseif ($saveTo instanceof StreamInterface) {
$saveTo->write($body);
}
}
$event->intercept($item);
}
public function count()
{
return count($this->queue);
}
/**
* Add a response to the end of the queue
*
* @param string|ResponseInterface $response Response or path to response file
*
* @return self
* @throws \InvalidArgumentException if a string or Response is not passed
*/
public function addResponse($response)
{
if (is_string($response)) {
$response = file_exists($response)
? $this->factory->fromMessage(file_get_contents($response))
: $this->factory->fromMessage($response);
} elseif (!($response instanceof ResponseInterface)) {
throw new \InvalidArgumentException('Response must a message '
. 'string, response object, or path to a file');
}
$this->queue[] = $response;
return $this;
}
/**
* Add an exception to the end of the queue
*
* @param RequestException $e Exception to throw when the request is executed
*
* @return self
*/
public function addException(RequestException $e)
{
$this->queue[] = $e;
return $this;
}
/**
* Add multiple items to the queue
*
* @param array $items Items to add
*/
public function addMultiple(array $items)
{
foreach ($items as $item) {
if ($item instanceof RequestException) {
$this->addException($item);
} else {
$this->addResponse($item);
}
}
}
/**
* Clear the queue
*/
public function clearQueue()
{
$this->queue = [];
}
}

View File

@@ -1,130 +0,0 @@
<?php
namespace GuzzleHttp\Subscriber;
use GuzzleHttp\Event\BeforeEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Message\AppliesHeadersInterface;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Mimetypes;
use GuzzleHttp\Stream\StreamInterface;
/**
* Prepares requests with a body before sending
*
* **Request Options**
*
* - expect: Set to true to enable the "Expect: 100-Continue" header for a
* request that send a body. Set to false to disable "Expect: 100-Continue".
* Set to a number so that the size of the payload must be greater than the
* number in order to send the Expect header. Setting to a number will send
* the Expect header for all requests in which the size of the payload cannot
* be determined or where the body is not rewindable.
*/
class Prepare implements SubscriberInterface
{
public function getEvents()
{
return ['before' => ['onBefore', RequestEvents::PREPARE_REQUEST]];
}
public function onBefore(BeforeEvent $event)
{
$request = $event->getRequest();
// Set the appropriate Content-Type for a request if one is not set and
// there are form fields
if (!($body = $request->getBody())) {
return;
}
$this->addContentLength($request, $body);
if ($body instanceof AppliesHeadersInterface) {
// Synchronize the body with the request headers
$body->applyRequestHeaders($request);
} elseif (!$request->hasHeader('Content-Type')) {
$this->addContentType($request, $body);
}
$this->addExpectHeader($request, $body);
}
private function addContentType(
RequestInterface $request,
StreamInterface $body
) {
if (!($uri = $body->getMetadata('uri'))) {
return;
}
// Guess the content-type based on the stream's "uri" metadata value.
// The file extension is used to determine the appropriate mime-type.
if ($contentType = Mimetypes::getInstance()->fromFilename($uri)) {
$request->setHeader('Content-Type', $contentType);
}
}
private function addContentLength(
RequestInterface $request,
StreamInterface $body
) {
// Set the Content-Length header if it can be determined, and never
// send a Transfer-Encoding: chunked and Content-Length header in
// the same request.
if ($request->hasHeader('Content-Length')) {
// Remove transfer-encoding if content-length is set.
$request->removeHeader('Transfer-Encoding');
return;
}
if ($request->hasHeader('Transfer-Encoding')) {
return;
}
if (null !== ($size = $body->getSize())) {
$request->setHeader('Content-Length', $size);
$request->removeHeader('Transfer-Encoding');
} elseif ('1.1' == $request->getProtocolVersion()) {
// Use chunked Transfer-Encoding if there is no determinable
// content-length header and we're using HTTP/1.1.
$request->setHeader('Transfer-Encoding', 'chunked');
$request->removeHeader('Content-Length');
}
}
private function addExpectHeader(
RequestInterface $request,
StreamInterface $body
) {
// Determine if the Expect header should be used
if ($request->hasHeader('Expect')) {
return;
}
$expect = $request->getConfig()['expect'];
// Return if disabled or if you're not using HTTP/1.1
if ($expect === false || $request->getProtocolVersion() !== '1.1') {
return;
}
// The expect header is unconditionally enabled
if ($expect === true) {
$request->setHeader('Expect', '100-Continue');
return;
}
// By default, send the expect header when the payload is > 1mb
if ($expect === null) {
$expect = 1048576;
}
// Always add if the body cannot be rewound, the size cannot be
// determined, or the size is greater than the cutoff threshold
$size = $body->getSize();
if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
$request->setHeader('Expect', '100-Continue');
}
}
}

View File

@@ -1,176 +0,0 @@
<?php
namespace GuzzleHttp\Subscriber;
use GuzzleHttp\Event\CompleteEvent;
use GuzzleHttp\Event\RequestEvents;
use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\CouldNotRewindStreamException;
use GuzzleHttp\Exception\TooManyRedirectsException;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Url;
/**
* Subscriber used to implement HTTP redirects.
*
* **Request options**
*
* - redirect: Associative array containing the 'max', 'strict', and 'referer'
* keys.
*
* - max: Maximum number of redirects allowed per-request
* - strict: You can use strict redirects by setting this value to ``true``.
* Strict redirects adhere to strict RFC compliant redirection (e.g.,
* redirect POST with POST) vs doing what most clients do (e.g., redirect
* POST request with a GET request).
* - referer: Set to true to automatically add the "Referer" header when a
* redirect request is sent.
* - protocols: Array of allowed protocols. Defaults to 'http' and 'https'.
* When a redirect attempts to utilize a protocol that is not white listed,
* an exception is thrown.
*/
class Redirect implements SubscriberInterface
{
public function getEvents()
{
return ['complete' => ['onComplete', RequestEvents::REDIRECT_RESPONSE]];
}
/**
* Rewind the entity body of the request if needed
*
* @param RequestInterface $redirectRequest
* @throws CouldNotRewindStreamException
*/
public static function rewindEntityBody(RequestInterface $redirectRequest)
{
// Rewind the entity body of the request if needed
if ($body = $redirectRequest->getBody()) {
// Only rewind the body if some of it has been read already, and
// throw an exception if the rewind fails
if ($body->tell() && !$body->seek(0)) {
throw new CouldNotRewindStreamException(
'Unable to rewind the non-seekable request body after redirecting',
$redirectRequest
);
}
}
}
/**
* Called when a request receives a redirect response
*
* @param CompleteEvent $event Event emitted
* @throws TooManyRedirectsException
*/
public function onComplete(CompleteEvent $event)
{
$response = $event->getResponse();
if (substr($response->getStatusCode(), 0, 1) != '3'
|| !$response->hasHeader('Location')
) {
return;
}
$request = $event->getRequest();
$config = $request->getConfig();
// Increment the redirect and initialize the redirect state.
if ($redirectCount = $config['redirect_count']) {
$config['redirect_count'] = ++$redirectCount;
} else {
$config['redirect_scheme'] = $request->getScheme();
$config['redirect_count'] = $redirectCount = 1;
}
$max = $config->getPath('redirect/max') ?: 5;
if ($redirectCount > $max) {
throw new TooManyRedirectsException(
"Will not follow more than {$redirectCount} redirects",
$request
);
}
$this->modifyRedirectRequest($request, $response);
$event->retry();
}
private function modifyRedirectRequest(
RequestInterface $request,
ResponseInterface $response
) {
$config = $request->getConfig();
$protocols = $config->getPath('redirect/protocols') ?: ['http', 'https'];
// Use a GET request if this is an entity enclosing request and we are
// not forcing RFC compliance, but rather emulating what all browsers
// would do.
$statusCode = $response->getStatusCode();
if ($statusCode == 303 ||
($statusCode <= 302 && $request->getBody() && !$config->getPath('redirect/strict'))
) {
$request->setMethod('GET');
$request->setBody(null);
}
$previousUrl = $request->getUrl();
$this->setRedirectUrl($request, $response, $protocols);
$this->rewindEntityBody($request);
// Add the Referer header if it is told to do so and only
// add the header if we are not redirecting from https to http.
if ($config->getPath('redirect/referer')
&& ($request->getScheme() == 'https' || $request->getScheme() == $config['redirect_scheme'])
) {
$url = Url::fromString($previousUrl);
$url->setUsername(null);
$url->setPassword(null);
$request->setHeader('Referer', (string) $url);
} else {
$request->removeHeader('Referer');
}
}
/**
* Set the appropriate URL on the request based on the location header
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param array $protocols
*/
private function setRedirectUrl(
RequestInterface $request,
ResponseInterface $response,
array $protocols
) {
$location = $response->getHeader('Location');
$location = Url::fromString($location);
// Combine location with the original URL if it is not absolute.
if (!$location->isAbsolute()) {
$originalUrl = Url::fromString($request->getUrl());
// Remove query string parameters and just take what is present on
// the redirect Location header
$originalUrl->getQuery()->clear();
$location = $originalUrl->combine($location);
}
// Ensure that the redirect URL is allowed based on the protocols.
if (!in_array($location->getScheme(), $protocols)) {
throw new BadResponseException(
sprintf(
'Redirect URL, %s, does not use one of the allowed redirect protocols: %s',
$location,
implode(', ', $protocols)
),
$request,
$response
);
}
$request->setUrl($location);
}
}

View File

@@ -1,15 +0,0 @@
<?php
namespace GuzzleHttp;
/**
* An object that can be represented as an array
*/
interface ToArrayInterface
{
/**
* Get the array representation of an object
*
* @return array
*/
public function toArray();
}

View File

@@ -1,103 +0,0 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
/**
* Represents the relationship between a client, request, and response.
*
* You can access the request, response, and client using their corresponding
* public properties.
*/
class Transaction
{
/**
* HTTP client used to transfer the request.
*
* @var ClientInterface
*/
public $client;
/**
* The request that is being sent.
*
* @var RequestInterface
*/
public $request;
/**
* The response associated with the transaction. A response will not be
* present when a networking error occurs or an error occurs before sending
* the request.
*
* @var ResponseInterface|null
*/
public $response;
/**
* Exception associated with the transaction. If this exception is present
* when processing synchronous or future commands, then it is thrown. When
* intercepting a failed transaction, you MUST set this value to null in
* order to prevent the exception from being thrown.
*
* @var \Exception
*/
public $exception;
/**
* Associative array of handler specific transfer statistics and custom
* key value pair information. When providing similar information, handlers
* should follow the same key value pair naming conventions as PHP's
* curl_getinfo() (http://php.net/manual/en/function.curl-getinfo.php).
*
* @var array
*/
public $transferInfo = [];
/**
* The number of transaction retries.
*
* @var int
*/
public $retries = 0;
/**
* The transaction's current state.
*
* @var string
*/
public $state;
/**
* Whether or not this is a future transaction. This value should not be
* changed after the future is constructed.
*
* @var bool
*/
public $future;
/**
* The number of state transitions that this transaction has been through.
*
* @var int
* @internal This is for internal use only. If you modify this, then you
* are asking for trouble.
*/
public $_transitionCount = 0;
/**
* @param ClientInterface $client Client that is used to send the requests
* @param RequestInterface $request Request to send
* @param bool $future Whether or not this is a future request.
*/
public function __construct(
ClientInterface $client,
RequestInterface $request,
$future = false
) {
$this->client = $client;
$this->request = $request;
$this->_future = $future;
}
}

View File

@@ -1,595 +0,0 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Ring\Core;
/**
* Parses and generates URLs based on URL parts
*/
class Url
{
private $scheme;
private $host;
private $port;
private $username;
private $password;
private $path = '';
private $fragment;
private static $defaultPorts = ['http' => 80, 'https' => 443, 'ftp' => 21];
private static $pathPattern = '/[^a-zA-Z0-9\-\._~!\$&\'\(\)\*\+,;=%:@\/]+|%(?![A-Fa-f0-9]{2})/';
private static $queryPattern = '/[^a-zA-Z0-9\-\._~!\$\'\(\)\*\+,;%:@\/\?=&]+|%(?![A-Fa-f0-9]{2})/';
/** @var Query|string Query part of the URL */
private $query;
/**
* Factory method to create a new URL from a URL string
*
* @param string $url Full URL used to create a Url object
*
* @return Url
* @throws \InvalidArgumentException
*/
public static function fromString($url)
{
static $defaults = ['scheme' => null, 'host' => null,
'path' => null, 'port' => null, 'query' => null,
'user' => null, 'pass' => null, 'fragment' => null];
if (false === ($parts = parse_url($url))) {
throw new \InvalidArgumentException('Unable to parse malformed '
. 'url: ' . $url);
}
$parts += $defaults;
// Convert the query string into a Query object
if ($parts['query'] || 0 !== strlen($parts['query'])) {
$parts['query'] = Query::fromString($parts['query']);
}
return new static($parts['scheme'], $parts['host'], $parts['user'],
$parts['pass'], $parts['port'], $parts['path'], $parts['query'],
$parts['fragment']);
}
/**
* Build a URL from parse_url parts. The generated URL will be a relative
* URL if a scheme or host are not provided.
*
* @param array $parts Array of parse_url parts
*
* @return string
*/
public static function buildUrl(array $parts)
{
$url = $scheme = '';
if (!empty($parts['scheme'])) {
$scheme = $parts['scheme'];
$url .= $scheme . ':';
}
if (!empty($parts['host'])) {
$url .= '//';
if (isset($parts['user'])) {
$url .= $parts['user'];
if (isset($parts['pass'])) {
$url .= ':' . $parts['pass'];
}
$url .= '@';
}
$url .= $parts['host'];
// Only include the port if it is not the default port of the scheme
if (isset($parts['port']) &&
(!isset(self::$defaultPorts[$scheme]) ||
$parts['port'] != self::$defaultPorts[$scheme])
) {
$url .= ':' . $parts['port'];
}
}
// Add the path component if present
if (isset($parts['path']) && strlen($parts['path'])) {
// Always ensure that the path begins with '/' if set and something
// is before the path
if (!empty($parts['host']) && $parts['path'][0] != '/') {
$url .= '/';
}
$url .= $parts['path'];
}
// Add the query string if present
if (isset($parts['query'])) {
$queryStr = (string) $parts['query'];
if ($queryStr || $queryStr === '0') {
$url .= '?' . $queryStr;
}
}
// Ensure that # is only added to the url if fragment contains anything.
if (isset($parts['fragment'])) {
$url .= '#' . $parts['fragment'];
}
return $url;
}
/**
* Create a new URL from URL parts
*
* @param string $scheme Scheme of the URL
* @param string $host Host of the URL
* @param string $username Username of the URL
* @param string $password Password of the URL
* @param int $port Port of the URL
* @param string $path Path of the URL
* @param Query|array|string $query Query string of the URL
* @param string $fragment Fragment of the URL
*/
public function __construct(
$scheme,
$host,
$username = null,
$password = null,
$port = null,
$path = null,
$query = null,
$fragment = null
) {
$this->scheme = strtolower($scheme);
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->fragment = $fragment;
if ($query) {
$this->setQuery($query);
}
$this->setPath($path);
}
/**
* Clone the URL
*/
public function __clone()
{
if ($this->query instanceof Query) {
$this->query = clone $this->query;
}
}
/**
* Returns the URL as a URL string
*
* @return string
*/
public function __toString()
{
return static::buildUrl($this->getParts());
}
/**
* Get the parts of the URL as an array
*
* @return array
*/
public function getParts()
{
return array(
'scheme' => $this->scheme,
'user' => $this->username,
'pass' => $this->password,
'host' => $this->host,
'port' => $this->port,
'path' => $this->path,
'query' => $this->query,
'fragment' => $this->fragment,
);
}
/**
* Set the host of the request.
*
* @param string $host Host to set (e.g. www.yahoo.com, yahoo.com)
*
* @return Url
*/
public function setHost($host)
{
if (strpos($host, ':') === false) {
$this->host = $host;
} else {
list($host, $port) = explode(':', $host);
$this->host = $host;
$this->setPort($port);
}
}
/**
* Get the host part of the URL
*
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set the scheme part of the URL (http, https, ftp, etc.)
*
* @param string $scheme Scheme to set
*/
public function setScheme($scheme)
{
// Remove the default port if one is specified
if ($this->port
&& isset(self::$defaultPorts[$this->scheme])
&& self::$defaultPorts[$this->scheme] == $this->port
) {
$this->port = null;
}
$this->scheme = strtolower($scheme);
}
/**
* Get the scheme part of the URL
*
* @return string
*/
public function getScheme()
{
return $this->scheme;
}
/**
* Set the port part of the URL
*
* @param int $port Port to set
*/
public function setPort($port)
{
$this->port = $port;
}
/**
* Get the port part of the URl.
*
* If no port was set, this method will return the default port for the
* scheme of the URI.
*
* @return int|null
*/
public function getPort()
{
if ($this->port) {
return $this->port;
} elseif (isset(self::$defaultPorts[$this->scheme])) {
return self::$defaultPorts[$this->scheme];
}
return null;
}
/**
* Set the path part of the URL.
*
* The provided URL is URL encoded as necessary.
*
* @param string $path Path string to set
*/
public function setPath($path)
{
$this->path = self::encodePath($path);
}
/**
* Removes dot segments from a URL
* @link http://tools.ietf.org/html/rfc3986#section-5.2.4
*/
public function removeDotSegments()
{
static $noopPaths = ['' => true, '/' => true, '*' => true];
static $ignoreSegments = ['.' => true, '..' => true];
if (isset($noopPaths[$this->path])) {
return;
}
$results = [];
$segments = $this->getPathSegments();
foreach ($segments as $segment) {
if ($segment == '..') {
array_pop($results);
} elseif (!isset($ignoreSegments[$segment])) {
$results[] = $segment;
}
}
$newPath = implode('/', $results);
// Add the leading slash if necessary
if (substr($this->path, 0, 1) === '/' &&
substr($newPath, 0, 1) !== '/'
) {
$newPath = '/' . $newPath;
}
// Add the trailing slash if necessary
if ($newPath != '/' && isset($ignoreSegments[end($segments)])) {
$newPath .= '/';
}
$this->path = $newPath;
}
/**
* Add a relative path to the currently set path.
*
* @param string $relativePath Relative path to add
*/
public function addPath($relativePath)
{
if ($relativePath != '/' &&
is_string($relativePath) &&
strlen($relativePath) > 0
) {
// Add a leading slash if needed
if ($relativePath[0] !== '/' &&
substr($this->path, -1, 1) !== '/'
) {
$relativePath = '/' . $relativePath;
}
$this->setPath($this->path . $relativePath);
}
}
/**
* Get the path part of the URL
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Get the path segments of the URL as an array
*
* @return array
*/
public function getPathSegments()
{
return explode('/', $this->path);
}
/**
* Set the password part of the URL
*
* @param string $password Password to set
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get the password part of the URL
*
* @return null|string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set the username part of the URL
*
* @param string $username Username to set
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get the username part of the URl
*
* @return null|string
*/
public function getUsername()
{
return $this->username;
}
/**
* Get the query part of the URL as a Query object
*
* @return Query
*/
public function getQuery()
{
// Convert the query string to a query object if not already done.
if (!$this->query instanceof Query) {
$this->query = $this->query === null
? new Query()
: Query::fromString($this->query);
}
return $this->query;
}
/**
* Set the query part of the URL.
*
* You may provide a query string as a string and pass $rawString as true
* to provide a query string that is not parsed until a call to getQuery()
* is made. Setting a raw query string will still encode invalid characters
* in a query string.
*
* @param Query|string|array $query Query string value to set. Can
* be a string that will be parsed into a Query object, an array
* of key value pairs, or a Query object.
* @param bool $rawString Set to true when providing a raw query string.
*
* @throws \InvalidArgumentException
*/
public function setQuery($query, $rawString = false)
{
if ($query instanceof Query) {
$this->query = $query;
} elseif (is_string($query)) {
if (!$rawString) {
$this->query = Query::fromString($query);
} else {
// Ensure the query does not have illegal characters.
$this->query = preg_replace_callback(
self::$queryPattern,
[__CLASS__, 'encodeMatch'],
$query
);
}
} elseif (is_array($query)) {
$this->query = new Query($query);
} else {
throw new \InvalidArgumentException('Query must be a Query, '
. 'array, or string. Got ' . Core::describeType($query));
}
}
/**
* Get the fragment part of the URL
*
* @return null|string
*/
public function getFragment()
{
return $this->fragment;
}
/**
* Set the fragment part of the URL
*
* @param string $fragment Fragment to set
*/
public function setFragment($fragment)
{
$this->fragment = $fragment;
}
/**
* Check if this is an absolute URL
*
* @return bool
*/
public function isAbsolute()
{
return $this->scheme && $this->host;
}
/**
* Combine the URL with another URL and return a new URL instance.
*
* Follows the rules specific in RFC 3986 section 5.4.
*
* @param string $url Relative URL to combine with
*
* @return Url
* @throws \InvalidArgumentException
* @link http://tools.ietf.org/html/rfc3986#section-5.4
*/
public function combine($url)
{
$url = static::fromString($url);
// Use the more absolute URL as the base URL
if (!$this->isAbsolute() && $url->isAbsolute()) {
$url = $url->combine($this);
}
$parts = $url->getParts();
// Passing a URL with a scheme overrides everything
if ($parts['scheme']) {
return clone $url;
}
// Setting a host overrides the entire rest of the URL
if ($parts['host']) {
return new static(
$this->scheme,
$parts['host'],
$parts['user'],
$parts['pass'],
$parts['port'],
$parts['path'],
$parts['query'] instanceof Query
? clone $parts['query']
: $parts['query'],
$parts['fragment']
);
}
if (!$parts['path'] && $parts['path'] !== '0') {
// The relative URL has no path, so check if it is just a query
$path = $this->path ?: '';
$query = $parts['query'] ?: $this->query;
} else {
$query = $parts['query'];
if ($parts['path'][0] == '/' || !$this->path) {
// Overwrite the existing path if the rel path starts with "/"
$path = $parts['path'];
} else {
// If the relative URL does not have a path or the base URL
// path does not end in a "/" then overwrite the existing path
// up to the last "/"
$path = substr($this->path, 0, strrpos($this->path, '/') + 1) . $parts['path'];
}
}
$result = new self(
$this->scheme,
$this->host,
$this->username,
$this->password,
$this->port,
$path,
$query instanceof Query ? clone $query : $query,
$parts['fragment']
);
if ($path) {
$result->removeDotSegments();
}
return $result;
}
/**
* Encodes the path part of a URL without double-encoding percent-encoded
* key value pairs.
*
* @param string $path Path to encode
*
* @return string
*/
public static function encodePath($path)
{
static $cb = [__CLASS__, 'encodeMatch'];
return preg_replace_callback(self::$pathPattern, $cb, $path);
}
private static function encodeMatch(array $match)
{
return rawurlencode($match[0]);
}
}

View File

@@ -1,215 +0,0 @@
<?php
namespace GuzzleHttp;
use GuzzleHttp\Ring\Client\CurlHandler;
use GuzzleHttp\Ring\Client\CurlMultiHandler;
use GuzzleHttp\Ring\Client\StreamHandler;
use GuzzleHttp\Ring\Client\Middleware;
/**
* Utility methods used throughout Guzzle.
*/
final class Utils
{
/**
* Gets a value from an array using a path syntax to retrieve nested data.
*
* This method does not allow for keys that contain "/". You must traverse
* the array manually or using something more advanced like JMESPath to
* work with keys that contain "/".
*
* // Get the bar key of a set of nested arrays.
* // This is equivalent to $collection['foo']['baz']['bar'] but won't
* // throw warnings for missing keys.
* GuzzleHttp\get_path($data, 'foo/baz/bar');
*
* @param array $data Data to retrieve values from
* @param string $path Path to traverse and retrieve a value from
*
* @return mixed|null
*/
public static function getPath($data, $path)
{
$path = explode('/', $path);
while (null !== ($part = array_shift($path))) {
if (!is_array($data) || !isset($data[$part])) {
return null;
}
$data = $data[$part];
}
return $data;
}
/**
* Set a value in a nested array key. Keys will be created as needed to set
* the value.
*
* This function does not support keys that contain "/" or "[]" characters
* because these are special tokens used when traversing the data structure.
* A value may be prepended to an existing array by using "[]" as the final
* key of a path.
*
* GuzzleHttp\get_path($data, 'foo/baz'); // null
* GuzzleHttp\set_path($data, 'foo/baz/[]', 'a');
* GuzzleHttp\set_path($data, 'foo/baz/[]', 'b');
* GuzzleHttp\get_path($data, 'foo/baz');
* // Returns ['a', 'b']
*
* @param array $data Data to modify by reference
* @param string $path Path to set
* @param mixed $value Value to set at the key
*
* @throws \RuntimeException when trying to setPath using a nested path
* that travels through a scalar value.
*/
public static function setPath(&$data, $path, $value)
{
$queue = explode('/', $path);
// Optimization for simple sets.
if (count($queue) === 1) {
$data[$path] = $value;
return;
}
$current =& $data;
while (null !== ($key = array_shift($queue))) {
if (!is_array($current)) {
throw new \RuntimeException("Trying to setPath {$path}, but "
. "{$key} is set and is not an array");
} elseif (!$queue) {
if ($key == '[]') {
$current[] = $value;
} else {
$current[$key] = $value;
}
} elseif (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = [];
$current =& $current[$key];
}
}
}
/**
* Expands a URI template
*
* @param string $template URI template
* @param array $variables Template variables
*
* @return string
*/
public static function uriTemplate($template, array $variables)
{
if (function_exists('\\uri_template')) {
return \uri_template($template, $variables);
}
static $uriTemplate;
if (!$uriTemplate) {
$uriTemplate = new UriTemplate();
}
return $uriTemplate->expand($template, $variables);
}
/**
* Wrapper for JSON decode that implements error detection with helpful
* error messages.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* into associative arrays.
* @param int $depth User specified recursion depth.
* @param int $options Bitmask of JSON decode options.
*
* @return mixed
* @throws \InvalidArgumentException if the JSON cannot be parsed.
* @link http://www.php.net/manual/en/function.json-decode.php
*/
public static function jsonDecode($json, $assoc = false, $depth = 512, $options = 0)
{
if ($json === '' || $json === null) {
return null;
}
static $jsonErrors = [
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
];
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
$last = json_last_error();
throw new \InvalidArgumentException(
'Unable to parse JSON data: '
. (isset($jsonErrors[$last])
? $jsonErrors[$last]
: 'Unknown error')
);
}
return $data;
}
/**
* Get the default User-Agent string to use with Guzzle
*
* @return string
*/
public static function getDefaultUserAgent()
{
static $defaultAgent = '';
if (!$defaultAgent) {
$defaultAgent = 'Guzzle/' . ClientInterface::VERSION;
if (extension_loaded('curl')) {
$defaultAgent .= ' curl/' . curl_version()['version'];
}
$defaultAgent .= ' PHP/' . PHP_VERSION;
}
return $defaultAgent;
}
/**
* Create a default handler to use based on the environment
*
* @throws \RuntimeException if no viable Handler is available.
*/
public static function getDefaultHandler()
{
$default = $future = null;
if (extension_loaded('curl')) {
$config = [
'select_timeout' => getenv('GUZZLE_CURL_SELECT_TIMEOUT') ?: 1
];
if ($maxHandles = getenv('GUZZLE_CURL_MAX_HANDLES')) {
$config['max_handles'] = $maxHandles;
}
if (function_exists('curl_reset')) {
$default = new CurlHandler();
$future = new CurlMultiHandler($config);
} else {
$default = new CurlMultiHandler($config);
}
}
if (ini_get('allow_url_fopen')) {
$default = !$default
? new StreamHandler()
: Middleware::wrapStreaming($default, new StreamHandler());
} elseif (!$default) {
throw new \RuntimeException('Guzzle requires cURL, the '
. 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $future ? Middleware::wrapFuture($default, $future) : $default;
}
}

View File

@@ -1,12 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[{Makefile,*.mk}]
indent_style = tab

View File

@@ -1,19 +0,0 @@
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -1,43 +0,0 @@
{
"name": "guzzlehttp/ringphp",
"description": "Provides a simple API and specification that abstracts away the details of HTTP into a single PHP function.",
"license": "MIT",
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"require": {
"php": ">=5.4.0",
"guzzlehttp/streams": "~3.0",
"react/promise": "~2.0"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "~4.0"
},
"suggest": {
"ext-curl": "Guzzle will use specific adapters if cURL is present"
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Ring\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"GuzzleHttp\\Tests\\Ring\\": "tests/"
}
},
"scripts": {
"test": "make test",
"test-ci": "make coverage"
},
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
}
}

View File

@@ -1,74 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
/**
* Client specific utility functions.
*/
class ClientUtils
{
/**
* Returns the default cacert bundle for the current system.
*
* First, the openssl.cafile and curl.cainfo php.ini settings are checked.
* If those settings are not configured, then the common locations for
* bundles found on Red Hat, CentOS, Fedora, Ubuntu, Debian, FreeBSD, OS X
* and Windows are checked. If any of these file locations are found on
* disk, they will be utilized.
*
* Note: the result of this function is cached for subsequent calls.
*
* @return string
* @throws \RuntimeException if no bundle can be found.
*/
public static function getDefaultCaBundle()
{
static $cached = null;
static $cafiles = [
// Red Hat, CentOS, Fedora (provided by the ca-certificates package)
'/etc/pki/tls/certs/ca-bundle.crt',
// Ubuntu, Debian (provided by the ca-certificates package)
'/etc/ssl/certs/ca-certificates.crt',
// FreeBSD (provided by the ca_root_nss package)
'/usr/local/share/certs/ca-root-nss.crt',
// OS X provided by homebrew (using the default path)
'/usr/local/etc/openssl/cert.pem',
// Windows?
'C:\\windows\\system32\\curl-ca-bundle.crt',
'C:\\windows\\curl-ca-bundle.crt',
];
if ($cached) {
return $cached;
}
if ($ca = ini_get('openssl.cafile')) {
return $cached = $ca;
}
if ($ca = ini_get('curl.cainfo')) {
return $cached = $ca;
}
foreach ($cafiles as $filename) {
if (file_exists($filename)) {
return $cached = $filename;
}
}
throw new \RuntimeException(self::CA_ERR);
}
const CA_ERR = "
No system CA bundle could be found in any of the the common system locations.
PHP versions earlier than 5.6 are not properly configured to use the system's
CA bundle by default. In order to verify peer certificates, you will need to
supply the path on disk to a certificate bundle to the 'verify' request
option: http://docs.guzzlephp.org/en/5.3/clients.html#verify. If you do not
need a specific certificate bundle, then Mozilla provides a commonly used CA
bundle which can be downloaded here (provided by the maintainer of cURL):
https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt. Once
you have a CA bundle available on disk, you can set the 'openssl.cafile' PHP
ini setting to point to the path to the file, allowing you to omit the 'verify'
request option. See http://curl.haxx.se/docs/sslcerts.html for more
information.";
}

View File

@@ -1,560 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Ring\Exception\ConnectException;
use GuzzleHttp\Ring\Exception\RingException;
use GuzzleHttp\Stream\LazyOpenStream;
use GuzzleHttp\Stream\StreamInterface;
/**
* Creates curl resources from a request
*/
class CurlFactory
{
/**
* Creates a cURL handle, header resource, and body resource based on a
* transaction.
*
* @param array $request Request hash
* @param null|resource $handle Optionally provide a curl handle to modify
*
* @return array Returns an array of the curl handle, headers array, and
* response body handle.
* @throws \RuntimeException when an option cannot be applied
*/
public function __invoke(array $request, $handle = null)
{
$headers = [];
$options = $this->getDefaultOptions($request, $headers);
$this->applyMethod($request, $options);
if (isset($request['client'])) {
$this->applyHandlerOptions($request, $options);
}
$this->applyHeaders($request, $options);
unset($options['_headers']);
// Add handler options from the request's configuration options
if (isset($request['client']['curl'])) {
$options = $this->applyCustomCurlOptions(
$request['client']['curl'],
$options
);
}
if (!$handle) {
$handle = curl_init();
}
$body = $this->getOutputBody($request, $options);
curl_setopt_array($handle, $options);
return [$handle, &$headers, $body];
}
/**
* Creates a response hash from a cURL result.
*
* @param callable $handler Handler that was used.
* @param array $request Request that sent.
* @param array $response Response hash to update.
* @param array $headers Headers received during transfer.
* @param resource $body Body fopen response.
*
* @return array
*/
public static function createResponse(
callable $handler,
array $request,
array $response,
array $headers,
$body
) {
if (isset($response['transfer_stats']['url'])) {
$response['effective_url'] = $response['transfer_stats']['url'];
}
if (!empty($headers)) {
$startLine = explode(' ', array_shift($headers), 3);
$headerList = Core::headersFromLines($headers);
$response['headers'] = $headerList;
$response['version'] = isset($startLine[0]) ? substr($startLine[0], 5) : null;
$response['status'] = isset($startLine[1]) ? (int) $startLine[1] : null;
$response['reason'] = isset($startLine[2]) ? $startLine[2] : null;
$response['body'] = $body;
Core::rewindBody($response);
}
return !empty($response['curl']['errno']) || !isset($response['status'])
? self::createErrorResponse($handler, $request, $response)
: $response;
}
private static function createErrorResponse(
callable $handler,
array $request,
array $response
) {
static $connectionErrors = [
CURLE_OPERATION_TIMEOUTED => true,
CURLE_COULDNT_RESOLVE_HOST => true,
CURLE_COULDNT_CONNECT => true,
CURLE_SSL_CONNECT_ERROR => true,
CURLE_GOT_NOTHING => true,
];
// Retry when nothing is present or when curl failed to rewind.
if (!isset($response['err_message'])
&& (empty($response['curl']['errno'])
|| $response['curl']['errno'] == 65)
) {
return self::retryFailedRewind($handler, $request, $response);
}
$message = isset($response['err_message'])
? $response['err_message']
: sprintf('cURL error %s: %s',
$response['curl']['errno'],
isset($response['curl']['error'])
? $response['curl']['error']
: 'See http://curl.haxx.se/libcurl/c/libcurl-errors.html');
$error = isset($response['curl']['errno'])
&& isset($connectionErrors[$response['curl']['errno']])
? new ConnectException($message)
: new RingException($message);
return $response + [
'status' => null,
'reason' => null,
'body' => null,
'headers' => [],
'error' => $error,
];
}
private function getOutputBody(array $request, array &$options)
{
// Determine where the body of the response (if any) will be streamed.
if (isset($options[CURLOPT_WRITEFUNCTION])) {
return $request['client']['save_to'];
}
if (isset($options[CURLOPT_FILE])) {
return $options[CURLOPT_FILE];
}
if ($request['http_method'] != 'HEAD') {
// Create a default body if one was not provided
return $options[CURLOPT_FILE] = fopen('php://temp', 'w+');
}
return null;
}
private function getDefaultOptions(array $request, array &$headers)
{
$url = Core::url($request);
$startingResponse = false;
$options = [
'_headers' => $request['headers'],
CURLOPT_CUSTOMREQUEST => $request['http_method'],
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT => 150,
CURLOPT_HEADERFUNCTION => function ($ch, $h) use (&$headers, &$startingResponse) {
$value = trim($h);
if ($value === '') {
$startingResponse = true;
} elseif ($startingResponse) {
$startingResponse = false;
$headers = [$value];
} else {
$headers[] = $value;
}
return strlen($h);
},
];
if (isset($request['version'])) {
if ($request['version'] == 2.0) {
$options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_2_0;
} else if ($request['version'] == 1.1) {
$options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
} else {
$options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_0;
}
}
if (defined('CURLOPT_PROTOCOLS')) {
$options[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
}
return $options;
}
private function applyMethod(array $request, array &$options)
{
if (isset($request['body'])) {
$this->applyBody($request, $options);
return;
}
switch ($request['http_method']) {
case 'PUT':
case 'POST':
// See http://tools.ietf.org/html/rfc7230#section-3.3.2
if (!Core::hasHeader($request, 'Content-Length')) {
$options[CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
}
break;
case 'HEAD':
$options[CURLOPT_NOBODY] = true;
unset(
$options[CURLOPT_WRITEFUNCTION],
$options[CURLOPT_READFUNCTION],
$options[CURLOPT_FILE],
$options[CURLOPT_INFILE]
);
}
}
private function applyBody(array $request, array &$options)
{
$contentLength = Core::firstHeader($request, 'Content-Length');
$size = $contentLength !== null ? (int) $contentLength : null;
// Send the body as a string if the size is less than 1MB OR if the
// [client][curl][body_as_string] request value is set.
if (($size !== null && $size < 1000000) ||
isset($request['client']['curl']['body_as_string']) ||
is_string($request['body'])
) {
$options[CURLOPT_POSTFIELDS] = Core::body($request);
// Don't duplicate the Content-Length header
$this->removeHeader('Content-Length', $options);
$this->removeHeader('Transfer-Encoding', $options);
} else {
$options[CURLOPT_UPLOAD] = true;
if ($size !== null) {
// Let cURL handle setting the Content-Length header
$options[CURLOPT_INFILESIZE] = $size;
$this->removeHeader('Content-Length', $options);
}
$this->addStreamingBody($request, $options);
}
// If the Expect header is not present, prevent curl from adding it
if (!Core::hasHeader($request, 'Expect')) {
$options[CURLOPT_HTTPHEADER][] = 'Expect:';
}
// cURL sometimes adds a content-type by default. Prevent this.
if (!Core::hasHeader($request, 'Content-Type')) {
$options[CURLOPT_HTTPHEADER][] = 'Content-Type:';
}
}
private function addStreamingBody(array $request, array &$options)
{
$body = $request['body'];
if ($body instanceof StreamInterface) {
$options[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
return (string) $body->read($length);
};
if (!isset($options[CURLOPT_INFILESIZE])) {
if ($size = $body->getSize()) {
$options[CURLOPT_INFILESIZE] = $size;
}
}
} elseif (is_resource($body)) {
$options[CURLOPT_INFILE] = $body;
} elseif ($body instanceof \Iterator) {
$buf = '';
$options[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body, &$buf) {
if ($body->valid()) {
$buf .= $body->current();
$body->next();
}
$result = (string) substr($buf, 0, $length);
$buf = substr($buf, $length);
return $result;
};
} else {
throw new \InvalidArgumentException('Invalid request body provided');
}
}
private function applyHeaders(array $request, array &$options)
{
foreach ($options['_headers'] as $name => $values) {
foreach ($values as $value) {
$options[CURLOPT_HTTPHEADER][] = "$name: $value";
}
}
// Remove the Accept header if one was not set
if (!Core::hasHeader($request, 'Accept')) {
$options[CURLOPT_HTTPHEADER][] = 'Accept:';
}
}
/**
* Takes an array of curl options specified in the 'curl' option of a
* request's configuration array and maps them to CURLOPT_* options.
*
* This method is only called when a request has a 'curl' config setting.
*
* @param array $config Configuration array of custom curl option
* @param array $options Array of existing curl options
*
* @return array Returns a new array of curl options
*/
private function applyCustomCurlOptions(array $config, array $options)
{
$curlOptions = [];
foreach ($config as $key => $value) {
if (is_int($key)) {
$curlOptions[$key] = $value;
}
}
return $curlOptions + $options;
}
/**
* Remove a header from the options array.
*
* @param string $name Case-insensitive header to remove
* @param array $options Array of options to modify
*/
private function removeHeader($name, array &$options)
{
foreach (array_keys($options['_headers']) as $key) {
if (!strcasecmp($key, $name)) {
unset($options['_headers'][$key]);
return;
}
}
}
/**
* Applies an array of request client options to a the options array.
*
* This method uses a large switch rather than double-dispatch to save on
* high overhead of calling functions in PHP.
*/
private function applyHandlerOptions(array $request, array &$options)
{
foreach ($request['client'] as $key => $value) {
switch ($key) {
// Violating PSR-4 to provide more room.
case 'verify':
if ($value === false) {
unset($options[CURLOPT_CAINFO]);
$options[CURLOPT_SSL_VERIFYHOST] = 0;
$options[CURLOPT_SSL_VERIFYPEER] = false;
continue 2;
}
$options[CURLOPT_SSL_VERIFYHOST] = 2;
$options[CURLOPT_SSL_VERIFYPEER] = true;
if (is_string($value)) {
$options[CURLOPT_CAINFO] = $value;
if (!file_exists($value)) {
throw new \InvalidArgumentException(
"SSL CA bundle not found: $value"
);
}
}
break;
case 'decode_content':
if ($value === false) {
continue 2;
}
$accept = Core::firstHeader($request, 'Accept-Encoding');
if ($accept) {
$options[CURLOPT_ENCODING] = $accept;
} else {
$options[CURLOPT_ENCODING] = '';
// Don't let curl send the header over the wire
$options[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
}
break;
case 'save_to':
if (is_string($value)) {
if (!is_dir(dirname($value))) {
throw new \RuntimeException(sprintf(
'Directory %s does not exist for save_to value of %s',
dirname($value),
$value
));
}
$value = new LazyOpenStream($value, 'w+');
}
if ($value instanceof StreamInterface) {
$options[CURLOPT_WRITEFUNCTION] =
function ($ch, $write) use ($value) {
return $value->write($write);
};
} elseif (is_resource($value)) {
$options[CURLOPT_FILE] = $value;
} else {
throw new \InvalidArgumentException('save_to must be a '
. 'GuzzleHttp\Stream\StreamInterface or resource');
}
break;
case 'timeout':
if (defined('CURLOPT_TIMEOUT_MS')) {
$options[CURLOPT_TIMEOUT_MS] = $value * 1000;
} else {
$options[CURLOPT_TIMEOUT] = $value;
}
break;
case 'connect_timeout':
if (defined('CURLOPT_CONNECTTIMEOUT_MS')) {
$options[CURLOPT_CONNECTTIMEOUT_MS] = $value * 1000;
} else {
$options[CURLOPT_CONNECTTIMEOUT] = $value;
}
break;
case 'proxy':
if (!is_array($value)) {
$options[CURLOPT_PROXY] = $value;
} elseif (isset($request['scheme'])) {
$scheme = $request['scheme'];
if (isset($value[$scheme])) {
$options[CURLOPT_PROXY] = $value[$scheme];
}
}
break;
case 'cert':
if (is_array($value)) {
$options[CURLOPT_SSLCERTPASSWD] = $value[1];
$value = $value[0];
}
if (!file_exists($value)) {
throw new \InvalidArgumentException(
"SSL certificate not found: {$value}"
);
}
$options[CURLOPT_SSLCERT] = $value;
break;
case 'ssl_key':
if (is_array($value)) {
$options[CURLOPT_SSLKEYPASSWD] = $value[1];
$value = $value[0];
}
if (!file_exists($value)) {
throw new \InvalidArgumentException(
"SSL private key not found: {$value}"
);
}
$options[CURLOPT_SSLKEY] = $value;
break;
case 'progress':
if (!is_callable($value)) {
throw new \InvalidArgumentException(
'progress client option must be callable'
);
}
$options[CURLOPT_NOPROGRESS] = false;
$options[CURLOPT_PROGRESSFUNCTION] =
function () use ($value) {
$args = func_get_args();
// PHP 5.5 pushed the handle onto the start of the args
if (is_resource($args[0])) {
array_shift($args);
}
call_user_func_array($value, $args);
};
break;
case 'debug':
if ($value) {
$options[CURLOPT_STDERR] = Core::getDebugResource($value);
$options[CURLOPT_VERBOSE] = true;
}
break;
}
}
}
/**
* This function ensures that a response was set on a transaction. If one
* was not set, then the request is retried if possible. This error
* typically means you are sending a payload, curl encountered a
* "Connection died, retrying a fresh connect" error, tried to rewind the
* stream, and then encountered a "necessary data rewind wasn't possible"
* error, causing the request to be sent through curl_multi_info_read()
* without an error status.
*/
private static function retryFailedRewind(
callable $handler,
array $request,
array $response
) {
// If there is no body, then there is some other kind of issue. This
// is weird and should probably never happen.
if (!isset($request['body'])) {
$response['err_message'] = 'No response was received for a request '
. 'with no body. This could mean that you are saturating your '
. 'network.';
return self::createErrorResponse($handler, $request, $response);
}
if (!Core::rewindBody($request)) {
$response['err_message'] = 'The connection unexpectedly failed '
. 'without providing an error. The request would have been '
. 'retried, but attempting to rewind the request body failed.';
return self::createErrorResponse($handler, $request, $response);
}
// Retry no more than 3 times before giving up.
if (!isset($request['curl']['retries'])) {
$request['curl']['retries'] = 1;
} elseif ($request['curl']['retries'] == 2) {
$response['err_message'] = 'The cURL request was retried 3 times '
. 'and did no succeed. cURL was unable to rewind the body of '
. 'the request and subsequent retries resulted in the same '
. 'error. Turn on the debug option to see what went wrong. '
. 'See https://bugs.php.net/bug.php?id=47204 for more information.';
return self::createErrorResponse($handler, $request, $response);
} else {
$request['curl']['retries']++;
}
return $handler($request);
}
}

View File

@@ -1,135 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
use GuzzleHttp\Ring\Future\CompletedFutureArray;
use GuzzleHttp\Ring\Core;
/**
* HTTP handler that uses cURL easy handles as a transport layer.
*
* Requires PHP 5.5+
*
* When using the CurlHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the "client" key of the request.
*/
class CurlHandler
{
/** @var callable */
private $factory;
/** @var array Array of curl easy handles */
private $handles = [];
/** @var array Array of owned curl easy handles */
private $ownedHandles = [];
/** @var int Total number of idle handles to keep in cache */
private $maxHandles;
/**
* Accepts an associative array of options:
*
* - factory: Optional callable factory used to create cURL handles.
* The callable is passed a request hash when invoked, and returns an
* array of the curl handle, headers resource, and body resource.
* - max_handles: Maximum number of idle handles (defaults to 5).
*
* @param array $options Array of options to use with the handler
*/
public function __construct(array $options = [])
{
$this->handles = $this->ownedHandles = [];
$this->factory = isset($options['handle_factory'])
? $options['handle_factory']
: new CurlFactory();
$this->maxHandles = isset($options['max_handles'])
? $options['max_handles']
: 5;
}
public function __destruct()
{
foreach ($this->handles as $handle) {
if (is_resource($handle)) {
curl_close($handle);
}
}
}
/**
* @param array $request
*
* @return CompletedFutureArray
*/
public function __invoke(array $request)
{
return new CompletedFutureArray(
$this->_invokeAsArray($request)
);
}
/**
* @internal
*
* @param array $request
*
* @return array
*/
public function _invokeAsArray(array $request)
{
$factory = $this->factory;
// Ensure headers are by reference. They're updated elsewhere.
$result = $factory($request, $this->checkoutEasyHandle());
$h = $result[0];
$hd =& $result[1];
$bd = $result[2];
Core::doSleep($request);
curl_exec($h);
$response = ['transfer_stats' => curl_getinfo($h)];
$response['curl']['error'] = curl_error($h);
$response['curl']['errno'] = curl_errno($h);
$response['transfer_stats'] = array_merge($response['transfer_stats'], $response['curl']);
$this->releaseEasyHandle($h);
return CurlFactory::createResponse([$this, '_invokeAsArray'], $request, $response, $hd, $bd);
}
private function checkoutEasyHandle()
{
// Find an unused handle in the cache
if (false !== ($key = array_search(false, $this->ownedHandles, true))) {
$this->ownedHandles[$key] = true;
return $this->handles[$key];
}
// Add a new handle
$handle = curl_init();
$id = (int) $handle;
$this->handles[$id] = $handle;
$this->ownedHandles[$id] = true;
return $handle;
}
private function releaseEasyHandle($handle)
{
$id = (int) $handle;
if (count($this->ownedHandles) > $this->maxHandles) {
curl_close($this->handles[$id]);
unset($this->handles[$id], $this->ownedHandles[$id]);
} else {
// curl_reset doesn't clear these out for some reason
static $unsetValues = [
CURLOPT_HEADERFUNCTION => null,
CURLOPT_WRITEFUNCTION => null,
CURLOPT_READFUNCTION => null,
CURLOPT_PROGRESSFUNCTION => null,
];
curl_setopt_array($handle, $unsetValues);
curl_reset($handle);
$this->ownedHandles[$id] = false;
}
}
}

View File

@@ -1,248 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
use GuzzleHttp\Ring\Future\FutureArray;
use React\Promise\Deferred;
/**
* Returns an asynchronous response using curl_multi_* functions.
*
* This handler supports future responses and the "delay" request client
* option that can be used to delay before sending a request.
*
* When using the CurlMultiHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the "client" key of the request.
*
* @property resource $_mh Internal use only. Lazy loaded multi-handle.
*/
class CurlMultiHandler
{
/** @var callable */
private $factory;
private $selectTimeout;
private $active;
private $handles = [];
private $delays = [];
private $maxHandles;
/**
* This handler accepts the following options:
*
* - mh: An optional curl_multi resource
* - handle_factory: An optional callable used to generate curl handle
* resources. the callable accepts a request hash and returns an array
* of the handle, headers file resource, and the body resource.
* - select_timeout: Optional timeout (in seconds) to block before timing
* out while selecting curl handles. Defaults to 1 second.
* - max_handles: Optional integer representing the maximum number of
* open requests. When this number is reached, the queued futures are
* flushed.
*
* @param array $options
*/
public function __construct(array $options = [])
{
if (isset($options['mh'])) {
$this->_mh = $options['mh'];
}
$this->factory = isset($options['handle_factory'])
? $options['handle_factory'] : new CurlFactory();
$this->selectTimeout = isset($options['select_timeout'])
? $options['select_timeout'] : 1;
$this->maxHandles = isset($options['max_handles'])
? $options['max_handles'] : 100;
}
public function __get($name)
{
if ($name === '_mh') {
return $this->_mh = curl_multi_init();
}
throw new \BadMethodCallException();
}
public function __destruct()
{
// Finish any open connections before terminating the script.
if ($this->handles) {
$this->execute();
}
if (isset($this->_mh)) {
curl_multi_close($this->_mh);
unset($this->_mh);
}
}
public function __invoke(array $request)
{
$factory = $this->factory;
$result = $factory($request);
$entry = [
'request' => $request,
'response' => [],
'handle' => $result[0],
'headers' => &$result[1],
'body' => $result[2],
'deferred' => new Deferred(),
];
$id = (int) $result[0];
$future = new FutureArray(
$entry['deferred']->promise(),
[$this, 'execute'],
function () use ($id) {
return $this->cancel($id);
}
);
$this->addRequest($entry);
// Transfer outstanding requests if there are too many open handles.
if (count($this->handles) >= $this->maxHandles) {
$this->execute();
}
return $future;
}
/**
* Runs until all outstanding connections have completed.
*/
public function execute()
{
do {
if ($this->active &&
curl_multi_select($this->_mh, $this->selectTimeout) === -1
) {
// Perform a usleep if a select returns -1.
// See: https://bugs.php.net/bug.php?id=61141
usleep(250);
}
// Add any delayed futures if needed.
if ($this->delays) {
$this->addDelays();
}
do {
$mrc = curl_multi_exec($this->_mh, $this->active);
} while ($mrc === CURLM_CALL_MULTI_PERFORM);
$this->processMessages();
// If there are delays but no transfers, then sleep for a bit.
if (!$this->active && $this->delays) {
usleep(500);
}
} while ($this->active || $this->handles);
}
private function addRequest(array &$entry)
{
$id = (int) $entry['handle'];
$this->handles[$id] = $entry;
// If the request is a delay, then add the reques to the curl multi
// pool only after the specified delay.
if (isset($entry['request']['client']['delay'])) {
$this->delays[$id] = microtime(true) + ($entry['request']['client']['delay'] / 1000);
} elseif (empty($entry['request']['future'])) {
curl_multi_add_handle($this->_mh, $entry['handle']);
} else {
curl_multi_add_handle($this->_mh, $entry['handle']);
// "lazy" futures are only sent once the pool has many requests.
if ($entry['request']['future'] !== 'lazy') {
do {
$mrc = curl_multi_exec($this->_mh, $this->active);
} while ($mrc === CURLM_CALL_MULTI_PERFORM);
$this->processMessages();
}
}
}
private function removeProcessed($id)
{
if (isset($this->handles[$id])) {
curl_multi_remove_handle(
$this->_mh,
$this->handles[$id]['handle']
);
curl_close($this->handles[$id]['handle']);
unset($this->handles[$id], $this->delays[$id]);
}
}
/**
* Cancels a handle from sending and removes references to it.
*
* @param int $id Handle ID to cancel and remove.
*
* @return bool True on success, false on failure.
*/
private function cancel($id)
{
// Cannot cancel if it has been processed.
if (!isset($this->handles[$id])) {
return false;
}
$handle = $this->handles[$id]['handle'];
unset($this->delays[$id], $this->handles[$id]);
curl_multi_remove_handle($this->_mh, $handle);
curl_close($handle);
return true;
}
private function addDelays()
{
$currentTime = microtime(true);
foreach ($this->delays as $id => $delay) {
if ($currentTime >= $delay) {
unset($this->delays[$id]);
curl_multi_add_handle(
$this->_mh,
$this->handles[$id]['handle']
);
}
}
}
private function processMessages()
{
while ($done = curl_multi_info_read($this->_mh)) {
$id = (int) $done['handle'];
if (!isset($this->handles[$id])) {
// Probably was cancelled.
continue;
}
$entry = $this->handles[$id];
$entry['response']['transfer_stats'] = curl_getinfo($done['handle']);
if ($done['result'] !== CURLM_OK) {
$entry['response']['curl']['errno'] = $done['result'];
$entry['response']['curl']['error'] = curl_error($done['handle']);
}
$result = CurlFactory::createResponse(
$this,
$entry['request'],
$entry['response'],
$entry['headers'],
$entry['body']
);
$this->removeProcessed($id);
$entry['deferred']->resolve($result);
}
}
}

View File

@@ -1,58 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
/**
* Provides basic middleware wrappers.
*
* If a middleware is more complex than a few lines of code, then it should
* be implemented in a class rather than a static method.
*/
class Middleware
{
/**
* Sends future requests to a future compatible handler while sending all
* other requests to a default handler.
*
* When the "future" option is not provided on a request, any future responses
* are automatically converted to synchronous responses and block.
*
* @param callable $default Handler used for non-streaming responses
* @param callable $future Handler used for future responses
*
* @return callable Returns the composed handler.
*/
public static function wrapFuture(
callable $default,
callable $future
) {
return function (array $request) use ($default, $future) {
return empty($request['client']['future'])
? $default($request)
: $future($request);
};
}
/**
* Sends streaming requests to a streaming compatible handler while sendin
* all other requests to a default handler.
*
* This, for example, could be useful for taking advantage of the
* performance benefits of curl while still supporting true streaming
* through the StreamHandler.
*
* @param callable $default Handler used for non-streaming responses
* @param callable $streaming Handler used for streaming responses
*
* @return callable Returns the composed handler.
*/
public static function wrapStreaming(
callable $default,
callable $streaming
) {
return function (array $request) use ($default, $streaming) {
return empty($request['client']['stream'])
? $default($request)
: $streaming($request);
};
}
}

View File

@@ -1,52 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Ring\Future\CompletedFutureArray;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
/**
* Ring handler that returns a canned response or evaluated function result.
*/
class MockHandler
{
/** @var callable|array|FutureArrayInterface */
private $result;
/**
* Provide an array or future to always return the same value. Provide a
* callable that accepts a request object and returns an array or future
* to dynamically create a response.
*
* @param array|FutureArrayInterface|callable $result Mock return value.
*/
public function __construct($result)
{
$this->result = $result;
}
public function __invoke(array $request)
{
Core::doSleep($request);
$response = is_callable($this->result)
? call_user_func($this->result, $request)
: $this->result;
if (is_array($response)) {
$response = new CompletedFutureArray($response + [
'status' => null,
'body' => null,
'headers' => [],
'reason' => null,
'effective_url' => null,
]);
} elseif (!$response instanceof FutureArrayInterface) {
throw new \InvalidArgumentException(
'Response must be an array or FutureArrayInterface. Found '
. Core::describeType($request)
);
}
return $response;
}
}

View File

@@ -1,414 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Client;
use GuzzleHttp\Ring\Core;
use GuzzleHttp\Ring\Exception\ConnectException;
use GuzzleHttp\Ring\Exception\RingException;
use GuzzleHttp\Ring\Future\CompletedFutureArray;
use GuzzleHttp\Stream\InflateStream;
use GuzzleHttp\Stream\StreamInterface;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Stream\Utils;
/**
* RingPHP client handler that uses PHP's HTTP stream wrapper.
*/
class StreamHandler
{
private $options;
private $lastHeaders;
public function __construct(array $options = [])
{
$this->options = $options;
}
public function __invoke(array $request)
{
$url = Core::url($request);
Core::doSleep($request);
try {
// Does not support the expect header.
$request = Core::removeHeader($request, 'Expect');
$stream = $this->createStream($url, $request);
return $this->createResponse($request, $url, $stream);
} catch (RingException $e) {
return $this->createErrorResponse($url, $e);
}
}
private function createResponse(array $request, $url, $stream)
{
$hdrs = $this->lastHeaders;
$this->lastHeaders = null;
$parts = explode(' ', array_shift($hdrs), 3);
$response = [
'version' => substr($parts[0], 5),
'status' => $parts[1],
'reason' => isset($parts[2]) ? $parts[2] : null,
'headers' => Core::headersFromLines($hdrs),
'effective_url' => $url,
];
$stream = $this->checkDecode($request, $response, $stream);
// If not streaming, then drain the response into a stream.
if (empty($request['client']['stream'])) {
$dest = isset($request['client']['save_to'])
? $request['client']['save_to']
: fopen('php://temp', 'r+');
$stream = $this->drain($stream, $dest);
}
$response['body'] = $stream;
return new CompletedFutureArray($response);
}
private function checkDecode(array $request, array $response, $stream)
{
// Automatically decode responses when instructed.
if (!empty($request['client']['decode_content'])) {
switch (Core::firstHeader($response, 'Content-Encoding', true)) {
case 'gzip':
case 'deflate':
$stream = new InflateStream(Stream::factory($stream));
break;
}
}
return $stream;
}
/**
* Drains the stream into the "save_to" client option.
*
* @param resource $stream
* @param string|resource|StreamInterface $dest
*
* @return Stream
* @throws \RuntimeException when the save_to option is invalid.
*/
private function drain($stream, $dest)
{
if (is_resource($stream)) {
if (!is_resource($dest)) {
$stream = Stream::factory($stream);
} else {
stream_copy_to_stream($stream, $dest);
fclose($stream);
rewind($dest);
return $dest;
}
}
// Stream the response into the destination stream
$dest = is_string($dest)
? new Stream(Utils::open($dest, 'r+'))
: Stream::factory($dest);
Utils::copyToStream($stream, $dest);
$dest->seek(0);
$stream->close();
return $dest;
}
/**
* Creates an error response for the given stream.
*
* @param string $url
* @param RingException $e
*
* @return array
*/
private function createErrorResponse($url, RingException $e)
{
// Determine if the error was a networking error.
$message = $e->getMessage();
// This list can probably get more comprehensive.
if (strpos($message, 'getaddrinfo') // DNS lookup failed
|| strpos($message, 'Connection refused')
) {
$e = new ConnectException($e->getMessage(), 0, $e);
}
return new CompletedFutureArray([
'status' => null,
'body' => null,
'headers' => [],
'effective_url' => $url,
'error' => $e
]);
}
/**
* Create a resource and check to ensure it was created successfully
*
* @param callable $callback Callable that returns stream resource
*
* @return resource
* @throws \RuntimeException on error
*/
private function createResource(callable $callback)
{
$errors = null;
set_error_handler(function ($_, $msg, $file, $line) use (&$errors) {
$errors[] = [
'message' => $msg,
'file' => $file,
'line' => $line
];
return true;
});
$resource = $callback();
restore_error_handler();
if (!$resource) {
$message = 'Error creating resource: ';
foreach ($errors as $err) {
foreach ($err as $key => $value) {
$message .= "[$key] $value" . PHP_EOL;
}
}
throw new RingException(trim($message));
}
return $resource;
}
private function createStream($url, array $request)
{
static $methods;
if (!$methods) {
$methods = array_flip(get_class_methods(__CLASS__));
}
// HTTP/1.1 streams using the PHP stream wrapper require a
// Connection: close header
if ((!isset($request['version']) || $request['version'] == '1.1')
&& !Core::hasHeader($request, 'Connection')
) {
$request['headers']['Connection'] = ['close'];
}
// Ensure SSL is verified by default
if (!isset($request['client']['verify'])) {
$request['client']['verify'] = true;
}
$params = [];
$options = $this->getDefaultOptions($request);
if (isset($request['client'])) {
foreach ($request['client'] as $key => $value) {
$method = "add_{$key}";
if (isset($methods[$method])) {
$this->{$method}($request, $options, $value, $params);
}
}
}
return $this->createStreamResource(
$url,
$request,
$options,
$this->createContext($request, $options, $params)
);
}
private function getDefaultOptions(array $request)
{
$headers = "";
foreach ($request['headers'] as $name => $value) {
foreach ((array) $value as $val) {
$headers .= "$name: $val\r\n";
}
}
$context = [
'http' => [
'method' => $request['http_method'],
'header' => $headers,
'protocol_version' => isset($request['version']) ? $request['version'] : 1.1,
'ignore_errors' => true,
'follow_location' => 0,
],
];
$body = Core::body($request);
if (isset($body)) {
$context['http']['content'] = $body;
// Prevent the HTTP handler from adding a Content-Type header.
if (!Core::hasHeader($request, 'Content-Type')) {
$context['http']['header'] .= "Content-Type:\r\n";
}
}
$context['http']['header'] = rtrim($context['http']['header']);
return $context;
}
private function add_proxy(array $request, &$options, $value, &$params)
{
if (!is_array($value)) {
$options['http']['proxy'] = $value;
} else {
$scheme = isset($request['scheme']) ? $request['scheme'] : 'http';
if (isset($value[$scheme])) {
$options['http']['proxy'] = $value[$scheme];
}
}
}
private function add_timeout(array $request, &$options, $value, &$params)
{
$options['http']['timeout'] = $value;
}
private function add_verify(array $request, &$options, $value, &$params)
{
if ($value === true) {
// PHP 5.6 or greater will find the system cert by default. When
// < 5.6, use the Guzzle bundled cacert.
if (PHP_VERSION_ID < 50600) {
$options['ssl']['cafile'] = ClientUtils::getDefaultCaBundle();
}
} elseif (is_string($value)) {
$options['ssl']['cafile'] = $value;
if (!file_exists($value)) {
throw new RingException("SSL CA bundle not found: $value");
}
} elseif ($value === false) {
$options['ssl']['verify_peer'] = false;
$options['ssl']['allow_self_signed'] = true;
return;
} else {
throw new RingException('Invalid verify request option');
}
$options['ssl']['verify_peer'] = true;
$options['ssl']['allow_self_signed'] = false;
}
private function add_cert(array $request, &$options, $value, &$params)
{
if (is_array($value)) {
$options['ssl']['passphrase'] = $value[1];
$value = $value[0];
}
if (!file_exists($value)) {
throw new RingException("SSL certificate not found: {$value}");
}
$options['ssl']['local_cert'] = $value;
}
private function add_progress(array $request, &$options, $value, &$params)
{
$fn = function ($code, $_1, $_2, $_3, $transferred, $total) use ($value) {
if ($code == STREAM_NOTIFY_PROGRESS) {
$value($total, $transferred, null, null);
}
};
// Wrap the existing function if needed.
$params['notification'] = isset($params['notification'])
? Core::callArray([$params['notification'], $fn])
: $fn;
}
private function add_debug(array $request, &$options, $value, &$params)
{
if ($value === false) {
return;
}
static $map = [
STREAM_NOTIFY_CONNECT => 'CONNECT',
STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
STREAM_NOTIFY_PROGRESS => 'PROGRESS',
STREAM_NOTIFY_FAILURE => 'FAILURE',
STREAM_NOTIFY_COMPLETED => 'COMPLETED',
STREAM_NOTIFY_RESOLVE => 'RESOLVE',
];
static $args = ['severity', 'message', 'message_code',
'bytes_transferred', 'bytes_max'];
$value = Core::getDebugResource($value);
$ident = $request['http_method'] . ' ' . Core::url($request);
$fn = function () use ($ident, $value, $map, $args) {
$passed = func_get_args();
$code = array_shift($passed);
fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
foreach (array_filter($passed) as $i => $v) {
fwrite($value, $args[$i] . ': "' . $v . '" ');
}
fwrite($value, "\n");
};
// Wrap the existing function if needed.
$params['notification'] = isset($params['notification'])
? Core::callArray([$params['notification'], $fn])
: $fn;
}
private function applyCustomOptions(array $request, array &$options)
{
if (!isset($request['client']['stream_context'])) {
return;
}
if (!is_array($request['client']['stream_context'])) {
throw new RingException('stream_context must be an array');
}
$options = array_replace_recursive(
$options,
$request['client']['stream_context']
);
}
private function createContext(array $request, array $options, array $params)
{
$this->applyCustomOptions($request, $options);
return $this->createResource(
function () use ($request, $options, $params) {
return stream_context_create($options, $params);
},
$request,
$options
);
}
private function createStreamResource(
$url,
array $request,
array $options,
$context
) {
return $this->createResource(
function () use ($url, $context) {
if (false === strpos($url, 'http')) {
trigger_error("URL is invalid: {$url}", E_USER_WARNING);
return null;
}
$resource = fopen($url, 'r', null, $context);
$this->lastHeaders = $http_response_header;
return $resource;
},
$request,
$options
);
}
}

View File

@@ -1,364 +0,0 @@
<?php
namespace GuzzleHttp\Ring;
use GuzzleHttp\Stream\StreamInterface;
use GuzzleHttp\Ring\Future\FutureArrayInterface;
use GuzzleHttp\Ring\Future\FutureArray;
/**
* Provides core functionality of Ring handlers and middleware.
*/
class Core
{
/**
* Returns a function that calls all of the provided functions, in order,
* passing the arguments provided to the composed function to each function.
*
* @param callable[] $functions Array of functions to proxy to.
*
* @return callable
*/
public static function callArray(array $functions)
{
return function () use ($functions) {
$args = func_get_args();
foreach ($functions as $fn) {
call_user_func_array($fn, $args);
}
};
}
/**
* Gets an array of header line values from a message for a specific header
*
* This method searches through the "headers" key of a message for a header
* using a case-insensitive search.
*
* @param array $message Request or response hash.
* @param string $header Header to retrieve
*
* @return array
*/
public static function headerLines($message, $header)
{
$result = [];
if (!empty($message['headers'])) {
foreach ($message['headers'] as $name => $value) {
if (!strcasecmp($name, $header)) {
$result = array_merge($result, $value);
}
}
}
return $result;
}
/**
* Gets a header value from a message as a string or null
*
* This method searches through the "headers" key of a message for a header
* using a case-insensitive search. The lines of the header are imploded
* using commas into a single string return value.
*
* @param array $message Request or response hash.
* @param string $header Header to retrieve
*
* @return string|null Returns the header string if found, or null if not.
*/
public static function header($message, $header)
{
$match = self::headerLines($message, $header);
return $match ? implode(', ', $match) : null;
}
/**
* Returns the first header value from a message as a string or null. If
* a header line contains multiple values separated by a comma, then this
* function will return the first value in the list.
*
* @param array $message Request or response hash.
* @param string $header Header to retrieve
*
* @return string|null Returns the value as a string if found.
*/
public static function firstHeader($message, $header)
{
if (!empty($message['headers'])) {
foreach ($message['headers'] as $name => $value) {
if (!strcasecmp($name, $header)) {
// Return the match itself if it is a single value.
$pos = strpos($value[0], ',');
return $pos ? substr($value[0], 0, $pos) : $value[0];
}
}
}
return null;
}
/**
* Returns true if a message has the provided case-insensitive header.
*
* @param array $message Request or response hash.
* @param string $header Header to check
*
* @return bool
*/
public static function hasHeader($message, $header)
{
if (!empty($message['headers'])) {
foreach ($message['headers'] as $name => $value) {
if (!strcasecmp($name, $header)) {
return true;
}
}
}
return false;
}
/**
* Parses an array of header lines into an associative array of headers.
*
* @param array $lines Header lines array of strings in the following
* format: "Name: Value"
* @return array
*/
public static function headersFromLines($lines)
{
$headers = [];
foreach ($lines as $line) {
$parts = explode(':', $line, 2);
$headers[trim($parts[0])][] = isset($parts[1])
? trim($parts[1])
: null;
}
return $headers;
}
/**
* Removes a header from a message using a case-insensitive comparison.
*
* @param array $message Message that contains 'headers'
* @param string $header Header to remove
*
* @return array
*/
public static function removeHeader(array $message, $header)
{
if (isset($message['headers'])) {
foreach (array_keys($message['headers']) as $key) {
if (!strcasecmp($header, $key)) {
unset($message['headers'][$key]);
}
}
}
return $message;
}
/**
* Replaces any existing case insensitive headers with the given value.
*
* @param array $message Message that contains 'headers'
* @param string $header Header to set.
* @param array $value Value to set.
*
* @return array
*/
public static function setHeader(array $message, $header, array $value)
{
$message = self::removeHeader($message, $header);
$message['headers'][$header] = $value;
return $message;
}
/**
* Creates a URL string from a request.
*
* If the "url" key is present on the request, it is returned, otherwise
* the url is built up based on the scheme, host, uri, and query_string
* request values.
*
* @param array $request Request to get the URL from
*
* @return string Returns the request URL as a string.
* @throws \InvalidArgumentException if no Host header is present.
*/
public static function url(array $request)
{
if (isset($request['url'])) {
return $request['url'];
}
$uri = (isset($request['scheme'])
? $request['scheme'] : 'http') . '://';
if ($host = self::header($request, 'host')) {
$uri .= $host;
} else {
throw new \InvalidArgumentException('No Host header was provided');
}
if (isset($request['uri'])) {
$uri .= $request['uri'];
}
if (isset($request['query_string'])) {
$uri .= '?' . $request['query_string'];
}
return $uri;
}
/**
* Reads the body of a message into a string.
*
* @param array|FutureArrayInterface $message Array containing a "body" key
*
* @return null|string Returns the body as a string or null if not set.
* @throws \InvalidArgumentException if a request body is invalid.
*/
public static function body($message)
{
if (!isset($message['body'])) {
return null;
}
if ($message['body'] instanceof StreamInterface) {
return (string) $message['body'];
}
switch (gettype($message['body'])) {
case 'string':
return $message['body'];
case 'resource':
return stream_get_contents($message['body']);
case 'object':
if ($message['body'] instanceof \Iterator) {
return implode('', iterator_to_array($message['body']));
} elseif (method_exists($message['body'], '__toString')) {
return (string) $message['body'];
}
default:
throw new \InvalidArgumentException('Invalid request body: '
. self::describeType($message['body']));
}
}
/**
* Rewind the body of the provided message if possible.
*
* @param array $message Message that contains a 'body' field.
*
* @return bool Returns true on success, false on failure
*/
public static function rewindBody($message)
{
if ($message['body'] instanceof StreamInterface) {
return $message['body']->seek(0);
}
if ($message['body'] instanceof \Generator) {
return false;
}
if ($message['body'] instanceof \Iterator) {
$message['body']->rewind();
return true;
}
if (is_resource($message['body'])) {
return rewind($message['body']);
}
return is_string($message['body'])
|| (is_object($message['body'])
&& method_exists($message['body'], '__toString'));
}
/**
* Debug function used to describe the provided value type and class.
*
* @param mixed $input
*
* @return string Returns a string containing the type of the variable and
* if a class is provided, the class name.
*/
public static function describeType($input)
{
switch (gettype($input)) {
case 'object':
return 'object(' . get_class($input) . ')';
case 'array':
return 'array(' . count($input) . ')';
default:
ob_start();
var_dump($input);
// normalize float vs double
return str_replace('double(', 'float(', rtrim(ob_get_clean()));
}
}
/**
* Sleep for the specified amount of time specified in the request's
* ['client']['delay'] option if present.
*
* This function should only be used when a non-blocking sleep is not
* possible.
*
* @param array $request Request to sleep
*/
public static function doSleep(array $request)
{
if (isset($request['client']['delay'])) {
usleep($request['client']['delay'] * 1000);
}
}
/**
* Returns a proxied future that modifies the dereferenced value of another
* future using a promise.
*
* @param FutureArrayInterface $future Future to wrap with a new future
* @param callable $onFulfilled Invoked when the future fulfilled
* @param callable $onRejected Invoked when the future rejected
* @param callable $onProgress Invoked when the future progresses
*
* @return FutureArray
*/
public static function proxy(
FutureArrayInterface $future,
callable $onFulfilled = null,
callable $onRejected = null,
callable $onProgress = null
) {
return new FutureArray(
$future->then($onFulfilled, $onRejected, $onProgress),
[$future, 'wait'],
[$future, 'cancel']
);
}
/**
* Returns a debug stream based on the provided variable.
*
* @param mixed $value Optional value
*
* @return resource
*/
public static function getDebugResource($value = null)
{
if (is_resource($value)) {
return $value;
} elseif (defined('STDOUT')) {
return STDOUT;
} else {
return fopen('php://output', 'w');
}
}
}

View File

@@ -1,7 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Exception;
/**
* Marker interface for cancelled exceptions.
*/
interface CancelledException {}

View File

@@ -1,4 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Exception;
class CancelledFutureAccessException extends RingException implements CancelledException {}

View File

@@ -1,7 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Exception;
/**
* Occurs when the connection failed.
*/
class ConnectException extends RingException {}

View File

@@ -1,4 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Exception;
class RingException extends \RuntimeException {};

View File

@@ -1,125 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
use GuzzleHttp\Ring\Exception\CancelledFutureAccessException;
use GuzzleHttp\Ring\Exception\RingException;
use React\Promise\PromiseInterface;
/**
* Implements common future functionality built on top of promises.
*/
trait BaseFutureTrait
{
/** @var callable */
private $waitfn;
/** @var callable */
private $cancelfn;
/** @var PromiseInterface */
private $wrappedPromise;
/** @var \Exception Error encountered. */
private $error;
/** @var mixed Result of the future */
private $result;
private $isRealized = false;
/**
* @param PromiseInterface $promise Promise to shadow with the future.
* @param callable $wait Function that blocks until the deferred
* computation has been resolved. This
* function MUST resolve the deferred value
* associated with the supplied promise.
* @param callable $cancel If possible and reasonable, provide a
* function that can be used to cancel the
* future from completing.
*/
public function __construct(
PromiseInterface $promise,
callable $wait = null,
callable $cancel = null
) {
$this->wrappedPromise = $promise;
$this->waitfn = $wait;
$this->cancelfn = $cancel;
}
public function wait()
{
if (!$this->isRealized) {
$this->addShadow();
if (!$this->isRealized && $this->waitfn) {
$this->invokeWait();
}
if (!$this->isRealized) {
$this->error = new RingException('Waiting did not resolve future');
}
}
if ($this->error) {
throw $this->error;
}
return $this->result;
}
public function promise()
{
return $this->wrappedPromise;
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null,
callable $onProgress = null
) {
return $this->wrappedPromise->then($onFulfilled, $onRejected, $onProgress);
}
public function cancel()
{
if (!$this->isRealized) {
$cancelfn = $this->cancelfn;
$this->waitfn = $this->cancelfn = null;
$this->isRealized = true;
$this->error = new CancelledFutureAccessException();
if ($cancelfn) {
$cancelfn($this);
}
}
}
private function addShadow()
{
// Get the result and error when the promise is resolved. Note that
// calling this function might trigger the resolution immediately.
$this->wrappedPromise->then(
function ($value) {
$this->isRealized = true;
$this->result = $value;
$this->waitfn = $this->cancelfn = null;
},
function ($error) {
$this->isRealized = true;
$this->error = $error;
$this->waitfn = $this->cancelfn = null;
}
);
}
private function invokeWait()
{
try {
$wait = $this->waitfn;
$this->waitfn = null;
$wait();
} catch (\Exception $e) {
// Defer can throw to reject.
$this->error = $e;
$this->isRealized = true;
}
}
}

View File

@@ -1,43 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
/**
* Represents a future array that has been completed successfully.
*/
class CompletedFutureArray extends CompletedFutureValue implements FutureArrayInterface
{
public function __construct(array $result)
{
parent::__construct($result);
}
public function offsetExists($offset)
{
return isset($this->result[$offset]);
}
public function offsetGet($offset)
{
return $this->result[$offset];
}
public function offsetSet($offset, $value)
{
$this->result[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->result[$offset]);
}
public function count()
{
return count($this->result);
}
public function getIterator()
{
return new \ArrayIterator($this->result);
}
}

View File

@@ -1,57 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
use React\Promise\FulfilledPromise;
use React\Promise\RejectedPromise;
/**
* Represents a future value that has been resolved or rejected.
*/
class CompletedFutureValue implements FutureInterface
{
protected $result;
protected $error;
private $cachedPromise;
/**
* @param mixed $result Resolved result
* @param \Exception $e Error. Pass a GuzzleHttp\Ring\Exception\CancelledFutureAccessException
* to mark the future as cancelled.
*/
public function __construct($result, \Exception $e = null)
{
$this->result = $result;
$this->error = $e;
}
public function wait()
{
if ($this->error) {
throw $this->error;
}
return $this->result;
}
public function cancel() {}
public function promise()
{
if (!$this->cachedPromise) {
$this->cachedPromise = $this->error
? new RejectedPromise($this->error)
: new FulfilledPromise($this->result);
}
return $this->cachedPromise;
}
public function then(
callable $onFulfilled = null,
callable $onRejected = null,
callable $onProgress = null
) {
return $this->promise()->then($onFulfilled, $onRejected, $onProgress);
}
}

View File

@@ -1,40 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
/**
* Represents a future array value that when dereferenced returns an array.
*/
class FutureArray implements FutureArrayInterface
{
use MagicFutureTrait;
public function offsetExists($offset)
{
return isset($this->_value[$offset]);
}
public function offsetGet($offset)
{
return $this->_value[$offset];
}
public function offsetSet($offset, $value)
{
$this->_value[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->_value[$offset]);
}
public function count()
{
return count($this->_value);
}
public function getIterator()
{
return new \ArrayIterator($this->_value);
}
}

View File

@@ -1,11 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
/**
* Future that provides array-like access.
*/
interface FutureArrayInterface extends
FutureInterface,
\ArrayAccess,
\Countable,
\IteratorAggregate {};

View File

@@ -1,40 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
use React\Promise\PromiseInterface;
use React\Promise\PromisorInterface;
/**
* Represents the result of a computation that may not have completed yet.
*
* You can use the future in a blocking manner using the wait() function, or
* you can use a promise from the future to receive the result when the future
* has been resolved.
*
* When the future is dereferenced using wait(), the result of the computation
* is cached and returned for subsequent calls to wait(). If the result of the
* computation has not yet completed when wait() is called, the call to wait()
* will block until the future has completed.
*/
interface FutureInterface extends PromiseInterface, PromisorInterface
{
/**
* Returns the result of the future either from cache or by blocking until
* it is complete.
*
* This method must block until the future has a result or is cancelled.
* Throwing an exception in the wait() method will mark the future as
* realized and will throw the exception each time wait() is called.
* Throwing an instance of GuzzleHttp\Ring\CancelledException will mark
* the future as realized, will not throw immediately, but will throw the
* exception if the future's wait() method is called again.
*
* @return mixed
*/
public function wait();
/**
* Cancels the future, if possible.
*/
public function cancel();
}

View File

@@ -1,12 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
/**
* Represents a future value that responds to wait() to retrieve the promised
* value, but can also return promises that are delivered the value when it is
* available.
*/
class FutureValue implements FutureInterface
{
use BaseFutureTrait;
}

View File

@@ -1,32 +0,0 @@
<?php
namespace GuzzleHttp\Ring\Future;
/**
* Implements common future functionality that is triggered when the result
* property is accessed via a magic __get method.
*
* @property mixed $_value Actual data used by the future. Accessing this
* property will cause the future to block if needed.
*/
trait MagicFutureTrait
{
use BaseFutureTrait;
/**
* This function handles retrieving the dereferenced result when requested.
*
* @param string $name Should always be "data" or an exception is thrown.
*
* @return mixed Returns the dereferenced data.
* @throws \RuntimeException
* @throws \GuzzleHttp\Ring\Exception\CancelledException
*/
public function __get($name)
{
if ($name !== '_value') {
throw new \RuntimeException("Class has no {$name} property");
}
return $this->_value = $this->wait();
}
}

View File

@@ -1,19 +0,0 @@
Copyright (c) 2014 Michael Dowling, https://github.com/mtdowling <mtdowling@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -1,28 +0,0 @@
{
"name": "guzzlehttp/streams",
"description": "Provides a simple abstraction over streams of data",
"homepage": "http://guzzlephp.org/",
"keywords": ["stream", "guzzle"],
"license": "MIT",
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"require": {
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"autoload": {
"psr-4": { "GuzzleHttp\\Stream\\": "src/" }
},
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
}
}

View File

@@ -1,220 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\CannotAttachException;
/**
* Reads from multiple streams, one after the other.
*
* This is a read-only stream decorator.
*/
class AppendStream implements StreamInterface
{
/** @var StreamInterface[] Streams being decorated */
private $streams = [];
private $seekable = true;
private $current = 0;
private $pos = 0;
private $detached = false;
/**
* @param StreamInterface[] $streams Streams to decorate. Each stream must
* be readable.
*/
public function __construct(array $streams = [])
{
foreach ($streams as $stream) {
$this->addStream($stream);
}
}
public function __toString()
{
try {
$this->seek(0);
return $this->getContents();
} catch (\Exception $e) {
return '';
}
}
/**
* Add a stream to the AppendStream
*
* @param StreamInterface $stream Stream to append. Must be readable.
*
* @throws \InvalidArgumentException if the stream is not readable
*/
public function addStream(StreamInterface $stream)
{
if (!$stream->isReadable()) {
throw new \InvalidArgumentException('Each stream must be readable');
}
// The stream is only seekable if all streams are seekable
if (!$stream->isSeekable()) {
$this->seekable = false;
}
$this->streams[] = $stream;
}
public function getContents()
{
return Utils::copyToString($this);
}
/**
* Closes each attached stream.
*
* {@inheritdoc}
*/
public function close()
{
$this->pos = $this->current = 0;
foreach ($this->streams as $stream) {
$stream->close();
}
$this->streams = [];
}
/**
* Detaches each attached stream
*
* {@inheritdoc}
*/
public function detach()
{
$this->close();
$this->detached = true;
}
public function attach($stream)
{
throw new CannotAttachException();
}
public function tell()
{
return $this->pos;
}
/**
* Tries to calculate the size by adding the size of each stream.
*
* If any of the streams do not return a valid number, then the size of the
* append stream cannot be determined and null is returned.
*
* {@inheritdoc}
*/
public function getSize()
{
$size = 0;
foreach ($this->streams as $stream) {
$s = $stream->getSize();
if ($s === null) {
return null;
}
$size += $s;
}
return $size;
}
public function eof()
{
return !$this->streams ||
($this->current >= count($this->streams) - 1 &&
$this->streams[$this->current]->eof());
}
/**
* Attempts to seek to the given position. Only supports SEEK_SET.
*
* {@inheritdoc}
*/
public function seek($offset, $whence = SEEK_SET)
{
if (!$this->seekable || $whence !== SEEK_SET) {
return false;
}
$success = true;
$this->pos = $this->current = 0;
// Rewind each stream
foreach ($this->streams as $stream) {
if (!$stream->seek(0)) {
$success = false;
}
}
if (!$success) {
return false;
}
// Seek to the actual position by reading from each stream
while ($this->pos < $offset && !$this->eof()) {
$this->read(min(8096, $offset - $this->pos));
}
return $this->pos == $offset;
}
/**
* Reads from all of the appended streams until the length is met or EOF.
*
* {@inheritdoc}
*/
public function read($length)
{
$buffer = '';
$total = count($this->streams) - 1;
$remaining = $length;
while ($remaining > 0) {
// Progress to the next stream if needed.
if ($this->streams[$this->current]->eof()) {
if ($this->current == $total) {
break;
}
$this->current++;
}
$buffer .= $this->streams[$this->current]->read($remaining);
$remaining = $length - strlen($buffer);
}
$this->pos += strlen($buffer);
return $buffer;
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return false;
}
public function isSeekable()
{
return $this->seekable;
}
public function write($string)
{
return false;
}
public function getMetadata($key = null)
{
return $key ? null : [];
}
}

View File

@@ -1,207 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Represents an asynchronous read-only stream that supports a drain event and
* pumping data from a source stream.
*
* The AsyncReadStream can be used as a completely asynchronous stream, meaning
* the data you can read from the stream will immediately return only
* the data that is currently buffered.
*
* AsyncReadStream can also be used in a "blocking" manner if a "pump" function
* is provided. When a caller requests more bytes than are available in the
* buffer, then the pump function is used to block until the requested number
* of bytes are available or the remote source stream has errored, closed, or
* timed-out. This behavior isn't strictly "blocking" because the pump function
* can send other transfers while waiting on the desired buffer size to be
* ready for reading (e.g., continue to tick an event loop).
*
* @unstable This class is subject to change.
*/
class AsyncReadStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var callable|null Fn used to notify writers the buffer has drained */
private $drain;
/** @var callable|null Fn used to block for more data */
private $pump;
/** @var int|null Highwater mark of the underlying buffer */
private $hwm;
/** @var bool Whether or not drain needs to be called at some point */
private $needsDrain;
/** @var int The expected size of the remote source */
private $size;
/**
* In order to utilize high water marks to tell writers to slow down, the
* provided stream must answer to the "hwm" stream metadata variable,
* providing the high water mark. If no "hwm" metadata value is available,
* then the "drain" functionality is not utilized.
*
* This class accepts an associative array of configuration options.
*
* - drain: (callable) Function to invoke when the stream has drained,
* meaning the buffer is now writable again because the size of the
* buffer is at an acceptable level (e.g., below the high water mark).
* The function accepts a single argument, the buffer stream object that
* has drained.
* - pump: (callable) A function that accepts the number of bytes to read
* from the source stream. This function will block until all of the data
* that was requested has been read, EOF of the source stream, or the
* source stream is closed.
* - size: (int) The expected size in bytes of the data that will be read
* (if known up-front).
*
* @param StreamInterface $buffer Buffer that contains the data that has
* been read by the event loop.
* @param array $config Associative array of options.
*
* @throws \InvalidArgumentException if the buffer is not readable and
* writable.
*/
public function __construct(
StreamInterface $buffer,
array $config = []
) {
if (!$buffer->isReadable() || !$buffer->isWritable()) {
throw new \InvalidArgumentException(
'Buffer must be readable and writable'
);
}
if (isset($config['size'])) {
$this->size = $config['size'];
}
static $callables = ['pump', 'drain'];
foreach ($callables as $check) {
if (isset($config[$check])) {
if (!is_callable($config[$check])) {
throw new \InvalidArgumentException(
$check . ' must be callable'
);
}
$this->{$check} = $config[$check];
}
}
$this->hwm = $buffer->getMetadata('hwm');
// Cannot drain when there's no high water mark.
if ($this->hwm === null) {
$this->drain = null;
}
$this->stream = $buffer;
}
/**
* Factory method used to create new async stream and an underlying buffer
* if no buffer is provided.
*
* This function accepts the same options as AsyncReadStream::__construct,
* but added the following key value pairs:
*
* - buffer: (StreamInterface) Buffer used to buffer data. If none is
* provided, a default buffer is created.
* - hwm: (int) High water mark to use if a buffer is created on your
* behalf.
* - max_buffer: (int) If provided, wraps the utilized buffer in a
* DroppingStream decorator to ensure that buffer does not exceed a given
* length. When exceeded, the stream will begin dropping data. Set the
* max_buffer to 0, to use a NullStream which does not store data.
* - write: (callable) A function that is invoked when data is written
* to the underlying buffer. The function accepts the buffer as the first
* argument, and the data being written as the second. The function MUST
* return the number of bytes that were written or false to let writers
* know to slow down.
* - drain: (callable) See constructor documentation.
* - pump: (callable) See constructor documentation.
*
* @param array $options Associative array of options.
*
* @return array Returns an array containing the buffer used to buffer
* data, followed by the ready to use AsyncReadStream object.
*/
public static function create(array $options = [])
{
$maxBuffer = isset($options['max_buffer'])
? $options['max_buffer']
: null;
if ($maxBuffer === 0) {
$buffer = new NullStream();
} elseif (isset($options['buffer'])) {
$buffer = $options['buffer'];
} else {
$hwm = isset($options['hwm']) ? $options['hwm'] : 16384;
$buffer = new BufferStream($hwm);
}
if ($maxBuffer > 0) {
$buffer = new DroppingStream($buffer, $options['max_buffer']);
}
// Call the on_write callback if an on_write function was provided.
if (isset($options['write'])) {
$onWrite = $options['write'];
$buffer = FnStream::decorate($buffer, [
'write' => function ($string) use ($buffer, $onWrite) {
$result = $buffer->write($string);
$onWrite($buffer, $string);
return $result;
}
]);
}
return [$buffer, new self($buffer, $options)];
}
public function getSize()
{
return $this->size;
}
public function isWritable()
{
return false;
}
public function write($string)
{
return false;
}
public function read($length)
{
if (!$this->needsDrain && $this->drain) {
$this->needsDrain = $this->stream->getSize() >= $this->hwm;
}
$result = $this->stream->read($length);
// If we need to drain, then drain when the buffer is empty.
if ($this->needsDrain && $this->stream->getSize() === 0) {
$this->needsDrain = false;
$drainFn = $this->drain;
$drainFn($this->stream);
}
$resultLen = strlen($result);
// If a pump was provided, the buffer is still open, and not enough
// data was given, then block until the data is provided.
if ($this->pump && $resultLen < $length) {
$pumpFn = $this->pump;
$result .= $pumpFn($length - $resultLen);
}
return $result;
}
}

View File

@@ -1,138 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\CannotAttachException;
/**
* Provides a buffer stream that can be written to to fill a buffer, and read
* from to remove bytes from the buffer.
*
* 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.
*
* @package GuzzleHttp\Stream
*/
class BufferStream implements StreamInterface
{
private $hwm;
private $buffer = '';
/**
* @param int $hwm High water mark, representing the preferred maximum
* buffer size. If the size of the buffer exceeds the high
* water mark, then calls to write will continue to succeed
* but will return false to inform writers to slow down
* until the buffer has been drained by reading from it.
*/
public function __construct($hwm = 16384)
{
$this->hwm = $hwm;
}
public function __toString()
{
return $this->getContents();
}
public function getContents()
{
$buffer = $this->buffer;
$this->buffer = '';
return $buffer;
}
public function close()
{
$this->buffer = '';
}
public function detach()
{
$this->close();
}
public function attach($stream)
{
throw new CannotAttachException();
}
public function getSize()
{
return strlen($this->buffer);
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return true;
}
public function isSeekable()
{
return false;
}
public function seek($offset, $whence = SEEK_SET)
{
return false;
}
public function eof()
{
return strlen($this->buffer) === 0;
}
public function tell()
{
return false;
}
/**
* Reads data from the buffer.
*/
public function read($length)
{
$currentLength = strlen($this->buffer);
if ($length >= $currentLength) {
// No need to slice the buffer because we don't have enough data.
$result = $this->buffer;
$this->buffer = '';
} else {
// Slice up the result to provide a subset of the buffer.
$result = substr($this->buffer, 0, $length);
$this->buffer = substr($this->buffer, $length);
}
return $result;
}
/**
* Writes data to the buffer.
*/
public function write($string)
{
$this->buffer .= $string;
if (strlen($this->buffer) >= $this->hwm) {
return false;
}
return strlen($string);
}
public function getMetadata($key = null)
{
if ($key == 'hwm') {
return $this->hwm;
}
return $key ? null : [];
}
}

View File

@@ -1,122 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\SeekException;
/**
* Stream decorator that can cache previously read bytes from a sequentially
* read stream.
*/
class CachingStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var StreamInterface Stream being wrapped */
private $remoteStream;
/** @var int Number of bytes to skip reading due to a write on the buffer */
private $skipReadBytes = 0;
/**
* We will treat the buffer object as the body of the stream
*
* @param StreamInterface $stream Stream to cache
* @param StreamInterface $target Optionally specify where data is cached
*/
public function __construct(
StreamInterface $stream,
StreamInterface $target = null
) {
$this->remoteStream = $stream;
$this->stream = $target ?: new Stream(fopen('php://temp', 'r+'));
}
public function getSize()
{
return max($this->stream->getSize(), $this->remoteStream->getSize());
}
/**
* {@inheritdoc}
* @throws SeekException When seeking with SEEK_END or when seeking
* past the total size of the buffer stream
*/
public function seek($offset, $whence = SEEK_SET)
{
if ($whence == SEEK_SET) {
$byte = $offset;
} elseif ($whence == SEEK_CUR) {
$byte = $offset + $this->tell();
} else {
return false;
}
// You cannot skip ahead past where you've read from the remote stream
if ($byte > $this->stream->getSize()) {
throw new SeekException(
$this,
$byte,
sprintf('Cannot seek to byte %d when the buffered stream only'
. ' contains %d bytes', $byte, $this->stream->getSize())
);
}
return $this->stream->seek($byte);
}
public function read($length)
{
// Perform a regular read on any previously read data from the buffer
$data = $this->stream->read($length);
$remaining = $length - strlen($data);
// More data was requested so read from the remote stream
if ($remaining) {
// If data was written to the buffer in a position that would have
// been filled from the remote stream, then we must skip bytes on
// the remote stream to emulate overwriting bytes from that
// position. This mimics the behavior of other PHP stream wrappers.
$remoteData = $this->remoteStream->read(
$remaining + $this->skipReadBytes
);
if ($this->skipReadBytes) {
$len = strlen($remoteData);
$remoteData = substr($remoteData, $this->skipReadBytes);
$this->skipReadBytes = max(0, $this->skipReadBytes - $len);
}
$data .= $remoteData;
$this->stream->write($remoteData);
}
return $data;
}
public function write($string)
{
// When appending to the end of the currently read stream, you'll want
// to skip bytes from being read from the remote stream to emulate
// other stream wrappers. Basically replacing bytes of data of a fixed
// length.
$overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell();
if ($overflow > 0) {
$this->skipReadBytes += $overflow;
}
return $this->stream->write($string);
}
public function eof()
{
return $this->stream->eof() && $this->remoteStream->eof();
}
/**
* Close both the remote stream and buffer stream
*/
public function close()
{
$this->remoteStream->close() && $this->stream->close();
}
}

View File

@@ -1,42 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Stream decorator that begins dropping data once the size of the underlying
* stream becomes too full.
*/
class DroppingStream implements StreamInterface
{
use StreamDecoratorTrait;
private $maxLength;
/**
* @param StreamInterface $stream Underlying stream to decorate.
* @param int $maxLength Maximum size before dropping data.
*/
public function __construct(StreamInterface $stream, $maxLength)
{
$this->stream = $stream;
$this->maxLength = $maxLength;
}
public function write($string)
{
$diff = $this->maxLength - $this->stream->getSize();
// Begin returning false when the underlying stream is too large.
if ($diff <= 0) {
return false;
}
// Write the stream or a subset of the stream if needed.
if (strlen($string) < $diff) {
return $this->stream->write($string);
}
$this->stream->write(substr($string, 0, $diff));
return false;
}
}

View File

@@ -1,4 +0,0 @@
<?php
namespace GuzzleHttp\Stream\Exception;
class CannotAttachException extends \RuntimeException {}

View File

@@ -1,27 +0,0 @@
<?php
namespace GuzzleHttp\Stream\Exception;
use GuzzleHttp\Stream\StreamInterface;
/**
* Exception thrown when a seek fails on a stream.
*/
class SeekException extends \RuntimeException
{
private $stream;
public function __construct(StreamInterface $stream, $pos = 0, $msg = '')
{
$this->stream = $stream;
$msg = $msg ?: 'Could not seek the stream to position ' . $pos;
parent::__construct($msg);
}
/**
* @return StreamInterface
*/
public function getStream()
{
return $this->stream;
}
}

View File

@@ -1,147 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Compose stream implementations based on a hash of functions.
*
* Allows for easy testing and extension of a provided stream without needing
* to create a concrete class for a simple extension point.
*/
class FnStream implements StreamInterface
{
/** @var array */
private $methods;
/** @var array Methods that must be implemented in the given array */
private static $slots = ['__toString', 'close', 'detach', 'attach',
'getSize', 'tell', 'eof', 'isSeekable', 'seek', 'isWritable', 'write',
'isReadable', 'read', 'getContents', 'getMetadata'];
/**
* @param array $methods Hash of method name to a callable.
*/
public function __construct(array $methods)
{
$this->methods = $methods;
// Create the functions on the class
foreach ($methods as $name => $fn) {
$this->{'_fn_' . $name} = $fn;
}
}
/**
* Lazily determine which methods are not implemented.
* @throws \BadMethodCallException
*/
public function __get($name)
{
throw new \BadMethodCallException(str_replace('_fn_', '', $name)
. '() is not implemented in the FnStream');
}
/**
* The close method is called on the underlying stream only if possible.
*/
public function __destruct()
{
if (isset($this->_fn_close)) {
call_user_func($this->_fn_close);
}
}
/**
* Adds custom functionality to an underlying stream by intercepting
* specific method calls.
*
* @param StreamInterface $stream Stream to decorate
* @param array $methods Hash of method name to a closure
*
* @return FnStream
*/
public static function decorate(StreamInterface $stream, array $methods)
{
// If any of the required methods were not provided, then simply
// proxy to the decorated stream.
foreach (array_diff(self::$slots, array_keys($methods)) as $diff) {
$methods[$diff] = [$stream, $diff];
}
return new self($methods);
}
public function __toString()
{
return call_user_func($this->_fn___toString);
}
public function close()
{
return call_user_func($this->_fn_close);
}
public function detach()
{
return call_user_func($this->_fn_detach);
}
public function attach($stream)
{
return call_user_func($this->_fn_attach, $stream);
}
public function getSize()
{
return call_user_func($this->_fn_getSize);
}
public function tell()
{
return call_user_func($this->_fn_tell);
}
public function eof()
{
return call_user_func($this->_fn_eof);
}
public function isSeekable()
{
return call_user_func($this->_fn_isSeekable);
}
public function seek($offset, $whence = SEEK_SET)
{
return call_user_func($this->_fn_seek, $offset, $whence);
}
public function isWritable()
{
return call_user_func($this->_fn_isWritable);
}
public function write($string)
{
return call_user_func($this->_fn_write, $string);
}
public function isReadable()
{
return call_user_func($this->_fn_isReadable);
}
public function read($length)
{
return call_user_func($this->_fn_read, $length);
}
public function getContents()
{
return call_user_func($this->_fn_getContents);
}
public function getMetadata($key = null)
{
return call_user_func($this->_fn_getMetadata, $key);
}
}

View File

@@ -1,117 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Converts Guzzle streams into PHP stream resources.
*/
class GuzzleStreamWrapper
{
/** @var resource */
public $context;
/** @var StreamInterface */
private $stream;
/** @var string r, r+, or w */
private $mode;
/**
* Returns a resource representing the stream.
*
* @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)
{
self::register();
if ($stream->isReadable()) {
$mode = $stream->isWritable() ? 'r+' : 'r';
} elseif ($stream->isWritable()) {
$mode = 'w';
} else {
throw new \InvalidArgumentException('The stream must be readable, '
. 'writable, or both.');
}
return fopen('guzzle://stream', $mode, null, stream_context_create([
'guzzle' => ['stream' => $stream]
]));
}
/**
* Registers the stream wrapper if needed
*/
public static function register()
{
if (!in_array('guzzle', stream_get_wrappers())) {
stream_wrapper_register('guzzle', __CLASS__);
}
}
public function stream_open($path, $mode, $options, &$opened_path)
{
$options = stream_context_get_options($this->context);
if (!isset($options['guzzle']['stream'])) {
return false;
}
$this->mode = $mode;
$this->stream = $options['guzzle']['stream'];
return true;
}
public function stream_read($count)
{
return $this->stream->read($count);
}
public function stream_write($data)
{
return (int) $this->stream->write($data);
}
public function stream_tell()
{
return $this->stream->tell();
}
public function stream_eof()
{
return $this->stream->eof();
}
public function stream_seek($offset, $whence)
{
return $this->stream->seek($offset, $whence);
}
public function stream_stat()
{
static $modeMap = [
'r' => 33060,
'r+' => 33206,
'w' => 33188
];
return [
'dev' => 0,
'ino' => 0,
'mode' => $modeMap[$this->mode],
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 0,
'blocks' => 0
];
}
}

View File

@@ -1,27 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Uses PHP's zlib.inflate filter to inflate deflate or gzipped content.
*
* This stream decorator skips the first 10 bytes of the given stream to remove
* the gzip header, converts the provided stream to a PHP stream resource,
* then appends the zlib.inflate filter. The stream is then converted back
* to a Guzzle stream resource to be used as a Guzzle stream.
*
* @link http://tools.ietf.org/html/rfc1952
* @link http://php.net/manual/en/filters.compression.php
*/
class InflateStream implements StreamInterface
{
use StreamDecoratorTrait;
public function __construct(StreamInterface $stream)
{
// Skip the first 10 bytes
$stream = new LimitStream($stream, -1, 10);
$resource = GuzzleStreamWrapper::getResource($stream);
stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ);
$this->stream = new Stream($resource);
}
}

View File

@@ -1,37 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Lazily reads or writes to a file that is opened only after an IO operation
* take place on the stream.
*/
class LazyOpenStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var string File to open */
private $filename;
/** @var string $mode */
private $mode;
/**
* @param string $filename File to lazily open
* @param string $mode fopen mode to use when opening the stream
*/
public function __construct($filename, $mode)
{
$this->filename = $filename;
$this->mode = $mode;
}
/**
* Creates the underlying stream lazily when required.
*
* @return StreamInterface
*/
protected function createStream()
{
return Stream::factory(Utils::open($this->filename, $this->mode));
}
}

View File

@@ -1,161 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\SeekException;
/**
* Decorator used to return only a subset of a stream
*/
class LimitStream implements StreamInterface
{
use StreamDecoratorTrait;
/** @var int Offset to start reading from */
private $offset;
/** @var int Limit the number of bytes that can be read */
private $limit;
/**
* @param StreamInterface $stream Stream to wrap
* @param int $limit Total number of bytes to allow to be read
* from the stream. Pass -1 for no limit.
* @param int|null $offset Position to seek to before reading (only
* works on seekable streams).
*/
public function __construct(
StreamInterface $stream,
$limit = -1,
$offset = 0
) {
$this->stream = $stream;
$this->setLimit($limit);
$this->setOffset($offset);
}
public function eof()
{
// Always return true if the underlying stream is EOF
if ($this->stream->eof()) {
return true;
}
// No limit and the underlying stream is not at EOF
if ($this->limit == -1) {
return false;
}
$tell = $this->stream->tell();
if ($tell === false) {
return false;
}
return $tell >= $this->offset + $this->limit;
}
/**
* Returns the size of the limited subset of data
* {@inheritdoc}
*/
public function getSize()
{
if (null === ($length = $this->stream->getSize())) {
return null;
} elseif ($this->limit == -1) {
return $length - $this->offset;
} else {
return min($this->limit, $length - $this->offset);
}
}
/**
* Allow for a bounded seek on the read limited stream
* {@inheritdoc}
*/
public function seek($offset, $whence = SEEK_SET)
{
if ($whence !== SEEK_SET || $offset < 0) {
return false;
}
$offset += $this->offset;
if ($this->limit !== -1) {
if ($offset > $this->offset + $this->limit) {
$offset = $this->offset + $this->limit;
}
}
return $this->stream->seek($offset);
}
/**
* Give a relative tell()
* {@inheritdoc}
*/
public function tell()
{
return $this->stream->tell() - $this->offset;
}
/**
* Set the offset to start limiting from
*
* @param int $offset Offset to seek to and begin byte limiting from
*
* @return self
* @throws SeekException
*/
public function setOffset($offset)
{
$current = $this->stream->tell();
if ($current !== $offset) {
// If the stream cannot seek to the offset position, then read to it
if (!$this->stream->seek($offset)) {
if ($current > $offset) {
throw new SeekException($this, $offset);
} else {
$this->stream->read($offset - $current);
}
}
}
$this->offset = $offset;
return $this;
}
/**
* Set the limit of bytes that the decorator allows to be read from the
* stream.
*
* @param int $limit Number of bytes to allow to be read from the stream.
* Use -1 for no limit.
* @return self
*/
public function setLimit($limit)
{
$this->limit = $limit;
return $this;
}
public function read($length)
{
if ($this->limit == -1) {
return $this->stream->read($length);
}
// Check if the current position is less than the total allowed
// bytes + original offset
$remaining = ($this->offset + $this->limit) - $this->stream->tell();
if ($remaining > 0) {
// Only return the amount of requested data, ensuring that the byte
// limit is not exceeded
return $this->stream->read(min($remaining, $length));
} else {
return false;
}
}
}

View File

@@ -1,11 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* This interface is deprecated and should no longer be used. Just use
* StreamInterface now that the getMetadata method has been added to
* StreamInterface.
*
* @deprecated
*/
interface MetadataStreamInterface extends StreamInterface {}

View File

@@ -1,25 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Stream decorator that prevents a stream from being seeked
*/
class NoSeekStream implements StreamInterface
{
use StreamDecoratorTrait;
public function seek($offset, $whence = SEEK_SET)
{
return false;
}
public function isSeekable()
{
return false;
}
public function attach($stream)
{
$this->stream->attach($stream);
}
}

View File

@@ -1,78 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\CannotAttachException;
/**
* Does not store any data written to it.
*/
class NullStream implements StreamInterface
{
public function __toString()
{
return '';
}
public function getContents()
{
return '';
}
public function close() {}
public function detach() {}
public function attach($stream)
{
throw new CannotAttachException();
}
public function getSize()
{
return 0;
}
public function isReadable()
{
return true;
}
public function isWritable()
{
return true;
}
public function isSeekable()
{
return true;
}
public function eof()
{
return true;
}
public function tell()
{
return 0;
}
public function seek($offset, $whence = SEEK_SET)
{
return false;
}
public function read($length)
{
return false;
}
public function write($string)
{
return strlen($string);
}
public function getMetadata($key = null)
{
return $key ? null : [];
}
}

View File

@@ -1,161 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\CannotAttachException;
/**
* Provides a read only stream that pumps data from a PHP callable.
*
* When invoking the provided callable, the PumpStream will pass the amount of
* data requested to read to the callable. The callable can choose to ignore
* this value and return fewer or more bytes than requested. Any extra data
* 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.
*/
class PumpStream implements StreamInterface
{
/** @var callable */
private $source;
/** @var int */
private $size;
/** @var int */
private $tellPos = 0;
/** @var array */
private $metadata;
/** @var BufferStream */
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.
*/
public function __construct(callable $source, array $options = [])
{
$this->source = $source;
$this->size = isset($options['size']) ? $options['size'] : null;
$this->metadata = isset($options['metadata']) ? $options['metadata'] : [];
$this->buffer = new BufferStream();
}
public function __toString()
{
return Utils::copyToString($this);
}
public function close()
{
$this->detach();
}
public function detach()
{
$this->tellPos = false;
$this->source = null;
}
public function attach($stream)
{
throw new CannotAttachException();
}
public function getSize()
{
return $this->size;
}
public function tell()
{
return $this->tellPos;
}
public function eof()
{
return !$this->source;
}
public function isSeekable()
{
return false;
}
public function seek($offset, $whence = SEEK_SET)
{
return false;
}
public function isWritable()
{
return false;
}
public function write($string)
{
return false;
}
public function isReadable()
{
return true;
}
public function read($length)
{
$data = $this->buffer->read($length);
$readLen = strlen($data);
$this->tellPos += $readLen;
$remaining = $length - $readLen;
if ($remaining) {
$this->pump($remaining);
$data .= $this->buffer->read($remaining);
$this->tellPos += strlen($data) - $readLen;
}
return $data;
}
public function getContents()
{
$result = '';
while (!$this->eof()) {
$result .= $this->read(1000000);
}
return $result;
}
public function getMetadata($key = null)
{
if (!$key) {
return $this->metadata;
}
return isset($this->metadata[$key]) ? $this->metadata[$key] : null;
}
private function pump($length)
{
if ($this->source) {
do {
$data = call_user_func($this->source, $length);
if ($data === false || $data === null) {
$this->source = null;
return;
}
$this->buffer->write($data);
$length -= strlen($data);
} while ($length > 0);
}
}
}

View File

@@ -1,261 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* PHP stream implementation
*/
class Stream implements StreamInterface
{
private $stream;
private $size;
private $seekable;
private $readable;
private $writable;
private $uri;
private $customMetadata;
/** @var array Hash of readable and writable stream types */
private static $readWriteHash = [
'read' => [
'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true,
'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true,
'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true,
'x+t' => true, 'c+t' => true, 'a+' => true
],
'write' => [
'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true,
'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true,
'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true,
'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true
]
];
/**
* Create a new stream based on the input type.
*
* This factory accepts the same associative array of options as described
* in the constructor.
*
* @param resource|string|StreamInterface $resource Entity body data
* @param array $options Additional options
*
* @return Stream
* @throws \InvalidArgumentException if the $resource arg is not valid.
*/
public static function factory($resource = '', array $options = [])
{
$type = gettype($resource);
if ($type == 'string') {
$stream = fopen('php://temp', 'r+');
if ($resource !== '') {
fwrite($stream, $resource);
fseek($stream, 0);
}
return new self($stream, $options);
}
if ($type == 'resource') {
return new self($resource, $options);
}
if ($resource instanceof StreamInterface) {
return $resource;
}
if ($type == 'object' && method_exists($resource, '__toString')) {
return self::factory((string) $resource, $options);
}
if (is_callable($resource)) {
return new PumpStream($resource, $options);
}
if ($resource instanceof \Iterator) {
return new PumpStream(function () use ($resource) {
if (!$resource->valid()) {
return false;
}
$result = $resource->current();
$resource->next();
return $result;
}, $options);
}
throw new \InvalidArgumentException('Invalid resource type: ' . $type);
}
/**
* This constructor accepts an associative array of options.
*
* - size: (int) If a read stream would otherwise have an indeterminate
* size, but the size is known due to foreknownledge, then you can
* provide that size, in bytes.
* - metadata: (array) Any additional metadata to return when the metadata
* of the stream is accessed.
*
* @param resource $stream Stream resource to wrap.
* @param array $options Associative array of options.
*
* @throws \InvalidArgumentException if the stream is not a stream resource
*/
public function __construct($stream, $options = [])
{
if (!is_resource($stream)) {
throw new \InvalidArgumentException('Stream must be a resource');
}
if (isset($options['size'])) {
$this->size = $options['size'];
}
$this->customMetadata = isset($options['metadata'])
? $options['metadata']
: [];
$this->attach($stream);
}
/**
* Closes the stream when the destructed
*/
public function __destruct()
{
$this->close();
}
public function __toString()
{
if (!$this->stream) {
return '';
}
$this->seek(0);
return (string) stream_get_contents($this->stream);
}
public function getContents()
{
return $this->stream ? stream_get_contents($this->stream) : '';
}
public function close()
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
$this->detach();
}
public function detach()
{
$result = $this->stream;
$this->stream = $this->size = $this->uri = null;
$this->readable = $this->writable = $this->seekable = false;
return $result;
}
public function attach($stream)
{
$this->stream = $stream;
$meta = stream_get_meta_data($this->stream);
$this->seekable = $meta['seekable'];
$this->readable = isset(self::$readWriteHash['read'][$meta['mode']]);
$this->writable = isset(self::$readWriteHash['write'][$meta['mode']]);
$this->uri = $this->getMetadata('uri');
}
public function getSize()
{
if ($this->size !== null) {
return $this->size;
}
if (!$this->stream) {
return null;
}
// Clear the stat cache if the stream has a URI
if ($this->uri) {
clearstatcache(true, $this->uri);
}
$stats = fstat($this->stream);
if (isset($stats['size'])) {
$this->size = $stats['size'];
return $this->size;
}
return null;
}
public function isReadable()
{
return $this->readable;
}
public function isWritable()
{
return $this->writable;
}
public function isSeekable()
{
return $this->seekable;
}
public function eof()
{
return !$this->stream || feof($this->stream);
}
public function tell()
{
return $this->stream ? ftell($this->stream) : false;
}
public function setSize($size)
{
$this->size = $size;
return $this;
}
public function seek($offset, $whence = SEEK_SET)
{
return $this->seekable
? fseek($this->stream, $offset, $whence) === 0
: false;
}
public function read($length)
{
return $this->readable ? fread($this->stream, $length) : false;
}
public function write($string)
{
// We can't know the size after writing anything
$this->size = null;
return $this->writable ? fwrite($this->stream, $string) : false;
}
public function getMetadata($key = null)
{
if (!$this->stream) {
return $key ? null : [];
} elseif (!$key) {
return $this->customMetadata + stream_get_meta_data($this->stream);
} elseif (isset($this->customMetadata[$key])) {
return $this->customMetadata[$key];
}
$meta = stream_get_meta_data($this->stream);
return isset($meta[$key]) ? $meta[$key] : null;
}
}

View File

@@ -1,143 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\CannotAttachException;
/**
* Stream decorator trait
* @property StreamInterface stream
*/
trait StreamDecoratorTrait
{
/**
* @param StreamInterface $stream Stream to decorate
*/
public function __construct(StreamInterface $stream)
{
$this->stream = $stream;
}
/**
* Magic method used to create a new stream if streams are not added in
* the constructor of a decorator (e.g., LazyOpenStream).
*/
public function __get($name)
{
if ($name == 'stream') {
$this->stream = $this->createStream();
return $this->stream;
}
throw new \UnexpectedValueException("$name not found on class");
}
public function __toString()
{
try {
$this->seek(0);
return $this->getContents();
} catch (\Exception $e) {
// Really, PHP? https://bugs.php.net/bug.php?id=53648
trigger_error('StreamDecorator::__toString exception: '
. (string) $e, E_USER_ERROR);
return '';
}
}
public function getContents()
{
return Utils::copyToString($this);
}
/**
* Allow decorators to implement custom methods
*
* @param string $method Missing method name
* @param array $args Method arguments
*
* @return mixed
*/
public function __call($method, array $args)
{
$result = call_user_func_array(array($this->stream, $method), $args);
// Always return the wrapped object if the result is a return $this
return $result === $this->stream ? $this : $result;
}
public function close()
{
$this->stream->close();
}
public function getMetadata($key = null)
{
return $this->stream->getMetadata($key);
}
public function detach()
{
return $this->stream->detach();
}
public function attach($stream)
{
throw new CannotAttachException();
}
public function getSize()
{
return $this->stream->getSize();
}
public function eof()
{
return $this->stream->eof();
}
public function tell()
{
return $this->stream->tell();
}
public function isReadable()
{
return $this->stream->isReadable();
}
public function isWritable()
{
return $this->stream->isWritable();
}
public function isSeekable()
{
return $this->stream->isSeekable();
}
public function seek($offset, $whence = SEEK_SET)
{
return $this->stream->seek($offset, $whence);
}
public function read($length)
{
return $this->stream->read($length);
}
public function write($string)
{
return $this->stream->write($string);
}
/**
* Implement in subclasses to dynamically create streams when requested.
*
* @return StreamInterface
* @throws \BadMethodCallException
*/
protected function createStream()
{
throw new \BadMethodCallException('createStream() not implemented in '
. get_class($this));
}
}

View File

@@ -1,159 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
/**
* Describes a stream instance.
*/
interface StreamInterface
{
/**
* Attempts to seek to the beginning of the stream and reads all data into
* a string until the end of the stream is reached.
*
* Warning: This could attempt to load a large amount of data into memory.
*
* @return string
*/
public function __toString();
/**
* Closes the stream and any underlying resources.
*/
public function close();
/**
* Separates any underlying resources from the stream.
*
* After the underlying resource has been detached, the stream object is in
* an unusable state. If you wish to use a Stream object as a PHP stream
* but keep the Stream object in a consistent state, use
* {@see GuzzleHttp\Stream\GuzzleStreamWrapper::getResource}.
*
* @return resource|null Returns the underlying PHP stream resource or null
* if the Stream object did not utilize an underlying
* stream resource.
*/
public function detach();
/**
* Replaces the underlying stream resource with the provided stream.
*
* Use this method to replace the underlying stream with another; as an
* example, in server-side code, if you decide to return a file, you
* would replace the original content-oriented stream with the file
* stream.
*
* Any internal state such as caching of cursor position should be reset
* when attach() is called, as the stream has changed.
*
* @param resource $stream
*
* @return void
*/
public function attach($stream);
/**
* Get the size of the stream if known
*
* @return int|null Returns the size in bytes if known, or null if unknown
*/
public function getSize();
/**
* Returns the current position of the file read/write pointer
*
* @return int|bool Returns the position of the file pointer or false on error
*/
public function tell();
/**
* Returns true if the stream is at the end of the stream.
*
* @return bool
*/
public function eof();
/**
* Returns whether or not the stream is seekable
*
* @return bool
*/
public function isSeekable();
/**
* Seek to a position in the stream
*
* @param int $offset Stream offset
* @param int $whence Specifies how the cursor position will be calculated
* based on the seek offset. Valid values are identical
* to the built-in PHP $whence values for `fseek()`.
* SEEK_SET: Set position equal to offset bytes
* SEEK_CUR: Set position to current location plus offset
* SEEK_END: Set position to end-of-stream plus offset
*
* @return bool Returns true on success or false on failure
* @link http://www.php.net/manual/en/function.fseek.php
*/
public function seek($offset, $whence = SEEK_SET);
/**
* Returns whether or not the stream is writable
*
* @return bool
*/
public function isWritable();
/**
* Write data to the stream
*
* @param string $string The string that is to be written.
*
* @return int|bool Returns the number of bytes written to the stream on
* success returns false on failure (e.g., broken pipe,
* writer needs to slow down, buffer is full, etc.)
*/
public function write($string);
/**
* Returns whether or not the stream is readable
*
* @return bool
*/
public function isReadable();
/**
* Read data from the stream
*
* @param int $length Read up to $length bytes from the object and return
* them. Fewer than $length bytes may be returned if
* underlying stream call returns fewer bytes.
*
* @return string Returns the data read from the stream.
*/
public function read($length);
/**
* Returns the remaining contents of the stream as a string.
*
* Note: this could potentially load a large amount of data into memory.
*
* @return string
*/
public function getContents();
/**
* Get stream metadata as an associative array or retrieve a specific key.
*
* The keys returned are identical to the keys returned from PHP's
* stream_get_meta_data() function.
*
* @param string $key Specific metadata to retrieve.
*
* @return array|mixed|null Returns an associative array if no key is
* no key is provided. Returns a specific key
* value if a key is provided and the value is
* found, or null if the key is not found.
* @see http://php.net/manual/en/function.stream-get-meta-data.php
*/
public function getMetadata($key = null);
}

View File

@@ -1,196 +0,0 @@
<?php
namespace GuzzleHttp\Stream;
use GuzzleHttp\Stream\Exception\SeekException;
/**
* Static utility class because PHP's autoloaders don't support the concept
* of namespaced function autoloading.
*/
class Utils
{
/**
* 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 open($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;
}
/**
* 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
*/
public static function copyToString(StreamInterface $stream, $maxLen = -1)
{
$buffer = '';
if ($maxLen === -1) {
while (!$stream->eof()) {
$buf = $stream->read(1048576);
if ($buf === false) {
break;
}
$buffer .= $buf;
}
return $buffer;
}
$len = 0;
while (!$stream->eof() && $len < $maxLen) {
$buf = $stream->read($maxLen - $len);
if ($buf === false) {
break;
}
$buffer .= $buf;
$len = strlen($buffer);
}
return $buffer;
}
/**
* 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.
*/
public static function copyToStream(
StreamInterface $source,
StreamInterface $dest,
$maxLen = -1
) {
if ($maxLen === -1) {
while (!$source->eof()) {
if (!$dest->write($source->read(1048576))) {
break;
}
}
return;
}
$bytes = 0;
while (!$source->eof()) {
$buf = $source->read($maxLen - $bytes);
if (!($len = strlen($buf))) {
break;
}
$bytes += $len;
$dest->write($buf);
if ($bytes == $maxLen) {
break;
}
}
}
/**
* Calculate a hash of a Stream
*
* @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 SeekException
*/
public static function hash(
StreamInterface $stream,
$algo,
$rawOutput = false
) {
$pos = $stream->tell();
if ($pos > 0 && !$stream->seek(0)) {
throw new SeekException($stream);
}
$ctx = hash_init($algo);
while (!$stream->eof()) {
hash_update($ctx, $stream->read(1048576));
}
$out = hash_final($ctx, (bool) $rawOutput);
$stream->seek($pos);
return $out;
}
/**
* 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
*
* @return string|bool
*/
public static function readline(StreamInterface $stream, $maxLength = null)
{
$buffer = '';
$size = 0;
while (!$stream->eof()) {
if (false === ($byte = $stream->read(1))) {
return $buffer;
}
$buffer .= $byte;
// Break when a new line is found or the max length - 1 is reached
if ($byte == PHP_EOL || ++$size == $maxLength - 1) {
break;
}
}
return $buffer;
}
/**
* Alias of GuzzleHttp\Stream\Stream::factory.
*
* @param mixed $resource Resource to create
* @param array $options Associative array of stream options defined in
* {@see \GuzzleHttp\Stream\Stream::__construct}
*
* @return StreamInterface
*
* @see GuzzleHttp\Stream\Stream::factory
* @see GuzzleHttp\Stream\Stream::__construct
*/
public static function create($resource, array $options = [])
{
return Stream::factory($resource, $options);
}
}

Some files were not shown because too many files have changed in this diff Show More