1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-25 10:33:18 +01:00

Making some classes more readable

This commit is contained in:
Michael Dowling 2014-02-17 21:18:26 -08:00
parent 65333062c9
commit 0a5503b5bd
13 changed files with 112 additions and 54 deletions

View File

@ -3,13 +3,14 @@
namespace GuzzleHttp\Stream;
/**
* Stream decorator that can cache previously read bytes from a sequentially read stream
* Stream decorator that can cache previously read bytes from a sequentially
* read stream.
*/
class CachingStream implements StreamInterface, MetadataStreamInterface
{
use StreamDecoratorTrait;
/** @var StreamInterface Remote stream used to actually pull data onto the buffer */
/** @var StreamInterface Stream being wrapped */
private $remoteStream;
/** @var int The number of bytes to skip reading due to a write on the temporary buffer */
@ -21,8 +22,10 @@ class CachingStream implements StreamInterface, MetadataStreamInterface
* @param StreamInterface $stream Stream to cache
* @param StreamInterface $target Optionally specify where data is cached
*/
public function __construct(StreamInterface $stream, StreamInterface $target = null)
{
public function __construct(
StreamInterface $stream,
StreamInterface $target = null
) {
$this->remoteStream = $stream;
$this->stream = $target ?: new Stream(fopen('php://temp', 'r+'));
}
@ -34,7 +37,8 @@ class CachingStream implements StreamInterface, MetadataStreamInterface
/**
* {@inheritdoc}
* @throws \RuntimeException When seeking with SEEK_END or when seeking past the total size of the buffer stream
* @throws \RuntimeException When seeking with SEEK_END or when seeking
* past the total size of the buffer stream
*/
public function seek($offset, $whence = SEEK_SET)
{
@ -64,9 +68,10 @@ class CachingStream implements StreamInterface, MetadataStreamInterface
// 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.
// 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) {
@ -84,8 +89,10 @@ class CachingStream implements StreamInterface, MetadataStreamInterface
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.
// 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;

View File

@ -109,7 +109,8 @@ class LimitStream implements StreamInterface, MetadataStreamInterface
}
/**
* Set the limit of bytes that the decorator allows to be read from the stream
* 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.
*
@ -128,10 +129,12 @@ class LimitStream implements StreamInterface, MetadataStreamInterface
return $this->stream->read($length);
}
// Check if the current position is less than the total allowed bytes + original offset
// 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
// 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

@ -17,7 +17,7 @@ class Cookie implements SubscriberInterface
protected $cookieJar;
/**
* @param CookieJarInterface $cookieJar Cookie jar used to hold cookies. Creates an ArrayCookieJar by default.
* @param CookieJarInterface $cookieJar Cookie jar used to hold cookies
*/
public function __construct(CookieJarInterface $cookieJar = null)
{
@ -58,13 +58,20 @@ class Cookie implements SubscriberInterface
public function onRequestSent(CompleteEvent $event)
{
$this->cookieJar->addCookiesFromResponse($event->getRequest(), $event->getResponse());
$this->cookieJar->addCookiesFromResponse(
$event->getRequest(),
$event->getResponse()
);
}
private function getCookieValue($value)
{
// Quote the value if it is not already and contains problematic characters
if (substr($value, 0, 1) !== '"' && substr($value, -1, 1) !== '"' && strpbrk($value, ';,')) {
// Quote the cookie value if it is not already quoted and it contains
// problematic characters.
if (substr($value, 0, 1) !== '"' &&
substr($value, -1, 1) !== '"' &&
strpbrk($value, ';,')
) {
$value = '"' . $value . '"';
}

View File

@ -11,30 +11,34 @@ use Psr\Log\LogLevel;
/**
* Plugin class that will add request and response logging to an HTTP request.
*
* The log plugin uses a message formatter that allows custom messages via template variable substitution.
* The log plugin uses a message formatter that allows custom messages via
* template variable substitution.
*
* @see MessageLogger for a list of available log template variable substitutions
* @see MessageLogger for a list of available template variable substitutions
*/
class LogSubscriber implements SubscriberInterface
{
/** @var LoggerInterface */
private $logger;
/** @var MessageFormatter Formatter used to format messages before logging */
/** @var MessageFormatter Formatter used to format log messages */
private $formatter;
/**
* @param LoggerInterface $logger Logger used to log messages
* @param string|MessageFormatter $formatter Formatter used to format log messages or the formatter template
* @param LoggerInterface $logger Logger used to log messages
* @param string|MessageFormatter $formatter Formatter used to format log messages or the formatter template
*/
public function __construct(LoggerInterface $logger, $formatter = null)
{
$this->logger = $logger;
$this->formatter = $formatter instanceof MessageFormatter ? $formatter : new MessageFormatter($formatter);
$this->formatter = $formatter instanceof MessageFormatter
? $formatter
: new MessageFormatter($formatter);
}
/**
* Get a log plugin that outputs full request, response, and any error messages
* Get a log plugin that outputs full request, response, and any error
* messages.
*
* @param resource $stream Stream to write to when logging. Defaults to STDOUT
*
@ -42,7 +46,10 @@ class LogSubscriber implements SubscriberInterface
*/
public static function getDebugPlugin($stream = null)
{
return new self(new SimpleLogger($stream), "# Request:\n{request}\n# Response:\n{response}\n{error}");
return new self(
new SimpleLogger($stream),
"# Request:\n{request}\n# Response:\n{response}\n{error}"
);
}
public static function getSubscribedEvents()
@ -59,9 +66,14 @@ class LogSubscriber implements SubscriberInterface
public function onRequestAfterSend(CompleteEvent $event)
{
$this->logger->log(
substr($event->getResponse()->getStatusCode(), 0, 1) == '2' ? LogLevel::INFO : LogLevel::WARNING,
substr($event->getResponse()->getStatusCode(), 0, 1) == '2'
? LogLevel::INFO
: LogLevel::WARNING,
$this->formatter->format($event->getRequest(), $event->getResponse()),
['request' => $event->getRequest(), 'response' => $event->getResponse()]
[
'request' => $event->getRequest(),
'response' => $event->getResponse()
]
);
}
@ -74,7 +86,11 @@ class LogSubscriber implements SubscriberInterface
$this->logger->log(
LogLevel::CRITICAL,
$this->formatter->format($event->getRequest(), $event->getResponse(), $ex),
['request' => $event->getRequest(), 'response' => $event->getResponse(), 'exception' => $ex]
[
'request' => $event->getRequest(),
'response' => $event->getResponse(),
'exception' => $ex
]
);
}
}

View File

@ -6,7 +6,8 @@ use GuzzleHttp\Message\RequestInterface;
use GuzzleHttp\Message\ResponseInterface;
/**
* Formats messages using variable substitutions for requests, responses, and other transactional data.
* Formats messages using variable substitutions for requests, responses, and
* other transactional data.
*
* The following variable substitutions are supported:
*

View File

@ -8,7 +8,8 @@ use GuzzleHttp\Message\ResponseInterface;
use GuzzleHttp\Stream\StreamInterface;
/**
* Verifies the message integrity of a response after all of the data has been received
* Verifies the message integrity of a response after all of the data has been
* received.
*/
class FullResponseIntegritySubscriber implements SubscriberInterface
{

View File

@ -6,7 +6,8 @@ use GuzzleHttp\Event\SubscriberInterface;
use GuzzleHttp\Event\BeforeEvent;
/**
* Verifies the message integrity of a response after all of the data has been received
* Verifies the message integrity of a response after all of the data has been
* received.
*/
class MessageIntegritySubscriber implements SubscriberInterface
{

View File

@ -14,7 +14,7 @@ class PhpHash implements HashInterface
/**
* @param string $algo Hashing algorithm. One of PHP's hash_algos() return values (e.g. md5)
* @param array $options Associative array of hashing options:
* - hmac_key: Shared secret key used with HMAC algorithms
* - hmac_key: Shared secret key used with HMAC algorithms
*/
public function __construct($algo, array $options = [])
{

View File

@ -6,7 +6,8 @@ use GuzzleHttp\Stream\StreamDecoratorTrait;
use GuzzleHttp\Stream\StreamInterface;
/**
* Stream decorator that validates a rolling hash of the entity body as it is read
* Stream decorator that validates a rolling hash of the entity body as it is
* read.
* @todo Allow the file pointer to skip around and read bytes randomly
*/
class ReadIntegrityStream implements StreamInterface

View File

@ -7,7 +7,8 @@ use GuzzleHttp\Event\HeadersEvent;
use GuzzleHttp\Message\ResponseInterface;
/**
* Verifies the message integrity of a response only after the entire response body has been read
* Verifies the message integrity of a response only after the entire response
* body has been read.
*/
class StreamingResponseIntegritySubscriber implements SubscriberInterface
{

View File

@ -11,14 +11,15 @@ use GuzzleHttp\Message\MessageFactory;
use GuzzleHttp\Message\ResponseInterface;
/**
* Queues mock responses or exceptions and delivers mock responses or exceptions in a fifo order.
* 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 a mock response is served */
/** @var bool Whether or not to consume an entity body when mocking */
private $readBodies;
/** @var MessageFactory */
@ -77,7 +78,7 @@ class Mock implements SubscriberInterface, \Countable
/**
* Add a response to the end of the queue
*
* @param string|ResponseInterface $response Response object or path to response file
* @param string|ResponseInterface $response Response or path to response file
*
* @return self
* @throws \InvalidArgumentException if a string or Response is not passed

View File

@ -31,7 +31,8 @@ class PrepareRequestBody implements SubscriberInterface
{
$request = $event->getRequest();
// Set the appropriate Content-Type for a request if one is not set and there are form fields
// Set the appropriate Content-Type for a request if one is not set and
// there are form fields
if (!($body = $request->getBody())) {
return;
}
@ -43,7 +44,8 @@ class PrepareRequestBody implements SubscriberInterface
$this->addExpectHeader($request, $body);
// Never send a Transfer-Encoding: chunked and Content-Length header in the same request
// Never send a Transfer-Encoding: chunked and Content-Length header in
// the same request
if ($request->getHeader('Transfer-Encoding') == 'chunked') {
$request->removeHeader('Content-Length');
}

View File

@ -10,7 +10,8 @@ use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* Plugin to automatically retry failed HTTP requests using filters a delay strategy.
* Plugin to automatically retry failed HTTP requests using filters a delay
* strategy.
*/
class RetrySubscriber implements SubscriberInterface
{
@ -59,10 +60,11 @@ class RetrySubscriber implements SubscriberInterface
}
/**
* Retrieve a basic truncated exponential backoff plugin that will retry HTTP errors and cURL errors
* Retrieve a basic truncated exponential backoff plugin that will retry
* HTTP errors and cURL errors
*
* @param array $config Exponential backoff configuration
* - max_retries: Maximum number of retries (overiddes the default of 5)
* - max_retries: Maximum number of retries (overriddes the default of 5)
* - http_codes: HTTP response codes to retry (overrides the default)
* - curl_codes: cURL error codes to retry (overrides the default)
* - logger: Pass a logger instance to log each retry or pass true for STDOUT
@ -78,7 +80,9 @@ class RetrySubscriber implements SubscriberInterface
if (!extension_loaded('curl')) {
$filter = self::createStatusFilter($httpCodes);
} else {
$curlCodes = isset($config['curl_codes']) ? $config['curl_codes'] : null;
$curlCodes = isset($config['curl_codes'])
? $config['curl_codes']
: null;
$filter = self::createChainFilter([
self::createStatusFilter($httpCodes),
self::createCurlFilter($curlCodes)
@ -98,7 +102,12 @@ class RetrySubscriber implements SubscriberInterface
$maxRetries = isset($config['max_retries']) ? $config['max_retries'] : 5;
return new self($filter, $delay, $maxRetries, isset($config['sleep_fn']) ? $config['sleep_fn'] : null);
return new self(
$filter,
$delay,
$maxRetries,
isset($config['sleep_fn']) ? $config['sleep_fn'] : null
);
}
public function onRequestSent(AbstractTransferStatsEvent $event)
@ -126,17 +135,20 @@ class RetrySubscriber implements SubscriberInterface
*
* @return int
*/
public static function exponentialDelay($retries, AbstractTransferStatsEvent $event)
{
public static function exponentialDelay(
$retries,
AbstractTransferStatsEvent $event
) {
return (int) pow(2, $retries - 1);
}
/**
* Creates a delay function that logs each retry before proxying to a wrapped delay function.
* Creates a delay function that logs each retry before proxying to a
* wrapped delay function.
*
* @param callable $delayFn Delay function to proxy to
* @param LoggerInterface $logger Logger used to log messages
* @param string|MessageFormatter $formatter Format string or Message formatter used to format messages
* @param string|MessageFormatter $formatter Formatter to format messages
*
* @return callable
*/
@ -166,7 +178,8 @@ class RetrySubscriber implements SubscriberInterface
/**
* Creates a retry filter based on HTTP status codes
*
* @param array $failureStatuses Pass an array of status codes to override the default of [500, 503]
* @param array $failureStatuses Pass an array of status codes to override
* the default of [500, 503]
*
* @return callable
*/
@ -186,7 +199,8 @@ class RetrySubscriber implements SubscriberInterface
/**
* Creates a retry filter based on cURL error codes.
*
* @param array $errorCodes Pass an array of curl error codes to override the default list of error codes.
* @param array $errorCodes Pass an array of curl error codes to override
* the default list of error codes.
*
* @return callable
*/
@ -206,12 +220,15 @@ class RetrySubscriber implements SubscriberInterface
}
/**
* Creates a chain of callables that triggers one after the other until a callable returns true.
* Creates a chain of callables that triggers one after the other until a
* callable returns true.
*
* @param array $filters Array of callables that accept the number of retries and an after send event and return
* true to retry the transaction or false to not retry.
* @param array $filters Array of callables that accept the number of
* retries and an after send event and return true to retry the
* transaction or false to not retry.
*
* @return callable Returns a filter that can be used to determine if a transaction should be retried
* @return callable Returns a filter that can be used to determine if a
* transaction should be retried
*/
public static function createChainFilter(array $filters)
{