package.xml 0000644 233176441610067500000102424 12155472567 014627 0 ustar dowling ANT\Domain Users
Guzzleguzzlephp.org/pearObject-oriented PHP HTTP Client for PHP 5.3+Guzzle is a PHP HTTP client library and framework for building RESTful web service clientsMichael Dowlingmtdowlingmtdowling@gmail.comyes2013-06-103.7.03.0.0stablestableMIT
-
5.3.21.4.6EventDispatcherpear.symfony.com2.1.0curl3.7.03.0.0stablestable2013-06-10MIT
-
Guzzle-3.7.0/Guzzle/CHANGELOG.md 0000644 233176441610067500000120716 12155472567 017532 0 ustar dowling ANT\Domain Users CHANGELOG
=========
3.7.0 (2013-06-10)
------------------
* See UPGRADING.md for more information on how to upgrade.
* Requests now support the ability to specify an array of $options when creating a request to more easily modify a
request. You can pass a 'request.options' configuration setting to a client to apply default request options to
every request created by a client (e.g. default query string variables, headers, curl options, etc).
* Added a static facade class that allows you to use Guzzle with static methods and mount the class to `\Guzzle`.
See `Guzzle\Http\StaticClient::mount`.
* Added `command.request_options` to `Guzzle\Service\Command\AbstractCommand` to pass request options to requests
created by a command (e.g. custom headers, query string variables, timeout settings, etc).
* Stream size in `Guzzle\Stream\PhpStreamRequestFactory` will now be set if Content-Length is returned in the
headers of a response
* Added `Guzzle\Common\Collection::setPath($path, $value)` to set a value into an array using a nested key
(e.g. `$collection->setPath('foo/baz/bar', 'test'); echo $collection['foo']['bar']['bar'];`)
* ServiceBuilders now support storing and retrieving arbitrary data
* CachePlugin can now purge all resources for a given URI
* CachePlugin can automatically purge matching cached items when a non-idempotent request is sent to a resource
* CachePlugin now uses the Vary header to determine if a resource is a cache hit
* `Guzzle\Http\Message\Response` now implements `\Serializable`
* Added `Guzzle\Cache\CacheAdapterFactory::fromCache()` to more easily create cache adapters
* `Guzzle\Service\ClientInterface::execute()` now accepts an array, single command, or Traversable
* Fixed a bug in `Guzzle\Http\Message\Header\Link::addLink()`
* Better handling of calculating the size of a stream in `Guzzle\Stream\Stream` using fstat() and caching the size
* `Guzzle\Common\Exception\ExceptionCollection` now creates a more readable exception message
* Fixing BC break: Added back the MonologLogAdapter implementation rather than extending from PsrLog so that older
Symfony users can still use the old version of Monolog.
* Fixing BC break: Added the implementation back in for `Guzzle\Http\Message\AbstractMessage::getTokenizedHeader()`.
Now triggering an E_USER_DEPRECATED warning when used. Use `$message->getHeader()->parseParams()`.
* Several performance improvements to `Guzzle\Common\Collection`
* Added an `$options` argument to the end of the following methods of `Guzzle\Http\ClientInterface`:
createRequest, head, delete, put, patch, post, options, prepareRequest
* Added an `$options` argument to the end of `Guzzle\Http\Message\Request\RequestFactoryInterface::createRequest()`
* Added an `applyOptions()` method to `Guzzle\Http\Message\Request\RequestFactoryInterface`
* Changed `Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $body = null)` to
`Guzzle\Http\ClientInterface::get($uri = null, $headers = null, $options = array())`. You can still pass in a
resource, string, or EntityBody into the $options parameter to specify the download location of the response.
* Changed `Guzzle\Common\Collection::__construct($data)` to no longer accepts a null value for `$data` but a
default `array()`
* Added `Guzzle\Stream\StreamInterface::isRepeatable`
* Removed `Guzzle\Http\ClientInterface::setDefaultHeaders(). Use
$client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`. or
$client->getConfig()->setPath('request.options/headers', array('header_name' => 'value'))`.
* Removed `Guzzle\Http\ClientInterface::getDefaultHeaders(). Use $client->getConfig()->getPath('request.options/headers')`.
* Removed `Guzzle\Http\ClientInterface::expandTemplate()`
* Removed `Guzzle\Http\ClientInterface::setRequestFactory()`
* Removed `Guzzle\Http\ClientInterface::getCurlMulti()`
* Removed `Guzzle\Http\Message\RequestInterface::canCache`
* Removed `Guzzle\Http\Message\RequestInterface::setIsRedirect`
* Removed `Guzzle\Http\Message\RequestInterface::isRedirect`
* Made `Guzzle\Http\Client::expandTemplate` and `getUriTemplate` protected methods.
* You can now enable E_USER_DEPRECATED warnings to see if you are using a deprecated method by setting
`Guzzle\Common\Version::$emitWarnings` to true.
* Marked `Guzzle\Http\Message\Request::isResponseBodyRepeatable()` as deprecated. Use
`$request->getResponseBody()->isRepeatable()` instead.
* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use
`Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
* Marked `Guzzle\Http\Message\Request::canCache()` as deprecated. Use
`Guzzle\Plugin\Cache\DefaultCanCacheStrategy->canCacheRequest()` instead.
* Marked `Guzzle\Http\Message\Request::setIsRedirect()` as deprecated. Use the HistoryPlugin instead.
* Marked `Guzzle\Http\Message\Request::isRedirect()` as deprecated. Use the HistoryPlugin instead.
* Marked `Guzzle\Cache\CacheAdapterFactory::factory()` as deprecated
* Marked 'command.headers', 'command.response_body' and 'command.on_complete' as deprecated for AbstractCommand.
These will work through Guzzle 4.0
* Marked 'request.params' for `Guzzle\Http\Client` as deprecated. Use [request.options][params].
* Marked `Guzzle\Service\Client::enableMagicMethods()` as deprecated. Magic methods can no longer be disabled on a Guzzle\Service\Client.
* Marked `Guzzle\Service\Client::getDefaultHeaders()` as deprecated. Use $client->getConfig()->getPath('request.options/headers')`.
* Marked `Guzzle\Service\Client::setDefaultHeaders()` as deprecated. Use $client->getConfig()->setPath('request.options/headers/{header_name}', 'value')`.
* Marked `Guzzle\Parser\Url\UrlParser` as deprecated. Just use PHP's `parse_url()` and percent encode your UTF-8.
* Marked `Guzzle\Common\Collection::inject()` as deprecated.
* Marked `Guzzle\Plugin\CurlAuth\CurlAuthPlugin` as deprecated. Use `$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');`
* CacheKeyProviderInterface and DefaultCacheKeyProvider are no longer used. All of this logic is handled in a
CacheStorageInterface. These two objects and interface will be removed in a future version.
* Always setting X-cache headers on cached responses
* Default cache TTLs are now handled by the CacheStorageInterface of a CachePlugin
* `CacheStorageInterface::cache($key, Response $response, $ttl = null)` has changed to `cache(RequestInterface
$request, Response $response);`
* `CacheStorageInterface::fetch($key)` has changed to `fetch(RequestInterface $request);`
* `CacheStorageInterface::delete($key)` has changed to `delete(RequestInterface $request);`
* Added `CacheStorageInterface::purge($url)`
* `DefaultRevalidation::__construct(CacheKeyProviderInterface $cacheKey, CacheStorageInterface $cache, CachePlugin
$plugin)` has changed to `DefaultRevalidation::__construct(CacheStorageInterface $cache,
CanCacheStrategyInterface $canCache = null)`
* Added `RevalidationInterface::shouldRevalidate(RequestInterface $request, Response $response)`
3.6.0 (2013-05-29)
------------------
* ServiceDescription now implements ToArrayInterface
* Added command.hidden_params to blacklist certain headers from being treated as additionalParameters
* Guzzle can now correctly parse incomplete URLs
* Mixed casing of headers are now forced to be a single consistent casing across all values for that header.
* Messages internally use a HeaderCollection object to delegate handling case-insensitive header resolution
* Removed the whole changedHeader() function system of messages because all header changes now go through addHeader().
* Specific header implementations can be created for complex headers. When a message creates a header, it uses a
HeaderFactory which can map specific headers to specific header classes. There is now a Link header and
CacheControl header implementation.
* Removed from interface: Guzzle\Http\ClientInterface::setUriTemplate
* Removed from interface: Guzzle\Http\ClientInterface::setCurlMulti()
* Removed Guzzle\Http\Message\Request::receivedRequestHeader() and implemented this functionality in
Guzzle\Http\Curl\RequestMediator
* Removed the optional $asString parameter from MessageInterface::getHeader(). Just cast the header to a string.
* Removed the optional $tryChunkedTransfer option from Guzzle\Http\Message\EntityEnclosingRequestInterface
* Removed the $asObjects argument from Guzzle\Http\Message\MessageInterface::getHeaders()
* Removed Guzzle\Parser\ParserRegister::get(). Use getParser()
* Removed Guzzle\Parser\ParserRegister::set(). Use registerParser().
* All response header helper functions return a string rather than mixing Header objects and strings inconsistently
* Removed cURL blacklist support. This is no longer necessary now that Expect, Accept, etc are managed by Guzzle
directly via interfaces
* Removed the injecting of a request object onto a response object. The methods to get and set a request still exist
but are a no-op until removed.
* Most classes that used to require a ``Guzzle\Service\Command\CommandInterface` typehint now request a
`Guzzle\Service\Command\ArrayCommandInterface`.
* Added `Guzzle\Http\Message\RequestInterface::startResponse()` to the RequestInterface to handle injecting a response
on a request while the request is still being transferred
* The ability to case-insensitively search for header values
* Guzzle\Http\Message\Header::hasExactHeader
* Guzzle\Http\Message\Header::raw. Use getAll()
* Deprecated cache control specific methods on Guzzle\Http\Message\AbstractMessage. Use the CacheControl header object
instead.
* `Guzzle\Service\Command\CommandInterface` now extends from ToArrayInterface and ArrayAccess
* Added the ability to cast Model objects to a string to view debug information.
3.5.0 (2013-05-13)
------------------
* Bug: Fixed a regression so that request responses are parsed only once per oncomplete event rather than multiple times
* Bug: Better cleanup of one-time events accross the board (when an event is meant to fire once, it will now remove
itself from the EventDispatcher)
* Bug: `Guzzle\Log\MessageFormatter` now properly writes "total_time" and "connect_time" values
* Bug: Cloning an EntityEnclosingRequest now clones the EntityBody too
* Bug: Fixed an undefined index error when parsing nested JSON responses with a sentAs parameter that reference a
non-existent key
* Bug: All __call() method arguments are now required (helps with mocking frameworks)
* Deprecating Response::getRequest() and now using a shallow clone of a request object to remove a circular reference
to help with refcount based garbage collection of resources created by sending a request
* Deprecating ZF1 cache and log adapters. These will be removed in the next major version.
* Deprecating `Response::getPreviousResponse()` (method signature still exists, but it'sdeprecated). Use the
HistoryPlugin for a history.
* Added a `responseBody` alias for the `response_body` location
* Refactored internals to no longer rely on Response::getRequest()
* HistoryPlugin can now be cast to a string
* HistoryPlugin now logs transactions rather than requests and responses to more accurately keep track of the requests
and responses that are sent over the wire
* Added `getEffectiveUrl()` and `getRedirectCount()` to Response objects
3.4.3 (2013-04-30)
------------------
* Bug fix: Fixing bug introduced in 3.4.2 where redirect responses are duplicated on the final redirected response
* Added a check to re-extract the temp cacert bundle from the phar before sending each request
3.4.2 (2013-04-29)
------------------
* Bug fix: Stream objects now work correctly with "a" and "a+" modes
* Bug fix: Removing `Transfer-Encoding: chunked` header when a Content-Length is present
* Bug fix: AsyncPlugin no longer forces HEAD requests
* Bug fix: DateTime timezones are now properly handled when using the service description schema formatter
* Bug fix: CachePlugin now properly handles stale-if-error directives when a request to the origin server fails
* Setting a response on a request will write to the custom request body from the response body if one is specified
* LogPlugin now writes to php://output when STDERR is undefined
* Added the ability to set multiple POST files for the same key in a single call
* application/x-www-form-urlencoded POSTs now use the utf-8 charset by default
* Added the ability to queue CurlExceptions to the MockPlugin
* Cleaned up how manual responses are queued on requests (removed "queued_response" and now using request.before_send)
* Configuration loading now allows remote files
3.4.1 (2013-04-16)
------------------
* Large refactoring to how CurlMulti handles work. There is now a proxy that sits in front of a pool of CurlMulti
handles. This greatly simplifies the implementation, fixes a couple bugs, and provides a small performance boost.
* Exceptions are now properly grouped when sending requests in parallel
* Redirects are now properly aggregated when a multi transaction fails
* Redirects now set the response on the original object even in the event of a failure
* Bug fix: Model names are now properly set even when using $refs
* Added support for PHP 5.5's CurlFile to prevent warnings with the deprecated @ syntax
* Added support for oauth_callback in OAuth signatures
* Added support for oauth_verifier in OAuth signatures
* Added support to attempt to retrieve a command first literally, then ucfirst, the with inflection
3.4.0 (2013-04-11)
------------------
* Bug fix: URLs are now resolved correctly based on http://tools.ietf.org/html/rfc3986#section-5.2. #289
* Bug fix: Absolute URLs with a path in a service description will now properly override the base URL. #289
* Bug fix: Parsing a query string with a single PHP array value will now result in an array. #263
* Bug fix: Better normalization of the User-Agent header to prevent duplicate headers. #264.
* Bug fix: Added `number` type to service descriptions.
* Bug fix: empty parameters are removed from an OAuth signature
* Bug fix: Revalidating a cache entry prefers the Last-Modified over the Date header
* Bug fix: Fixed "array to string" error when validating a union of types in a service description
* Bug fix: Removed code that attempted to determine the size of a stream when data is written to the stream
* Bug fix: Not including an `oauth_token` if the value is null in the OauthPlugin.
* Bug fix: Now correctly aggregating successful requests and failed requests in CurlMulti when a redirect occurs.
* The new default CURLOPT_TIMEOUT setting has been increased to 150 seconds so that Guzzle works on poor connections.
* Added a feature to EntityEnclosingRequest::setBody() that will automatically set the Content-Type of the request if
the Content-Type can be determined based on the entity body or the path of the request.
* Added the ability to overwrite configuration settings in a client when grabbing a throwaway client from a builder.
* Added support for a PSR-3 LogAdapter.
* Added a `command.after_prepare` event
* Added `oauth_callback` parameter to the OauthPlugin
* Added the ability to create a custom stream class when using a stream factory
* Added a CachingEntityBody decorator
* Added support for `additionalParameters` in service descriptions to define how custom parameters are serialized.
* The bundled SSL certificate is now provided in the phar file and extracted when running Guzzle from a phar.
* You can now send any EntityEnclosingRequest with POST fields or POST files and cURL will handle creating bodies
* POST requests using a custom entity body are now treated exactly like PUT requests but with a custom cURL method. This
means that the redirect behavior of POST requests with custom bodies will not be the same as POST requests that use
POST fields or files (the latter is only used when emulating a form POST in the browser).
* Lots of cleanup to CurlHandle::factory and RequestFactory::createRequest
3.3.1 (2013-03-10)
------------------
* Added the ability to create PHP streaming responses from HTTP requests
* Bug fix: Running any filters when parsing response headers with service descriptions
* Bug fix: OauthPlugin fixes to allow for multi-dimensional array signing, and sorting parameters before signing
* Bug fix: Removed the adding of default empty arrays and false Booleans to responses in order to be consistent across
response location visitors.
* Bug fix: Removed the possibility of creating configuration files with circular dependencies
* RequestFactory::create() now uses the key of a POST file when setting the POST file name
* Added xmlAllowEmpty to serialize an XML body even if no XML specific parameters are set
3.3.0 (2013-03-03)
------------------
* A large number of performance optimizations have been made
* Bug fix: Added 'wb' as a valid write mode for streams
* Bug fix: `Guzzle\Http\Message\Response::json()` now allows scalar values to be returned
* Bug fix: Fixed bug in `Guzzle\Http\Message\Response` where wrapping quotes were stripped from `getEtag()`
* BC: Removed `Guzzle\Http\Utils` class
* BC: Setting a service description on a client will no longer modify the client's command factories.
* BC: Emitting IO events from a RequestMediator is now a parameter that must be set in a request's curl options using
the 'emit_io' key. This was previously set under a request's parameters using 'curl.emit_io'
* BC: `Guzzle\Stream\Stream::getWrapper()` and `Guzzle\Stream\Stream::getSteamType()` are no longer converted to
lowercase
* Operation parameter objects are now lazy loaded internally
* Added ErrorResponsePlugin that can throw errors for responses defined in service description operations' errorResponses
* Added support for instantiating responseType=class responseClass classes. Classes must implement
`Guzzle\Service\Command\ResponseClassInterface`
* Added support for additionalProperties for top-level parameters in responseType=model responseClasses. These
additional properties also support locations and can be used to parse JSON responses where the outermost part of the
JSON is an array
* Added support for nested renaming of JSON models (rename sentAs to name)
* CachePlugin
* Added support for stale-if-error so that the CachePlugin can now serve stale content from the cache on error
* Debug headers can now added to cached response in the CachePlugin
3.2.0 (2013-02-14)
------------------
* CurlMulti is no longer reused globally. A new multi object is created per-client. This helps to isolate clients.
* URLs with no path no longer contain a "/" by default
* Guzzle\Http\QueryString does no longer manages the leading "?". This is now handled in Guzzle\Http\Url.
* BadResponseException no longer includes the full request and response message
* Adding setData() to Guzzle\Service\Description\ServiceDescriptionInterface
* Adding getResponseBody() to Guzzle\Http\Message\RequestInterface
* Various updates to classes to use ServiceDescriptionInterface type hints rather than ServiceDescription
* Header values can now be normalized into distinct values when multiple headers are combined with a comma separated list
* xmlEncoding can now be customized for the XML declaration of a XML service description operation
* Guzzle\Http\QueryString now uses Guzzle\Http\QueryAggregator\QueryAggregatorInterface objects to add custom value
aggregation and no longer uses callbacks
* The URL encoding implementation of Guzzle\Http\QueryString can now be customized
* Bug fix: Filters were not always invoked for array service description parameters
* Bug fix: Redirects now use a target response body rather than a temporary response body
* Bug fix: The default exponential backoff BackoffPlugin was not giving when the request threshold was exceeded
* Bug fix: Guzzle now takes the first found value when grabbing Cache-Control directives
3.1.2 (2013-01-27)
------------------
* Refactored how operation responses are parsed. Visitors now include a before() method responsible for parsing the
response body. For example, the XmlVisitor now parses the XML response into an array in the before() method.
* Fixed an issue where cURL would not automatically decompress responses when the Accept-Encoding header was sent
* CURLOPT_SSL_VERIFYHOST is never set to 1 because it is deprecated (see 5e0ff2ef20f839e19d1eeb298f90ba3598784444)
* Fixed a bug where redirect responses were not chained correctly using getPreviousResponse()
* Setting default headers on a client after setting the user-agent will not erase the user-agent setting
3.1.1 (2013-01-20)
------------------
* Adding wildcard support to Guzzle\Common\Collection::getPath()
* Adding alias support to ServiceBuilder configs
* Adding Guzzle\Service\Resource\CompositeResourceIteratorFactory and cleaning up factory interface
3.1.0 (2013-01-12)
------------------
* BC: CurlException now extends from RequestException rather than BadResponseException
* BC: Renamed Guzzle\Plugin\Cache\CanCacheStrategyInterface::canCache() to canCacheRequest() and added CanCacheResponse()
* Added getData to ServiceDescriptionInterface
* Added context array to RequestInterface::setState()
* Bug: Removing hard dependency on the BackoffPlugin from Guzzle\Http
* Bug: Adding required content-type when JSON request visitor adds JSON to a command
* Bug: Fixing the serialization of a service description with custom data
* Made it easier to deal with exceptions thrown when transferring commands or requests in parallel by providing
an array of successful and failed responses
* Moved getPath from Guzzle\Service\Resource\Model to Guzzle\Common\Collection
* Added Guzzle\Http\IoEmittingEntityBody
* Moved command filtration from validators to location visitors
* Added `extends` attributes to service description parameters
* Added getModels to ServiceDescriptionInterface
3.0.7 (2012-12-19)
------------------
* Fixing phar detection when forcing a cacert to system if null or true
* Allowing filename to be passed to `Guzzle\Http\Message\Request::setResponseBody()`
* Cleaning up `Guzzle\Common\Collection::inject` method
* Adding a response_body location to service descriptions
3.0.6 (2012-12-09)
------------------
* CurlMulti performance improvements
* Adding setErrorResponses() to Operation
* composer.json tweaks
3.0.5 (2012-11-18)
------------------
* Bug: Fixing an infinite recursion bug caused from revalidating with the CachePlugin
* Bug: Response body can now be a string containing "0"
* Bug: Using Guzzle inside of a phar uses system by default but now allows for a custom cacert
* Bug: QueryString::fromString now properly parses query string parameters that contain equal signs
* Added support for XML attributes in service description responses
* DefaultRequestSerializer now supports array URI parameter values for URI template expansion
* Added better mimetype guessing to requests and post files
3.0.4 (2012-11-11)
------------------
* Bug: Fixed a bug when adding multiple cookies to a request to use the correct glue value
* Bug: Cookies can now be added that have a name, domain, or value set to "0"
* Bug: Using the system cacert bundle when using the Phar
* Added json and xml methods to Response to make it easier to parse JSON and XML response data into data structures
* Enhanced cookie jar de-duplication
* Added the ability to enable strict cookie jars that throw exceptions when invalid cookies are added
* Added setStream to StreamInterface to actually make it possible to implement custom rewind behavior for entity bodies
* Added the ability to create any sort of hash for a stream rather than just an MD5 hash
3.0.3 (2012-11-04)
------------------
* Implementing redirects in PHP rather than cURL
* Added PECL URI template extension and using as default parser if available
* Bug: Fixed Content-Length parsing of Response factory
* Adding rewind() method to entity bodies and streams. Allows for custom rewinding of non-repeatable streams.
* Adding ToArrayInterface throughout library
* Fixing OauthPlugin to create unique nonce values per request
3.0.2 (2012-10-25)
------------------
* Magic methods are enabled by default on clients
* Magic methods return the result of a command
* Service clients no longer require a base_url option in the factory
* Bug: Fixed an issue with URI templates where null template variables were being expanded
3.0.1 (2012-10-22)
------------------
* Models can now be used like regular collection objects by calling filter, map, etc
* Models no longer require a Parameter structure or initial data in the constructor
* Added a custom AppendIterator to get around a PHP bug with the `\AppendIterator`
3.0.0 (2012-10-15)
------------------
* Rewrote service description format to be based on Swagger
* Now based on JSON schema
* Added nested input structures and nested response models
* Support for JSON and XML input and output models
* Renamed `commands` to `operations`
* Removed dot class notation
* Removed custom types
* Broke the project into smaller top-level namespaces to be more component friendly
* Removed support for XML configs and descriptions. Use arrays or JSON files.
* Removed the Validation component and Inspector
* Moved all cookie code to Guzzle\Plugin\Cookie
* Magic methods on a Guzzle\Service\Client now return the command un-executed.
* Calling getResult() or getResponse() on a command will lazily execute the command if needed.
* Now shipping with cURL's CA certs and using it by default
* Added previousResponse() method to response objects
* No longer sending Accept and Accept-Encoding headers on every request
* Only sending an Expect header by default when a payload is greater than 1MB
* Added/moved client options:
* curl.blacklist to curl.option.blacklist
* Added ssl.certificate_authority
* Added a Guzzle\Iterator component
* Moved plugins from Guzzle\Http\Plugin to Guzzle\Plugin
* Added a more robust backoff retry strategy (replaced the ExponentialBackoffPlugin)
* Added a more robust caching plugin
* Added setBody to response objects
* Updating LogPlugin to use a more flexible MessageFormatter
* Added a completely revamped build process
* Cleaning up Collection class and removing default values from the get method
* Fixed ZF2 cache adapters
2.8.8 (2012-10-15)
------------------
* Bug: Fixed a cookie issue that caused dot prefixed domains to not match where popular browsers did
2.8.7 (2012-09-30)
------------------
* Bug: Fixed config file aliases for JSON includes
* Bug: Fixed cookie bug on a request object by using CookieParser to parse cookies on requests
* Bug: Removing the path to a file when sending a Content-Disposition header on a POST upload
* Bug: Hardening request and response parsing to account for missing parts
* Bug: Fixed PEAR packaging
* Bug: Fixed Request::getInfo
* Bug: Fixed cases where CURLM_CALL_MULTI_PERFORM return codes were causing curl transactions to fail
* Adding the ability for the namespace Iterator factory to look in multiple directories
* Added more getters/setters/removers from service descriptions
* Added the ability to remove POST fields from OAuth signatures
* OAuth plugin now supports 2-legged OAuth
2.8.6 (2012-09-05)
------------------
* Added the ability to modify and build service descriptions
* Added the use of visitors to apply parameters to locations in service descriptions using the dynamic command
* Added a `json` parameter location
* Now allowing dot notation for classes in the CacheAdapterFactory
* Using the union of two arrays rather than an array_merge when extending service builder services and service params
* Ensuring that a service is a string before doing strpos() checks on it when substituting services for references
in service builder config files.
* Services defined in two different config files that include one another will by default replace the previously
defined service, but you can now create services that extend themselves and merge their settings over the previous
* The JsonLoader now supports aliasing filenames with different filenames. This allows you to alias something like
'_default' with a default JSON configuration file.
2.8.5 (2012-08-29)
------------------
* Bug: Suppressed empty arrays from URI templates
* Bug: Added the missing $options argument from ServiceDescription::factory to enable caching
* Added support for HTTP responses that do not contain a reason phrase in the start-line
* AbstractCommand commands are now invokable
* Added a way to get the data used when signing an Oauth request before a request is sent
2.8.4 (2012-08-15)
------------------
* Bug: Custom delay time calculations are no longer ignored in the ExponentialBackoffPlugin
* Added the ability to transfer entity bodies as a string rather than streamed. This gets around curl error 65. Set `body_as_string` in a request's curl options to enable.
* Added a StreamInterface, EntityBodyInterface, and added ftell() to Guzzle\Common\Stream
* Added an AbstractEntityBodyDecorator and a ReadLimitEntityBody decorator to transfer only a subset of a decorated stream
* Stream and EntityBody objects will now return the file position to the previous position after a read required operation (e.g. getContentMd5())
* Added additional response status codes
* Removed SSL information from the default User-Agent header
* DELETE requests can now send an entity body
* Added an EventDispatcher to the ExponentialBackoffPlugin and added an ExponentialBackoffLogger to log backoff retries
* Added the ability of the MockPlugin to consume mocked request bodies
* LogPlugin now exposes request and response objects in the extras array
2.8.3 (2012-07-30)
------------------
* Bug: Fixed a case where empty POST requests were sent as GET requests
* Bug: Fixed a bug in ExponentialBackoffPlugin that caused fatal errors when retrying an EntityEnclosingRequest that does not have a body
* Bug: Setting the response body of a request to null after completing a request, not when setting the state of a request to new
* Added multiple inheritance to service description commands
* Added an ApiCommandInterface and added ``getParamNames()`` and ``hasParam()``
* Removed the default 2mb size cutoff from the Md5ValidatorPlugin so that it now defaults to validating everything
* Changed CurlMulti::perform to pass a smaller timeout to CurlMulti::executeHandles
2.8.2 (2012-07-24)
------------------
* Bug: Query string values set to 0 are no longer dropped from the query string
* Bug: A Collection object is no longer created each time a call is made to ``Guzzle\Service\Command\AbstractCommand::getRequestHeaders()``
* Bug: ``+`` is now treated as an encoded space when parsing query strings
* QueryString and Collection performance improvements
* Allowing dot notation for class paths in filters attribute of a service descriptions
2.8.1 (2012-07-16)
------------------
* Loosening Event Dispatcher dependency
* POST redirects can now be customized using CURLOPT_POSTREDIR
2.8.0 (2012-07-15)
------------------
* BC: Guzzle\Http\Query
* Query strings with empty variables will always show an equal sign unless the variable is set to QueryString::BLANK (e.g. ?acl= vs ?acl)
* Changed isEncodingValues() and isEncodingFields() to isUrlEncoding()
* Changed setEncodeValues(bool) and setEncodeFields(bool) to useUrlEncoding(bool)
* Changed the aggregation functions of QueryString to be static methods
* Can now use fromString() with querystrings that have a leading ?
* cURL configuration values can be specified in service descriptions using ``curl.`` prefixed parameters
* Content-Length is set to 0 before emitting the request.before_send event when sending an empty request body
* Cookies are no longer URL decoded by default
* Bug: URI template variables set to null are no longer expanded
2.7.2 (2012-07-02)
------------------
* BC: Moving things to get ready for subtree splits. Moving Inflection into Common. Moving Guzzle\Http\Parser to Guzzle\Parser.
* BC: Removing Guzzle\Common\Batch\Batch::count() and replacing it with isEmpty()
* CachePlugin now allows for a custom request parameter function to check if a request can be cached
* Bug fix: CachePlugin now only caches GET and HEAD requests by default
* Bug fix: Using header glue when transferring headers over the wire
* Allowing deeply nested arrays for composite variables in URI templates
* Batch divisors can now return iterators or arrays
2.7.1 (2012-06-26)
------------------
* Minor patch to update version number in UA string
* Updating build process
2.7.0 (2012-06-25)
------------------
* BC: Inflection classes moved to Guzzle\Inflection. No longer static methods. Can now inject custom inflectors into classes.
* BC: Removed magic setX methods from commands
* BC: Magic methods mapped to service description commands are now inflected in the command factory rather than the client __call() method
* Verbose cURL options are no longer enabled by default. Set curl.debug to true on a client to enable.
* Bug: Now allowing colons in a response start-line (e.g. HTTP/1.1 503 Service Unavailable: Back-end server is at capacity)
* Guzzle\Service\Resource\ResourceIteratorApplyBatched now internally uses the Guzzle\Common\Batch namespace
* Added Guzzle\Service\Plugin namespace and a PluginCollectionPlugin
* Added the ability to set POST fields and files in a service description
* Guzzle\Http\EntityBody::factory() now accepts objects with a __toString() method
* Adding a command.before_prepare event to clients
* Added BatchClosureTransfer and BatchClosureDivisor
* BatchTransferException now includes references to the batch divisor and transfer strategies
* Fixed some tests so that they pass more reliably
* Added Guzzle\Common\Log\ArrayLogAdapter
2.6.6 (2012-06-10)
------------------
* BC: Removing Guzzle\Http\Plugin\BatchQueuePlugin
* BC: Removing Guzzle\Service\Command\CommandSet
* Adding generic batching system (replaces the batch queue plugin and command set)
* Updating ZF cache and log adapters and now using ZF's composer repository
* Bug: Setting the name of each ApiParam when creating through an ApiCommand
* Adding result_type, result_doc, deprecated, and doc_url to service descriptions
* Bug: Changed the default cookie header casing back to 'Cookie'
2.6.5 (2012-06-03)
------------------
* BC: Renaming Guzzle\Http\Message\RequestInterface::getResourceUri() to getResource()
* BC: Removing unused AUTH_BASIC and AUTH_DIGEST constants from
* BC: Guzzle\Http\Cookie is now used to manage Set-Cookie data, not Cookie data
* BC: Renaming methods in the CookieJarInterface
* Moving almost all cookie logic out of the CookiePlugin and into the Cookie or CookieJar implementations
* Making the default glue for HTTP headers ';' instead of ','
* Adding a removeValue to Guzzle\Http\Message\Header
* Adding getCookies() to request interface.
* Making it easier to add event subscribers to HasDispatcherInterface classes. Can now directly call addSubscriber()
2.6.4 (2012-05-30)
------------------
* BC: Cleaning up how POST files are stored in EntityEnclosingRequest objects. Adding PostFile class.
* BC: Moving ApiCommand specific functionality from the Inspector and on to the ApiCommand
* Bug: Fixing magic method command calls on clients
* Bug: Email constraint only validates strings
* Bug: Aggregate POST fields when POST files are present in curl handle
* Bug: Fixing default User-Agent header
* Bug: Only appending or prepending parameters in commands if they are specified
* Bug: Not requiring response reason phrases or status codes to match a predefined list of codes
* Allowing the use of dot notation for class namespaces when using instance_of constraint
* Added any_match validation constraint
* Added an AsyncPlugin
* Passing request object to the calculateWait method of the ExponentialBackoffPlugin
* Allowing the result of a command object to be changed
* Parsing location and type sub values when instantiating a service description rather than over and over at runtime
2.6.3 (2012-05-23)
------------------
* [BC] Guzzle\Common\FromConfigInterface no longer requires any config options.
* [BC] Refactoring how POST files are stored on an EntityEnclosingRequest. They are now separate from POST fields.
* You can now use an array of data when creating PUT request bodies in the request factory.
* Removing the requirement that HTTPS requests needed a Cache-Control: public directive to be cacheable.
* [Http] Adding support for Content-Type in multipart POST uploads per upload
* [Http] Added support for uploading multiple files using the same name (foo[0], foo[1])
* Adding more POST data operations for easier manipulation of POST data.
* You can now set empty POST fields.
* The body of a request is only shown on EntityEnclosingRequest objects that do not use POST files.
* Split the Guzzle\Service\Inspector::validateConfig method into two methods. One to initialize when a command is created, and one to validate.
* CS updates
2.6.2 (2012-05-19)
------------------
* [Http] Better handling of nested scope requests in CurlMulti. Requests are now always prepares in the send() method rather than the addRequest() method.
2.6.1 (2012-05-19)
------------------
* [BC] Removing 'path' support in service descriptions. Use 'uri'.
* [BC] Guzzle\Service\Inspector::parseDocBlock is now protected. Adding getApiParamsForClass() with cache.
* [BC] Removing Guzzle\Common\NullObject. Use https://github.com/mtdowling/NullObject if you need it.
* [BC] Removing Guzzle\Common\XmlElement.
* All commands, both dynamic and concrete, have ApiCommand objects.
* Adding a fix for CurlMulti so that if all of the connections encounter some sort of curl error, then the loop exits.
* Adding checks to EntityEnclosingRequest so that empty POST files and fields are ignored.
* Making the method signature of Guzzle\Service\Builder\ServiceBuilder::factory more flexible.
2.6.0 (2012-05-15)
------------------
* [BC] Moving Guzzle\Service\Builder to Guzzle\Service\Builder\ServiceBuilder
* [BC] Executing a Command returns the result of the command rather than the command
* [BC] Moving all HTTP parsing logic to Guzzle\Http\Parsers. Allows for faster C implementations if needed.
* [BC] Changing the Guzzle\Http\Message\Response::setProtocol() method to accept a protocol and version in separate args.
* [BC] Moving ResourceIterator* to Guzzle\Service\Resource
* [BC] Completely refactored ResourceIterators to iterate over a cloned command object
* [BC] Moved Guzzle\Http\UriTemplate to Guzzle\Http\Parser\UriTemplate\UriTemplate
* [BC] Guzzle\Guzzle is now deprecated
* Moving Guzzle\Common\Guzzle::inject to Guzzle\Common\Collection::inject
* Adding Guzzle\Version class to give version information about Guzzle
* Adding Guzzle\Http\Utils class to provide getDefaultUserAgent() and getHttpDate()
* Adding Guzzle\Curl\CurlVersion to manage caching curl_version() data
* ServiceDescription and ServiceBuilder are now cacheable using similar configs
* Changing the format of XML and JSON service builder configs. Backwards compatible.
* Cleaned up Cookie parsing
* Trimming the default Guzzle User-Agent header
* Adding a setOnComplete() method to Commands that is called when a command completes
* Keeping track of requests that were mocked in the MockPlugin
* Fixed a caching bug in the CacheAdapterFactory
* Inspector objects can be injected into a Command object
* Refactoring a lot of code and tests to be case insensitive when dealing with headers
* Adding Guzzle\Http\Message\HeaderComparison for easy comparison of HTTP headers using a DSL
* Adding the ability to set global option overrides to service builder configs
* Adding the ability to include other service builder config files from within XML and JSON files
* Moving the parseQuery method out of Url and on to QueryString::fromString() as a static factory method.
2.5.0 (2012-05-08)
------------------
* Major performance improvements
* [BC] Simplifying Guzzle\Common\Collection. Please check to see if you are using features that are now deprecated.
* [BC] Using a custom validation system that allows a flyweight implementation for much faster validation. No longer using Symfony2 Validation component.
* [BC] No longer supporting "{{ }}" for injecting into command or UriTemplates. Use "{}"
* Added the ability to passed parameters to all requests created by a client
* Added callback functionality to the ExponentialBackoffPlugin
* Using microtime in ExponentialBackoffPlugin to allow more granular backoff strategies.
* Rewinding request stream bodies when retrying requests
* Exception is thrown when JSON response body cannot be decoded
* Added configurable magic method calls to clients and commands. This is off by default.
* Fixed a defect that added a hash to every parsed URL part
* Fixed duplicate none generation for OauthPlugin.
* Emitting an event each time a client is generated by a ServiceBuilder
* Using an ApiParams object instead of a Collection for parameters of an ApiCommand
* cache.* request parameters should be renamed to params.cache.*
* Added the ability to set arbitrary curl options on requests (disable_wire, progress, etc). See CurlHandle.
* Added the ability to disable type validation of service descriptions
* ServiceDescriptions and ServiceBuilders are now Serializable
Guzzle-3.7.0/Guzzle/LICENSE.md 0000644 233176441610067500000002127 12155472567 017320 0 ustar dowling ANT\Domain Users Copyright (c) 2011 Michael Dowling, https://github.com/mtdowling
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.
Guzzle-3.7.0/Guzzle/README.md 0000644 233176441610067500000020702 12155472567 017172 0 ustar dowling ANT\Domain Users Guzzle, PHP HTTP client and webservice framework
================================================
[](https://packagist.org/packages/guzzle/guzzle) [](https://packagist.org/packages/guzzle/guzzle) [](http://travis-ci.org/guzzle/guzzle)
Guzzle is a PHP HTTP client and framework for building RESTful web service clients.
- Extremely powerful API provides all the power of cURL with a simple interface.
- Truly take advantage of HTTP/1.1 with persistent connections, connection pooling, and parallel requests.
- Service description DSL allows you build awesome web service clients faster.
- Symfony2 event-based plugin system allows you to completely modify the behavior of a request.
Get answers with: [Documentation](http://www.guzzlephp.org/), [Forums](https://groups.google.com/forum/?hl=en#!forum/guzzle), IRC ([#guzzlephp](irc://irc.freenode.net/#guzzlephp) @ irc.freenode.net)
```php
// Really simple using a static facade
Guzzle\Http\StaticClient::mount();
$response = Guzzle::get('http://guzzlephp.org');
// More control using a client class
$client = new \Guzzle\Http\Client('http://guzzlephp.org');
$request = $client->get('/');
$response = $request->send();
```
### Installing via Composer
The recommended way to install Guzzle is through [Composer](http://getcomposer.org).
```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
# Add Guzzle as a dependency
php composer.phar require guzzle/guzzle:~3.6
```
After installing, you need to require Composer's autoloader:
```php
require 'vendor/autoload.php';
```
### Installing via phar
[Download the phar](http://guzzlephp.org/guzzle.phar) and include it in your project
([minimal phar](http://guzzlephp.org/guzzle-min.phar))
Features
--------
- Supports GET, HEAD, POST, DELETE, PUT, PATCH, OPTIONS, and any other custom HTTP method
- Allows full access to request and response headers
- Persistent connections are implicitly managed by Guzzle, resulting in huge performance benefits
- [Send requests in parallel](http://guzzlephp.org/tour/http.html#send-http-requests-in-parallel)
- Cookie sessions can be maintained between requests using the
[CookiePlugin](http://guzzlephp.org/tour/http.html#cookie-session-plugin)
- Allows custom [entity bodies](http://guzzlephp.org/tour/http.html#entity-bodies), including sending data from a PHP
stream and downloading data to a PHP stream
- Responses can be cached and served from cache using the
[caching forward proxy plugin](http://guzzlephp.org/tour/http.html#php-based-caching-forward-proxy)
- Failed requests can be retried using
[truncated exponential backoff](http://guzzlephp.org/tour/http.html#truncated-exponential-backoff) with custom retry
policies
- Entity bodies can be validated automatically using Content-MD5 headers and the
[MD5 hash validator plugin](http://guzzlephp.org/tour/http.html#md5-hash-validator-plugin)
- All data sent over the wire can be logged using the
[LogPlugin](http://guzzlephp.org/tour/http.html#over-the-wire-logging)
- Subject/Observer signal slot system for unobtrusively
[modifying request behavior](http://guzzlephp.org/guide/http/creating_plugins.html)
- Supports all of the features of libcurl including authentication, compression, redirects, SSL, proxies, etc
- Web service client framework for building future-proof interfaces to web services
- Includes a [service description DSL](http://guzzlephp.org/guide/service/service_descriptions.html) for quickly
building webservice clients
- Full support for [URI templates](http://tools.ietf.org/html/rfc6570)
- Advanced batching functionality to efficiently send requests or commands in parallel with customizable batch sizes
and transfer strategies
HTTP basics
-----------
```php
'***'
]);
// Issue a path using a relative URL to the client's base URL
// Sends to http://www.example.com/api/v1/key/***/users
$request = $client->get('users');
$response = $request->send();
// Relative URL that overwrites the path of the base URL
$request = $client->get('/test/123.php?a=b');
// Issue a head request on the base URL
$response = $client->head()->send();
// Delete user 123
$response = $client->delete('users/123')->send();
// Send a PUT request with custom headers
$response = $client->put('upload/text', [
'X-Header' => 'My Header'
], 'body of the request')->send();
// Send a PUT request using the contents of a PHP stream as the body
// Send using an absolute URL (overrides the base URL)
$response = $client->put('http://www.example.com/upload', [
'X-Header' => 'My Header'
], fopen('http://www.test.com/', 'r'));
// Create a POST request with a file upload (notice the @ symbol):
$request = $client->post('http://localhost:8983/solr/update', null, [
'custom_field' => 'my value',
'file' => '@/path/to/documents.xml'
]);
// Create a POST request and add the POST files manually
$request = $client->post('http://localhost:8983/solr/update')
->addPostFiles(['file' => '/path/to/documents.xml']);
// Responses are objects
echo $response->getStatusCode() . ' ' . $response->getReasonPhrase() . "\n";
// Requests and responses can be cast to a string to show the raw HTTP message
echo $request . "\n\n" . $response;
// Create a request based on an HTTP message
$request = RequestFactory::fromMessage(
"PUT / HTTP/1.1\r\n" .
"Host: test.com:8081\r\n" .
"Content-Type: text/plain" .
"Transfer-Encoding: chunked\r\n" .
"\r\n" .
"this is the body"
);
```
Using the static client facade
------------------------------
You can use Guzzle through a static client to make it even easier to send simple HTTP requests.
```php
['X-Foo' => 'Bar']
'body' => ['Foo' => 'Bar'],
'query' => ['Test' => 123],
'timeout' => 10,
'debug' => true,
'save_to' => '/path/to/file.html'
]);
```
### Available request options:
* headers: Associative array of headers
* query: Associative array of query string values to add to the request
* body: Body of a request, including an EntityBody, string, or array when sending POST requests. Setting a body for a
GET request will set where the response body is downloaded.
* auth: Array of HTTP authentication parameters to use with the request. The array must contain the
username in index [0], the password in index [2], and can optionally contain the authentication type in index [3].
The authentication types are: "Basic", "Digest". The default auth type is "Basic".
* cookies: Associative array of cookies
* allow_redirects: Set to false to disable redirects
* save_to: String, fopen resource, or EntityBody object used to store the body of the response
* events: Associative array mapping event names to a closure or array of (priority, closure)
* plugins: Array of plugins to add to the request
* exceptions: Set to false to disable throwing exceptions on an HTTP level error (e.g. 404, 500, etc)
* timeout: Float describing the timeout of the request in seconds
* connect_timeout: Float describing the number of seconds to wait while trying to connect. Use 0 to wait
indefinitely.
* verify: Set to true to enable SSL cert validation (the default), false to disable, or supply the path to a CA
bundle to enable verification using a custom certificate.
* proxy: Specify an HTTP proxy (e.g. "http://username:password@192.168.16.1:10")
* debug: Set to true to display all data sent over the wire
These options can also be used when creating requests using a standard client:
```php
$client = new Guzzle\Http\Client();
// Create a request with a timeout of 10 seconds
$request = $client->get('http://guzzlephp.org', [], ['timeout' => 10]);
$response = $request->send();
```
Unit testing
------------
Guzzle uses PHPUnit for unit testing. In order to run the unit tests, you'll first need
to install the dependencies of the project using Composer: `php composer.phar install --dev`.
You can then run the tests using `vendor/bin/phpunit`.
Guzzle-3.7.0/Guzzle/Batch/AbstractBatchDecorator.php 0000644 233176441610067500000002737 12155472567 024025 0 ustar dowling ANT\Domain Users decoratedBatch = $decoratedBatch;
}
/**
* Allow decorators to implement custom methods
*
* @param string $method Missing method name
* @param array $args Method arguments
*
* @return mixed
* @codeCoverageIgnore
*/
public function __call($method, array $args)
{
return call_user_func_array(array($this->decoratedBatch, $method), $args);
}
public function add($item)
{
$this->decoratedBatch->add($item);
return $this;
}
public function flush()
{
return $this->decoratedBatch->flush();
}
public function isEmpty()
{
return $this->decoratedBatch->isEmpty();
}
/**
* Trace the decorators associated with the batch
*
* @return array
*/
public function getDecorators()
{
$found = array($this);
if (method_exists($this->decoratedBatch, 'getDecorators')) {
$found = array_merge($found, $this->decoratedBatch->getDecorators());
}
return $found;
}
}
Guzzle-3.7.0/Guzzle/Batch/Batch.php 0000644 233176441610067500000005723 12155472567 020474 0 ustar dowling ANT\Domain Users transferStrategy = $transferStrategy;
$this->divisionStrategy = $divisionStrategy;
$this->queue = new \SplQueue();
$this->queue->setIteratorMode(\SplQueue::IT_MODE_DELETE);
$this->dividedBatches = array();
}
public function add($item)
{
$this->queue->enqueue($item);
return $this;
}
public function flush()
{
$this->createBatches();
$items = array();
foreach ($this->dividedBatches as $batchIndex => $dividedBatch) {
while ($dividedBatch->valid()) {
$batch = $dividedBatch->current();
$dividedBatch->next();
try {
$this->transferStrategy->transfer($batch);
$items = array_merge($items, $batch);
} catch (\Exception $e) {
throw new BatchTransferException($batch, $items, $e, $this->transferStrategy, $this->divisionStrategy);
}
}
// Keep the divided batch down to a minimum in case of a later exception
unset($this->dividedBatches[$batchIndex]);
}
return $items;
}
public function isEmpty()
{
return count($this->queue) == 0 && count($this->dividedBatches) == 0;
}
/**
* Create batches for any queued items
*/
protected function createBatches()
{
if (count($this->queue)) {
if ($batches = $this->divisionStrategy->createBatches($this->queue)) {
// Convert arrays into iterators
if (is_array($batches)) {
$batches = new \ArrayIterator($batches);
}
$this->dividedBatches[] = $batches;
}
}
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchBuilder.php 0000644 233176441610067500000012753 12155472567 022004 0 ustar dowling ANT\Domain Users 'Guzzle\Batch\BatchRequestTransfer',
'command' => 'Guzzle\Batch\BatchCommandTransfer'
);
/**
* Create a new instance of the BatchBuilder
*
* @return BatchBuilder
*/
public static function factory()
{
return new self();
}
/**
* Automatically flush the batch when the size of the queue reaches a certain threshold. Adds {@see FlushingBatch}.
*
* @param $threshold Number of items to allow in the queue before a flush
*
* @return BatchBuilder
*/
public function autoFlushAt($threshold)
{
$this->autoFlush = $threshold;
return $this;
}
/**
* Maintain a history of all items that have been transferred using the batch. Adds {@see HistoryBatch}.
*
* @return BatchBuilder
*/
public function keepHistory()
{
$this->history = true;
return $this;
}
/**
* Buffer exceptions thrown during transfer so that you can transfer as much as possible, and after a transfer
* completes, inspect each exception that was thrown. Enables the {@see ExceptionBufferingBatch} decorator.
*
* @return BatchBuilder
*/
public function bufferExceptions()
{
$this->exceptionBuffering = true;
return $this;
}
/**
* Notify a callable each time a batch flush completes. Enables the {@see NotifyingBatch} decorator.
*
* @param mixed $callable Callable function to notify
*
* @return BatchBuilder
* @throws InvalidArgumentException if the argument is not callable
*/
public function notify($callable)
{
$this->afterFlush = $callable;
return $this;
}
/**
* Configures the batch to transfer batches of requests. Associates a {@see \Guzzle\Http\BatchRequestTransfer}
* object as both the transfer and divisor strategy.
*
* @param int $batchSize Batch size for each batch of requests
*
* @return BatchBuilder
*/
public function transferRequests($batchSize = 50)
{
$className = self::$mapping['request'];
$this->transferStrategy = new $className($batchSize);
$this->divisorStrategy = $this->transferStrategy;
return $this;
}
/**
* Configures the batch to transfer batches commands. Associates as
* {@see \Guzzle\Service\Command\BatchCommandTransfer} as both the transfer and divisor strategy.
*
* @param int $batchSize Batch size for each batch of commands
*
* @return BatchBuilder
*/
public function transferCommands($batchSize = 50)
{
$className = self::$mapping['command'];
$this->transferStrategy = new $className($batchSize);
$this->divisorStrategy = $this->transferStrategy;
return $this;
}
/**
* Specify the strategy used to divide the queue into an array of batches
*
* @param BatchDivisorInterface $divisorStrategy Strategy used to divide a batch queue into batches
*
* @return BatchBuilder
*/
public function createBatchesWith(BatchDivisorInterface $divisorStrategy)
{
$this->divisorStrategy = $divisorStrategy;
return $this;
}
/**
* Specify the strategy used to transport the items when flush is called
*
* @param BatchTransferInterface $transferStrategy How items are transferred
*
* @return BatchBuilder
*/
public function transferWith(BatchTransferInterface $transferStrategy)
{
$this->transferStrategy = $transferStrategy;
return $this;
}
/**
* Create and return the instantiated batch
*
* @return BatchInterface
* @throws RuntimeException if no transfer strategy has been specified
*/
public function build()
{
if (!$this->transferStrategy) {
throw new RuntimeException('No transfer strategy has been specified');
}
if (!$this->divisorStrategy) {
throw new RuntimeException('No divisor strategy has been specified');
}
$batch = new Batch($this->transferStrategy, $this->divisorStrategy);
if ($this->exceptionBuffering) {
$batch = new ExceptionBufferingBatch($batch);
}
if ($this->afterFlush) {
$batch = new NotifyingBatch($batch, $this->afterFlush);
}
if ($this->autoFlush) {
$batch = new FlushingBatch($batch, $this->autoFlush);
}
if ($this->history) {
$batch = new HistoryBatch($batch);
}
return $batch;
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchClosureDivisor.php 0000644 233176441610067500000002164 12155472567 023365 0 ustar dowling ANT\Domain Users callable = $callable;
$this->context = $context;
}
public function createBatches(\SplQueue $queue)
{
return call_user_func($this->callable, $queue, $this->context);
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchClosureTransfer.php 0000644 233176441610067500000002276 12155472567 023536 0 ustar dowling ANT\Domain Users callable = $callable;
$this->context = $context;
}
public function transfer(array $batch)
{
return empty($batch) ? null : call_user_func($this->callable, $batch, $this->context);
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchCommandTransfer.php 0000644 233176441610067500000004256 12155472567 023500 0 ustar dowling ANT\Domain Users batchSize = $batchSize;
}
/**
* Creates batches by grouping commands by their associated client
* {@inheritdoc}
*/
public function createBatches(\SplQueue $queue)
{
$groups = new \SplObjectStorage();
foreach ($queue as $item) {
if (!$item instanceof CommandInterface) {
throw new InvalidArgumentException('All items must implement Guzzle\Service\Command\CommandInterface');
}
$client = $item->getClient();
if (!$groups->contains($client)) {
$groups->attach($client, new \ArrayObject(array($item)));
} else {
$groups[$client]->append($item);
}
}
$batches = array();
foreach ($groups as $batch) {
$batches = array_merge($batches, array_chunk($groups[$batch]->getArrayCopy(), $this->batchSize));
}
return $batches;
}
public function transfer(array $batch)
{
if (empty($batch)) {
return;
}
// Get the client of the first found command
$client = reset($batch)->getClient();
// Keep a list of all commands with invalid clients
$invalid = array_filter($batch, function ($command) use ($client) {
return $command->getClient() !== $client;
});
if (!empty($invalid)) {
throw new InconsistentClientTransferException($invalid);
}
$client->execute($batch);
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchDivisorInterface.php 0000644 233176441610067500000000776 12155472567 023660 0 ustar dowling ANT\Domain Users batchSize = $batchSize;
}
/**
* Creates batches of requests by grouping requests by their associated curl multi object.
* {@inheritdoc}
*/
public function createBatches(\SplQueue $queue)
{
// Create batches by client objects
$groups = new \SplObjectStorage();
foreach ($queue as $item) {
if (!$item instanceof RequestInterface) {
throw new InvalidArgumentException('All items must implement Guzzle\Http\Message\RequestInterface');
}
$client = $item->getClient();
if (!$groups->contains($client)) {
$groups->attach($client, array($item));
} else {
$current = $groups[$client];
$current[] = $item;
$groups[$client] = $current;
}
}
$batches = array();
foreach ($groups as $batch) {
$batches = array_merge($batches, array_chunk($groups[$batch], $this->batchSize));
}
return $batches;
}
public function transfer(array $batch)
{
if ($batch) {
reset($batch)->getClient()->send($batch);
}
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchSizeDivisor.php 0000644 233176441610067500000001553 12155472567 022664 0 ustar dowling ANT\Domain Users size = $size;
}
/**
* Set the size of each batch
*
* @param int $size Size of each batch
*
* @return BatchSizeDivisor
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get the size of each batch
*
* @return int
*/
public function getSize()
{
return $this->size;
}
public function createBatches(\SplQueue $queue)
{
return array_chunk(iterator_to_array($queue, false), $this->size);
}
}
Guzzle-3.7.0/Guzzle/Batch/BatchTransferInterface.php 0000644 233176441610067500000000434 12155472567 024014 0 ustar dowling ANT\Domain Users decoratedBatch->isEmpty()) {
try {
$transferredItems = $this->decoratedBatch->flush();
} catch (BatchTransferException $e) {
$this->exceptions[] = $e;
$transferredItems = $e->getTransferredItems();
}
$items = array_merge($items, $transferredItems);
}
return $items;
}
/**
* Get the buffered exceptions
*
* @return array Array of BatchTransferException objects
*/
public function getExceptions()
{
return $this->exceptions;
}
/**
* Clear the buffered exceptions
*/
public function clearExceptions()
{
$this->exceptions = array();
}
}
Guzzle-3.7.0/Guzzle/Batch/FlushingBatch.php 0000644 233176441610067500000002677 12155472567 022201 0 ustar dowling ANT\Domain Users threshold = $threshold;
parent::__construct($decoratedBatch);
}
/**
* Set the auto-flush threshold
*
* @param int $threshold The auto-flush threshold
*
* @return FlushingBatch
*/
public function setThreshold($threshold)
{
$this->threshold = $threshold;
return $this;
}
/**
* Get the auto-flush threshold
*
* @return int
*/
public function getThreshold()
{
return $this->threshold;
}
public function add($item)
{
$this->decoratedBatch->add($item);
if (++$this->currentTotal >= $this->threshold) {
$this->currentTotal = 0;
$this->decoratedBatch->flush();
}
return $this;
}
}
Guzzle-3.7.0/Guzzle/Batch/HistoryBatch.php 0000644 233176441610067500000001366 12155472567 022055 0 ustar dowling ANT\Domain Users history[] = $item;
$this->decoratedBatch->add($item);
return $this;
}
/**
* Get the batch history
*
* @return array
*/
public function getHistory()
{
return $this->history;
}
/**
* Clear the batch history
*/
public function clearHistory()
{
$this->history = array();
}
}
Guzzle-3.7.0/Guzzle/Batch/NotifyingBatch.php 0000644 233176441610067500000001675 12155472567 022365 0 ustar dowling ANT\Domain Users callable = $callable;
parent::__construct($decoratedBatch);
}
public function flush()
{
$items = $this->decoratedBatch->flush();
call_user_func($this->callable, $items);
return $items;
}
}
Guzzle-3.7.0/Guzzle/Batch/Exception/BatchTransferException.php 0000644 233176441610067500000005213 12155472567 026010 0 ustar dowling ANT\Domain Users batch = $batch;
$this->transferredItems = $transferredItems;
$this->transferStrategy = $transferStrategy;
$this->divisorStrategy = $divisorStrategy;
parent::__construct(
'Exception encountered while transferring batch: ' . $exception->getMessage(),
$exception->getCode(),
$exception
);
}
/**
* Get the batch that we being sent when the exception occurred
*
* @return array
*/
public function getBatch()
{
return $this->batch;
}
/**
* Get the items transferred at the point in which the exception was encountered
*
* @return array
*/
public function getTransferredItems()
{
return $this->transferredItems;
}
/**
* Get the transfer strategy
*
* @return TransferStrategy
*/
public function getTransferStrategy()
{
return $this->transferStrategy;
}
/**
* Get the divisor strategy
*
* @return DivisorStrategy
*/
public function getDivisorStrategy()
{
return $this->divisorStrategy;
}
}
Guzzle-3.7.0/Guzzle/Cache/AbstractCacheAdapter.php 0000644 233176441610067500000000507 12155472567 023420 0 ustar dowling ANT\Domain Users cache;
}
}
Guzzle-3.7.0/Guzzle/Cache/CacheAdapterFactory.php 0000644 233176441610067500000010137 12155472567 023264 0 ustar dowling ANT\Domain Users newInstanceArgs($args);
}
} catch (\Exception $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
}
}
Guzzle-3.7.0/Guzzle/Cache/CacheAdapterInterface.php 0000644 233176441610067500000003353 12155472567 023557 0 ustar dowling ANT\Domain Users callables = $callables;
}
public function contains($id, array $options = null)
{
return call_user_func($this->callables['contains'], $id, $options);
}
public function delete($id, array $options = null)
{
return call_user_func($this->callables['delete'], $id, $options);
}
public function fetch($id, array $options = null)
{
return call_user_func($this->callables['fetch'], $id, $options);
}
public function save($id, $data, $lifeTime = false, array $options = null)
{
return call_user_func($this->callables['save'], $id, $data, $lifeTime, $options);
}
}
Guzzle-3.7.0/Guzzle/Cache/DoctrineCacheAdapter.php 0000644 233176441610067500000001513 12155472567 023422 0 ustar dowling ANT\Domain Users cache = $cache;
}
public function contains($id, array $options = null)
{
return $this->cache->contains($id);
}
public function delete($id, array $options = null)
{
return $this->cache->delete($id);
}
public function fetch($id, array $options = null)
{
return $this->cache->fetch($id);
}
public function save($id, $data, $lifeTime = false, array $options = null)
{
return $this->cache->save($id, $data, $lifeTime);
}
}
Guzzle-3.7.0/Guzzle/Cache/NullCacheAdapter.php 0000644 233176441610067500000001032 12155472567 022561 0 ustar dowling ANT\Domain Users cache = $cache;
}
public function contains($id, array $options = null)
{
return $this->cache->test($id);
}
public function delete($id, array $options = null)
{
return $this->cache->remove($id);
}
public function fetch($id, array $options = null)
{
return $this->cache->load($id);
}
public function save($id, $data, $lifeTime = false, array $options = null)
{
return $this->cache->save($data, $id, array(), $lifeTime);
}
}
Guzzle-3.7.0/Guzzle/Cache/Zf2CacheAdapter.php 0000644 233176441610067500000001627 12155472567 022322 0 ustar dowling ANT\Domain Users cache = $cache;
}
public function contains($id, array $options = null)
{
return $this->cache->hasItem($id);
}
public function delete($id, array $options = null)
{
return $this->cache->removeItem($id);
}
public function fetch($id, array $options = null)
{
return $this->cache->getItem($id);
}
public function save($id, $data, $lifeTime = false, array $options = null)
{
return $this->cache->setItem($id, $data);
}
}
Guzzle-3.7.0/Guzzle/Common/AbstractHasDispatcher.php 0000644 233176441610067500000002244 12155472567 024063 0 ustar dowling ANT\Domain Users eventDispatcher = $eventDispatcher;
return $this;
}
public function getEventDispatcher()
{
if (!$this->eventDispatcher) {
$this->eventDispatcher = new EventDispatcher();
}
return $this->eventDispatcher;
}
public function dispatch($eventName, array $context = array())
{
$this->getEventDispatcher()->dispatch($eventName, new Event($context));
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->getEventDispatcher()->addSubscriber($subscriber);
return $this;
}
}
Guzzle-3.7.0/Guzzle/Common/Collection.php 0000644 233176441610067500000026416 12155472567 021757 0 ustar dowling ANT\Domain Users 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(), array $defaults = array(), array $required = array())
{
$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);
}
public function count()
{
return count($this->data);
}
public function getIterator()
{
return new \ArrayIterator($this->data);
}
public function toArray()
{
return $this->data;
}
/**
* Removes all key value pairs
*
* @return Collection
*/
public function clear()
{
$this->data = array();
return $this;
}
/**
* Get all or a subset of matching key value pairs
*
* @param array $keys Pass an array of keys to retrieve only a subset of key value pairs
*
* @return array Returns an array of all matching key value pairs
*/
public function getAll(array $keys = null)
{
return $keys ? array_intersect_key($this->data, array_flip($keys)) : $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
*
* @return Collection Returns a reference to the object
*/
public function set($key, $value)
{
$this->data[$key] = $value;
return $this;
}
/**
* 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
*
* @return Collection Returns a reference to the object.
*/
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);
}
return $this;
}
/**
* Remove a specific key value pair
*
* @param string $key A key to remove
*
* @return Collection
*/
public function remove($key)
{
unset($this->data[$key]);
return $this;
}
/**
* 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);
}
/**
* Case insensitive search the keys in the collection
*
* @param string $key Key to search for
*
* @return bool|string Returns false if not found, otherwise returns the key
*/
public function keySearch($key)
{
foreach (array_keys($this->data) as $k) {
if (!strcasecmp($k, $key)) {
return $k;
}
}
return false;
}
/**
* 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);
}
/**
* Replace the data of the object with the value of an array
*
* @param array $data Associative array of data
*
* @return Collection Returns a reference to the object
*/
public function replace(array $data)
{
$this->data = $data;
return $this;
}
/**
* Add and merge in a Collection or array of key value pair data.
*
* @param Collection|array $data Associative array of key value pair data
*
* @return Collection Returns a reference to the object.
*/
public function merge($data)
{
foreach ($data as $key => $value) {
$this->add($key, $value);
}
return $this;
}
/**
* Over write 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
*
* @return self
*/
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;
}
}
return $this;
}
/**
* Returns a Collection containing all the elements of the collection after applying the callback function to each
* one. The Closure should accept three parameters: (string) $key, (string) $value, (array) $context and return a
* modified value
*
* @param \Closure $closure Closure to apply
* @param array $context Context to pass to the closure
* @param bool $static Set to TRUE to use the same class as the return rather than returning a Collection
*
* @return Collection
*/
public function map(\Closure $closure, array $context = array(), $static = true)
{
$collection = $static ? new static() : new self();
foreach ($this as $key => $value) {
$collection->add($key, $closure($key, $value, $context));
}
return $collection;
}
/**
* Iterates over each key value pair in the collection passing them to the Closure. If the Closure function returns
* true, the current value from input is returned into the result Collection. The Closure must accept three
* parameters: (string) $key, (string) $value and return Boolean TRUE or FALSE for each value.
*
* @param \Closure $closure Closure evaluation function
* @param bool $static Set to TRUE to use the same class as the return rather than returning a Collection
*
* @return Collection
*/
public function filter(\Closure $closure, $static = true)
{
$collection = ($static) ? new static() : new self();
foreach ($this->data as $key => $value) {
if ($closure($key, $value)) {
$collection->add($key, $value);
}
}
return $collection;
}
public function offsetExists($offset)
{
return isset($this->data[$offset]);
}
public function offsetGet($offset)
{
return isset($this->data[$offset]) ? $this->data[$offset] : null;
}
public function offsetSet($offset, $value)
{
$this->data[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->data[$offset]);
}
/**
* 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
*
* @return self
* @throws RuntimeException when trying to setPath using a nested path that travels through a scalar value
*/
public function setPath($path, $value)
{
$current =& $this->data;
$queue = explode('/', $path);
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) {
$current[$key] = $value;
} elseif (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = array();
$current =& $current[$key];
}
}
return $this;
}
/**
* Gets a value from the collection using an array path (e.g. foo/baz/bar would retrieve bar from two nested arrays)
* Allows for wildcard searches which recursively combine matches up to the level at which the wildcard occurs. This
* can be useful for accepting any key of a sub-array and combining matching keys from each diverging path.
*
* @param string $path Path to traverse and retrieve a value from
* @param string $separator Character used to add depth to the search
* @param mixed $data Optional data to descend into (used when wildcards are encountered)
*
* @return mixed|null
*/
public function getPath($path, $separator = '/', $data = null)
{
if ($data === null) {
$data =& $this->data;
}
$path = is_array($path) ? $path : explode($separator, $path);
while (null !== ($part = array_shift($path))) {
if (!is_array($data)) {
return null;
} elseif (isset($data[$part])) {
$data =& $data[$part];
} elseif ($part != '*') {
return null;
} else {
// Perform a wildcard search by diverging and merging paths
$result = array();
foreach ($data as $value) {
if (!$path) {
$result = array_merge_recursive($result, (array) $value);
} elseif (null !== ($test = $this->getPath($path, $separator, $value))) {
$result = array_merge_recursive($result, (array) $test);
}
}
return $result;
}
}
return $data;
}
/**
* Inject configuration settings into an input string
*
* @param string $input Input to inject
*
* @return string
* @deprecated
*/
public function inject($input)
{
Version::warn(__METHOD__ . ' is deprecated');
$replace = array();
foreach ($this->data as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
return strtr($input, $replace);
}
}
Guzzle-3.7.0/Guzzle/Common/Event.php 0000644 233176441610067500000002050 12155472567 020731 0 ustar dowling ANT\Domain Users context = $context;
}
public function getIterator()
{
return new \ArrayIterator($this->context);
}
public function offsetGet($offset)
{
return isset($this->context[$offset]) ? $this->context[$offset] : null;
}
public function offsetSet($offset, $value)
{
$this->context[$offset] = $value;
}
public function offsetExists($offset)
{
return isset($this->context[$offset]);
}
public function offsetUnset($offset)
{
unset($this->context[$offset]);
}
public function toArray()
{
return $this->context;
}
}
Guzzle-3.7.0/Guzzle/Common/FromConfigInterface.php 0000644 233176441610067500000000747 12155472567 023535 0 ustar dowling ANT\Domain Users exceptions = array();
foreach ($exceptions as $exception) {
$this->add($exception);
}
return $this;
}
/**
* Add exceptions to the collection
*
* @param ExceptionCollection|\Exception $e Exception to add
*
* @return ExceptionCollection;
*/
public function add($e)
{
if ($this->message) {
$this->message .= "\n";
}
if ($e instanceof self) {
$this->message .= '(' . get_class($e) . ")";
foreach (explode("\n", $e->getMessage()) as $message) {
$this->message .= "\n {$message}";
}
} elseif ($e instanceof \Exception) {
$this->exceptions[] = $e;
$this->message .= '(' . get_class($e) . ') ' . $e->getMessage();
}
return $this;
}
/**
* Get the total number of request exceptions
*
* @return int
*/
public function count()
{
return count($this->exceptions);
}
/**
* Allows array-like iteration over the request exceptions
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->exceptions);
}
/**
* Get the first exception in the collection
*
* @return \Exception
*/
public function getFirst()
{
return $this->exceptions ? $this->exceptions[0] : null;
}
}
Guzzle-3.7.0/Guzzle/Common/Exception/GuzzleException.php 0000644 233176441610067500000000144 12155472567 024747 0 ustar dowling ANT\Domain Users body = $body;
}
public function __toString()
{
return (string) $this->body;
}
/**
* 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)
{
return call_user_func_array(array($this->body, $method), $args);
}
public function close()
{
return $this->body->close();
}
public function setRewindFunction($callable)
{
$this->body->setRewindFunction($callable);
return $this;
}
public function rewind()
{
return $this->body->rewind();
}
public function compress($filter = 'zlib.deflate')
{
return $this->body->compress($filter);
}
public function uncompress($filter = 'zlib.inflate')
{
return $this->body->uncompress($filter);
}
public function getContentLength()
{
return $this->getSize();
}
public function getContentType()
{
return $this->body->getContentType();
}
public function getContentMd5($rawOutput = false, $base64Encode = false)
{
$hash = Stream::getHash($this, 'md5', $rawOutput);
return $hash && $base64Encode ? base64_encode($hash) : $hash;
}
public function getContentEncoding()
{
return $this->body->getContentEncoding();
}
public function getMetaData($key = null)
{
return $this->body->getMetaData($key);
}
public function getStream()
{
return $this->body->getStream();
}
public function setStream($stream, $size = 0)
{
$this->body->setStream($stream, $size);
return $this;
}
public function detachStream()
{
$this->body->detachStream();
return $this;
}
public function getWrapper()
{
return $this->body->getWrapper();
}
public function getWrapperData()
{
return $this->body->getWrapperData();
}
public function getStreamType()
{
return $this->body->getStreamType();
}
public function getUri()
{
return $this->body->getUri();
}
public function getSize()
{
return $this->body->getSize();
}
public function isReadable()
{
return $this->body->isReadable();
}
public function isRepeatable()
{
return $this->isSeekable() && $this->isReadable();
}
public function isWritable()
{
return $this->body->isWritable();
}
public function isConsumed()
{
return $this->body->isConsumed();
}
/**
* Alias of isConsumed()
* {@inheritdoc}
*/
public function feof()
{
return $this->isConsumed();
}
public function isLocal()
{
return $this->body->isLocal();
}
public function isSeekable()
{
return $this->body->isSeekable();
}
public function setSize($size)
{
$this->body->setSize($size);
return $this;
}
public function seek($offset, $whence = SEEK_SET)
{
return $this->body->seek($offset, $whence);
}
public function read($length)
{
return $this->body->read($length);
}
public function write($string)
{
return $this->body->write($string);
}
public function readLine($maxLength = null)
{
return $this->body->readLine($maxLength);
}
public function ftell()
{
return $this->body->ftell();
}
public function getCustomData($key)
{
return $this->body->getCustomData($key);
}
public function setCustomData($key, $value)
{
$this->body->setCustomData($key, $value);
return $this;
}
}
Guzzle-3.7.0/Guzzle/Http/CachingEntityBody.php 0000644 233176441610067500000014172 12155472567 022716 0 ustar dowling ANT\Domain Users remoteStream = $body;
$this->body = new EntityBody(fopen('php://temp', 'r+'));
}
/**
* Will give the contents of the buffer followed by the exhausted remote stream.
*
* Warning: Loads the entire stream into memory
*
* @return string
*/
public function __toString()
{
$pos = $this->ftell();
$this->rewind();
$str = '';
while (!$this->isConsumed()) {
$str .= $this->read(16384);
}
$this->seek($pos);
return $str;
}
public function getSize()
{
return max($this->body->getSize(), $this->remoteStream->getSize());
}
/**
* {@inheritdoc}
* @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)
{
if ($whence == SEEK_SET) {
$byte = $offset;
} elseif ($whence == SEEK_CUR) {
$byte = $offset + $this->ftell();
} else {
throw new RuntimeException(__CLASS__ . ' supports only SEEK_SET and SEEK_CUR seek operations');
}
// You cannot skip ahead past where you've read from the remote stream
if ($byte > $this->body->getSize()) {
throw new RuntimeException(
"Cannot seek to byte {$byte} when the buffered stream only contains {$this->body->getSize()} bytes"
);
}
return $this->body->seek($byte);
}
public function rewind()
{
return $this->seek(0);
}
/**
* Does not support custom rewind functions
*
* @throws RuntimeException
*/
public function setRewindFunction($callable)
{
throw new RuntimeException(__CLASS__ . ' does not support custom stream rewind functions');
}
public function read($length)
{
// Perform a regular read on any previously read data from the buffer
$data = $this->body->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->body->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->ftell()) - $this->remoteStream->ftell();
if ($overflow > 0) {
$this->skipReadBytes += $overflow;
}
return $this->body->write($string);
}
/**
* {@inheritdoc}
* @link http://php.net/manual/en/function.fgets.php
*/
public function readLine($maxLength = null)
{
$buffer = '';
$size = 0;
while (!$this->isConsumed()) {
$byte = $this->read(1);
$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;
}
public function isConsumed()
{
return $this->body->isConsumed() && $this->remoteStream->isConsumed();
}
/**
* Close both the remote stream and buffer stream
*/
public function close()
{
return $this->remoteStream->close() && $this->body->close();
}
public function setStream($stream, $size = 0)
{
$this->remoteStream->setStream($stream, $size);
}
public function getContentType()
{
return $this->remoteStream->getContentType();
}
public function getContentEncoding()
{
return $this->remoteStream->getContentEncoding();
}
public function getMetaData($key = null)
{
return $this->remoteStream->getMetaData($key);
}
public function getStream()
{
return $this->remoteStream->getStream();
}
public function getWrapper()
{
return $this->remoteStream->getWrapper();
}
public function getWrapperData()
{
return $this->remoteStream->getWrapperData();
}
public function getStreamType()
{
return $this->remoteStream->getStreamType();
}
public function getUri()
{
return $this->remoteStream->getUri();
}
/**
* Always retrieve custom data from the remote stream
* {@inheritdoc}
*/
public function getCustomData($key)
{
return $this->remoteStream->getCustomData($key);
}
/**
* Always set custom data on the remote stream
* {@inheritdoc}
*/
public function setCustomData($key, $value)
{
$this->remoteStream->setCustomData($key, $value);
return $this;
}
}
Guzzle-3.7.0/Guzzle/Http/Client.php 0000644 233176441610067500000040470 12155472567 020565 0 ustar dowling ANT\Domain Users setConfig($config ?: new Collection());
$this->initSsl();
$this->setBaseUrl($baseUrl);
$this->defaultHeaders = new Collection();
$this->setRequestFactory(RequestFactory::getInstance());
$this->userAgent = $this->getDefaultUserAgent();
if (!$this->config[self::DISABLE_REDIRECTS]) {
$this->addSubscriber(new RedirectPlugin());
}
}
final public function setConfig($config)
{
if ($config instanceof Collection) {
$this->config = $config;
} elseif (is_array($config)) {
$this->config = new Collection($config);
} else {
throw new InvalidArgumentException('Config must be an array or Collection');
}
return $this;
}
final public function getConfig($key = false)
{
return $key ? $this->config[$key] : $this->config;
}
/**
* Set a default request option on the client that will be used as a default for each request
*
* @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo)
* @param mixed $value Value to set
*
* @return $this
*/
public function setDefaultOption($keyOrPath, $value)
{
if (strpos($keyOrPath, '/')) {
$this->config->setPath($keyOrPath, $value);
} else {
$this->config[$keyOrPath] = $value;
}
return $this;
}
/**
* Retrieve a default request option from the client
*
* @param string $keyOrPath request.options key (e.g. allow_redirects) or path to a nested key (e.g. headers/foo)
*
* @return mixed|null
*/
public function getDefaultOption($keyOrPath)
{
return strpos($keyOrPath, '/') ? $this->config->getPath($keyOrPath) : $this->config[$keyOrPath];
}
final public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2)
{
$opts = $this->config[self::CURL_OPTIONS] ?: array();
if ($certificateAuthority === true) {
// use bundled CA bundle, set secure defaults
$opts[CURLOPT_CAINFO] = __DIR__ . '/Resources/cacert.pem';
$opts[CURLOPT_SSL_VERIFYPEER] = true;
$opts[CURLOPT_SSL_VERIFYHOST] = 2;
} elseif ($certificateAuthority === false) {
unset($opts[CURLOPT_CAINFO]);
$opts[CURLOPT_SSL_VERIFYPEER] = false;
$opts[CURLOPT_SSL_VERIFYHOST] = 2;
} elseif ($verifyPeer !== true && $verifyPeer !== false && $verifyPeer !== 1 && $verifyPeer !== 0) {
throw new InvalidArgumentException('verifyPeer must be 1, 0 or boolean');
} elseif ($verifyHost !== 0 && $verifyHost !== 1 && $verifyHost !== 2) {
throw new InvalidArgumentException('verifyHost must be 0, 1 or 2');
} else {
$opts[CURLOPT_SSL_VERIFYPEER] = $verifyPeer;
$opts[CURLOPT_SSL_VERIFYHOST] = $verifyHost;
if (is_file($certificateAuthority)) {
unset($opts[CURLOPT_CAPATH]);
$opts[CURLOPT_CAINFO] = $certificateAuthority;
} elseif (is_dir($certificateAuthority)) {
unset($opts[CURLOPT_CAINFO]);
$opts[CURLOPT_CAPATH] = $certificateAuthority;
} else {
throw new RuntimeException(
'Invalid option passed to ' . self::SSL_CERT_AUTHORITY . ': ' . $certificateAuthority
);
}
}
$this->config->set(self::CURL_OPTIONS, $opts);
return $this;
}
public function createRequest($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array())
{
if (!$uri) {
$url = $this->getBaseUrl();
} else {
if (!is_array($uri)) {
$templateVars = null;
} else {
list($uri, $templateVars) = $uri;
}
if (substr($uri, 0, 4) === 'http') {
// Use absolute URLs as-is
$url = $this->expandTemplate($uri, $templateVars);
} else {
$url = Url::factory($this->getBaseUrl())->combine($this->expandTemplate($uri, $templateVars));
}
}
// If default headers are provided, then merge them under any explicitly provided headers for the request
if (count($this->defaultHeaders)) {
if (!$headers) {
$headers = $this->defaultHeaders->toArray();
} elseif (is_array($headers)) {
$headers += $this->defaultHeaders->toArray();
} elseif ($headers instanceof Collection) {
$headers = $headers->toArray() + $this->defaultHeaders->toArray();
}
}
return $this->prepareRequest($this->requestFactory->create($method, (string) $url, $headers, $body), $options);
}
public function getBaseUrl($expand = true)
{
return $expand ? $this->expandTemplate($this->baseUrl) : $this->baseUrl;
}
public function setBaseUrl($url)
{
$this->baseUrl = $url;
return $this;
}
public function setUserAgent($userAgent, $includeDefault = false)
{
if ($includeDefault) {
$userAgent .= ' ' . $this->getDefaultUserAgent();
}
$this->userAgent = $userAgent;
return $this;
}
/**
* Get the default User-Agent string to use with Guzzle
*
* @return string
*/
public function getDefaultUserAgent()
{
return 'Guzzle/' . Version::VERSION
. ' curl/' . CurlVersion::getInstance()->get('version')
. ' PHP/' . PHP_VERSION;
}
public function get($uri = null, $headers = null, $options = array())
{
// BC compat: $options can be a string, resource, etc to specify where the response body is downloaded
return is_array($options)
? $this->createRequest('GET', $uri, $headers, null, $options)
: $this->createRequest('GET', $uri, $headers, $options);
}
public function head($uri = null, $headers = null, array $options = array())
{
return $this->createRequest('HEAD', $uri, $headers, $options);
}
public function delete($uri = null, $headers = null, $body = null, array $options = array())
{
return $this->createRequest('DELETE', $uri, $headers, $body, $options);
}
public function put($uri = null, $headers = null, $body = null, array $options = array())
{
return $this->createRequest('PUT', $uri, $headers, $body, $options);
}
public function patch($uri = null, $headers = null, $body = null, array $options = array())
{
return $this->createRequest('PATCH', $uri, $headers, $body, $options);
}
public function post($uri = null, $headers = null, $postBody = null, array $options = array())
{
return $this->createRequest('POST', $uri, $headers, $postBody, $options);
}
public function options($uri = null, array $options = array())
{
return $this->createRequest('OPTIONS', $uri, $options);
}
public function send($requests)
{
if (!($requests instanceof RequestInterface)) {
return $this->sendMultiple($requests);
}
try {
/** @var $requests RequestInterface */
$this->getCurlMulti()->add($requests)->send();
return $requests->getResponse();
} catch (ExceptionCollection $e) {
throw $e->getFirst();
}
}
/**
* Set a curl multi object to be used internally by the client for transferring requests.
*
* @param CurlMultiInterface $curlMulti Multi object
*
* @return self
*/
public function setCurlMulti(CurlMultiInterface $curlMulti)
{
$this->curlMulti = $curlMulti;
return $this;
}
/**
* @return CurlMultiInterface|CurlMultiProxy
*/
public function getCurlMulti()
{
if (!$this->curlMulti) {
$this->curlMulti = new CurlMultiProxy();
}
return $this->curlMulti;
}
public function setRequestFactory(RequestFactoryInterface $factory)
{
$this->requestFactory = $factory;
return $this;
}
/**
* Set the URI template expander to use with the client
*
* @param UriTemplateInterface $uriTemplate URI template expander
*
* @return self
*/
public function setUriTemplate(UriTemplateInterface $uriTemplate)
{
$this->uriTemplate = $uriTemplate;
return $this;
}
/**
* Copy the cacert.pem file from the phar if it is not in the temp folder and validate the MD5 checksum
*
* @param bool $md5Check Set to false to not perform the MD5 validation
*
* @return string Returns the path to the extracted cacert
* @throws RuntimeException if the file cannot be copied or there is a MD5 mismatch
*/
public function preparePharCacert($md5Check = true)
{
$from = __DIR__ . '/Resources/cacert.pem';
$certFile = sys_get_temp_dir() . '/guzzle-cacert.pem';
if (!file_exists($certFile) && !copy($from, $certFile)) {
throw new RuntimeException("Could not copy {$from} to {$certFile}: " . var_export(error_get_last(), true));
} elseif ($md5Check) {
$actualMd5 = md5_file($certFile);
$expectedMd5 = trim(file_get_contents("{$from}.md5"));
if ($actualMd5 != $expectedMd5) {
throw new RuntimeException("{$certFile} MD5 mismatch: expected {$expectedMd5} but got {$actualMd5}");
}
}
return $certFile;
}
/**
* Expand a URI template while merging client config settings into the template variables
*
* @param string $template Template to expand
* @param array $variables Variables to inject
*
* @return string
*/
protected function expandTemplate($template, array $variables = null)
{
$expansionVars = $this->getConfig()->toArray();
if ($variables) {
$expansionVars = $variables + $expansionVars;
}
return $this->getUriTemplate()->expand($template, $expansionVars);
}
/**
* Get the URI template expander used by the client
*
* @return UriTemplateInterface
*/
protected function getUriTemplate()
{
if (!$this->uriTemplate) {
$this->uriTemplate = ParserRegistry::getInstance()->getParser('uri_template');
}
return $this->uriTemplate;
}
/**
* Send multiple requests in parallel
*
* @param array $requests Array of RequestInterface objects
*
* @return array Returns an array of Response objects
*/
protected function sendMultiple(array $requests)
{
$curlMulti = $this->getCurlMulti();
foreach ($requests as $request) {
$curlMulti->add($request);
}
$curlMulti->send();
/** @var $request RequestInterface */
$result = array();
foreach ($requests as $request) {
$result[] = $request->getResponse();
}
return $result;
}
/**
* Prepare a request to be sent from the Client by adding client specific behaviors and properties to the request.
*
* @param RequestInterface $request Request to prepare for the client
* @param array $options Options to apply to the request
*
* @return RequestInterface
*/
protected function prepareRequest(RequestInterface $request, array $options = array())
{
$request->setClient($this)->setEventDispatcher(clone $this->getEventDispatcher());
if ($curl = $this->config[self::CURL_OPTIONS]) {
$request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($curl));
}
if ($params = $this->config[self::REQUEST_PARAMS]) {
Version::warn('request.params is deprecated. Use request.options to add default request options.');
$request->getParams()->overwriteWith($params);
}
if ($this->userAgent && !$request->hasHeader('User-Agent')) {
$request->setHeader('User-Agent', $this->userAgent);
}
if ($defaults = $this->config[self::REQUEST_OPTIONS]) {
$this->requestFactory->applyOptions($request, $defaults, RequestFactoryInterface::OPTIONS_AS_DEFAULTS);
}
if ($options) {
$this->requestFactory->applyOptions($request, $options);
}
$this->dispatch('client.create_request', array('client' => $this, 'request' => $request));
return $request;
}
/**
* Initializes SSL settings
*/
protected function initSsl()
{
if ('system' == ($authority = $this->config[self::SSL_CERT_AUTHORITY])) {
return;
}
if ($authority === null) {
$authority = true;
}
if ($authority === true && substr(__FILE__, 0, 7) == 'phar://') {
$authority = $this->preparePharCacert();
$that = $this;
$this->getEventDispatcher()->addListener('request.before_send', function ($event) use ($authority, $that) {
if ($authority == $event['request']->getCurlOptions()->get(CURLOPT_CAINFO)) {
$that->preparePharCacert(false);
}
});
}
$this->setSslVerification($authority);
}
/**
* @deprecated
*/
public function getDefaultHeaders()
{
Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to retrieve default request options');
return $this->defaultHeaders;
}
/**
* @deprecated
*/
public function setDefaultHeaders($headers)
{
Version::warn(__METHOD__ . ' is deprecated. Use the request.options array to specify default request options');
if ($headers instanceof Collection) {
$this->defaultHeaders = $headers;
} elseif (is_array($headers)) {
$this->defaultHeaders = new Collection($headers);
} else {
throw new InvalidArgumentException('Headers must be an array or Collection');
}
return $this;
}
}
Guzzle-3.7.0/Guzzle/Http/ClientInterface.php 0000644 233176441610067500000023301 12155472567 022400 0 ustar dowling ANT\Domain Users rewindFunction = $callable;
return $this;
}
public function rewind()
{
return $this->rewindFunction ? call_user_func($this->rewindFunction, $this) : parent::rewind();
}
/**
* Create a new EntityBody from a string
*
* @param string $string String of data
*
* @return EntityBody
*/
public static function fromString($string)
{
$stream = fopen('php://temp', 'r+');
if ($string !== '') {
fwrite($stream, $string);
rewind($stream);
}
return new static($stream);
}
public function compress($filter = 'zlib.deflate')
{
$result = $this->handleCompression($filter);
$this->contentEncoding = $result ? $filter : false;
return $result;
}
public function uncompress($filter = 'zlib.inflate')
{
$offsetStart = 0;
// When inflating gzipped data, the first 10 bytes must be stripped
// if a gzip header is present
if ($filter == 'zlib.inflate') {
// @codeCoverageIgnoreStart
if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
return false;
}
// @codeCoverageIgnoreEnd
if (stream_get_contents($this->stream, 3, 0) === "\x1f\x8b\x08") {
$offsetStart = 10;
}
}
$this->contentEncoding = false;
return $this->handleCompression($filter, $offsetStart);
}
public function getContentLength()
{
return $this->getSize();
}
public function getContentType()
{
return $this->getUri() ? Mimetypes::getInstance()->fromFilename($this->getUri()) : null;
}
public function getContentMd5($rawOutput = false, $base64Encode = false)
{
$hash = self::getHash($this, 'md5', $rawOutput);
return $hash && $base64Encode ? base64_encode($hash) : $hash;
}
/**
* Calculate the MD5 hash of an entity body
*
* @param EntityBodyInterface $body Entity body to calculate the hash for
* @param bool $rawOutput Whether or not to use raw output
* @param bool $base64Encode Whether or not to base64 encode raw output (only if raw output is true)
*
* @return bool|string Returns an MD5 string on success or FALSE on failure
* @deprecated This will be deprecated soon
* @codeCoverageIgnore
*/
public static function calculateMd5(EntityBodyInterface $body, $rawOutput = false, $base64Encode = false)
{
Version::warn(__CLASS__ . ' is deprecated. Use getContentMd5()');
return $body->getContentMd5($rawOutput, $base64Encode);
}
public function setStreamFilterContentEncoding($streamFilterContentEncoding)
{
$this->contentEncoding = $streamFilterContentEncoding;
return $this;
}
public function getContentEncoding()
{
return strtr($this->contentEncoding, array(
'zlib.deflate' => 'gzip',
'bzip2.compress' => 'compress'
)) ?: false;
}
protected function handleCompression($filter, $offsetStart = 0)
{
// @codeCoverageIgnoreStart
if (!$this->isReadable() || ($this->isConsumed() && !$this->isSeekable())) {
return false;
}
// @codeCoverageIgnoreEnd
$handle = fopen('php://temp', 'r+');
$filter = @stream_filter_append($handle, $filter, STREAM_FILTER_WRITE);
if (!$filter) {
return false;
}
// Seek to the offset start if possible
$this->seek($offsetStart);
while ($data = fread($this->stream, 8096)) {
fwrite($handle, $data);
}
fclose($this->stream);
$this->stream = $handle;
stream_filter_remove($filter);
$stat = fstat($this->stream);
$this->size = $stat['size'];
$this->rebuildCache();
$this->seek(0);
// Remove any existing rewind function as the underlying stream has been replaced
$this->rewindFunction = null;
return true;
}
}
Guzzle-3.7.0/Guzzle/Http/EntityBodyInterface.php 0000644 233176441610067500000004563 12155472567 023265 0 ustar dowling ANT\Domain Users eventDispatcher = $eventDispatcher;
return $this;
}
public function getEventDispatcher()
{
if (!$this->eventDispatcher) {
$this->eventDispatcher = new EventDispatcher();
}
return $this->eventDispatcher;
}
public function dispatch($eventName, array $context = array())
{
$this->getEventDispatcher()->dispatch($eventName, new Event($context));
}
/**
* {@inheritdoc}
* @codeCoverageIgnore
*/
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->getEventDispatcher()->addSubscriber($subscriber);
return $this;
}
public function read($length)
{
$event = array(
'body' => $this,
'length' => $length,
'read' => $this->body->read($length)
);
$this->dispatch('body.read', $event);
return $event['read'];
}
public function write($string)
{
$event = array(
'body' => $this,
'write' => $string,
'result' => $this->body->write($string)
);
$this->dispatch('body.write', $event);
return $event['result'];
}
}
Guzzle-3.7.0/Guzzle/Http/Mimetypes.php 0000644 233176441610067500000122133 12155472567 021320 0 ustar dowling ANT\Domain Users '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)
{
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));
}
}
Guzzle-3.7.0/Guzzle/Http/QueryString.php 0000644 233176441610067500000016560 12155472567 021646 0 ustar dowling ANT\Domain Users hasKey($key)) {
$value = array($value);
}
$q->add($key, $value);
} else {
$q->add($key, null);
}
}
}
return $q;
}
/**
* Convert the query string parameters to a query string string
*
* @return string
*/
public function __toString()
{
if (!$this->data) {
return '';
}
$queryString = '';
foreach ($this->prepareData($this->data) as $name => $value) {
foreach ((array) $value as $v) {
if ($queryString) {
$queryString .= $this->fieldSeparator;
}
$queryString .= $name;
if ($v !== self::BLANK) {
$queryString .= $this->valueSeparator . $v;
}
}
}
return $queryString;
}
/**
* Get the query string field separator
*
* @return string
*/
public function getFieldSeparator()
{
return $this->fieldSeparator;
}
/**
* Get the query string value separator
*
* @return string
*/
public function getValueSeparator()
{
return $this->valueSeparator;
}
/**
* Returns the type of URL encoding used by the query string
*
* One of: false, "RFC 3986", or "application/x-www-form-urlencoded"
*
* @return bool|string
*/
public function getUrlEncoding()
{
return $this->urlEncode;
}
/**
* Returns true or false if using URL encoding
*
* @return bool
*/
public function isUrlEncoding()
{
return $this->urlEncode !== false;
}
/**
* Provide a function for combining multi-valued query string parameters into a single or multiple fields
*
* @param null|QueryAggregatorInterface $aggregator Pass in a QueryAggregatorInterface object to handle converting
* deeply nested query string variables into a flattened array.
* Pass null to use the default PHP style aggregator. For legacy
* reasons, this function accepts a callable that must accepts a
* $key, $value, and query object.
* @return self
* @see \Guzzle\Http\QueryString::aggregateUsingComma()
*/
public function setAggregator(QueryAggregatorInterface $aggregator = null)
{
// Use the default aggregator if none was set
if (!$aggregator) {
if (!self::$defaultAggregator) {
self::$defaultAggregator = new PhpAggregator();
}
$aggregator = self::$defaultAggregator;
}
$this->aggregator = $aggregator;
return $this;
}
/**
* Set whether or not field names and values should be rawurlencoded
*
* @param bool|string $encode Set to TRUE to use RFC 3986 encoding (rawurlencode), false to disable encoding, or
* form_urlencoding to use application/x-www-form-urlencoded encoding (urlencode)
* @return self
*/
public function useUrlEncoding($encode)
{
$this->urlEncode = ($encode === true) ? self::RFC_3986 : $encode;
return $this;
}
/**
* Set the query string separator
*
* @param string $separator The query string separator that will separate fields
*
* @return self
*/
public function setFieldSeparator($separator)
{
$this->fieldSeparator = $separator;
return $this;
}
/**
* Set the query string value separator
*
* @param string $separator The query string separator that will separate values from fields
*
* @return self
*/
public function setValueSeparator($separator)
{
$this->valueSeparator = $separator;
return $this;
}
/**
* Returns an array of url encoded field names and values
*
* @return array
*/
public function urlEncode()
{
return $this->prepareData($this->data);
}
/**
* URL encodes a value based on the url encoding type of the query string object
*
* @param string $value Value to encode
*
* @return string
*/
public function encodeValue($value)
{
if ($this->urlEncode == self::RFC_3986) {
return rawurlencode($value);
} elseif ($this->urlEncode == self::FORM_URLENCODED) {
return urlencode($value);
} else {
return (string) $value;
}
}
/**
* Url encode parameter data and convert nested query strings into a flattened hash.
*
* @param array $data The data to encode
*
* @return array Returns an array of encoded values and keys
*/
protected function prepareData(array $data)
{
// If no aggregator is present then set the default
if (!$this->aggregator) {
$this->setAggregator(null);
}
$temp = array();
foreach ($data as $key => $value) {
if (is_array($value)) {
$temp = array_merge($temp, $this->aggregator->aggregate($key, $value, $this));
} else {
$temp[$this->encodeValue($key)] = $this->encodeValue($value);
}
}
return $temp;
}
}
Guzzle-3.7.0/Guzzle/Http/ReadLimitEntityBody.php 0000644 233176441610067500000005642 12155472567 023236 0 ustar dowling ANT\Domain Users setLimit($limit)->setOffset($offset);
$this->body->seek($offset);
}
/**
* Returns only a subset of the decorated entity body when cast as a string
* {@inheritdoc}
*/
public function __toString()
{
return substr((string) $this->body, $this->offset, $this->limit) ?: '';
}
public function isConsumed()
{
return (($this->offset + $this->limit) - $this->body->ftell()) <= 0;
}
/**
* Returns the Content-Length of the limited subset of data
* {@inheritdoc}
*/
public function getContentLength()
{
$length = $this->body->getContentLength();
return $length === false
? $this->limit
: min($this->limit, min($length, $this->offset + $this->limit) - $this->offset);
}
/**
* Allow for a bounded seek on the read limited entity body
* {@inheritdoc}
*/
public function seek($offset, $whence = SEEK_SET)
{
return $whence === SEEK_SET
? $this->body->seek(max($this->offset, min($this->offset + $this->limit, $offset)))
: false;
}
/**
* Set the offset to start limiting from
*
* @param int $offset Offset to seek to and begin byte limiting from
*
* @return self
*/
public function setOffset($offset)
{
$this->body->seek($offset);
$this->offset = $offset;
return $this;
}
/**
* Set the limit of bytes that the decorator allows to be read from the stream
*
* @param int $limit Total number of bytes to allow to be read from the stream
*
* @return self
*/
public function setLimit($limit)
{
$this->limit = $limit;
return $this;
}
public function read($length)
{
// Check if the current position is less than the total allowed bytes + original offset
$remaining = ($this->offset + $this->limit) - $this->body->ftell();
if ($remaining > 0) {
// Only return the amount of requested data, ensuring that the byte limit is not exceeded
return $this->body->read(min($remaining, $length));
} else {
return false;
}
}
}
Guzzle-3.7.0/Guzzle/Http/RedirectPlugin.php 0000644 233176441610067500000023415 12155472567 022267 0 ustar dowling ANT\Domain Users array('onRequestSent', 100),
'request.clone' => 'cleanupRequest',
'request.before_send' => 'cleanupRequest'
);
}
/**
* Clean up the parameters of a request when it is cloned
*
* @param Event $event Event emitted
*/
public function cleanupRequest(Event $event)
{
$params = $event['request']->getParams();
unset($params[self::REDIRECT_COUNT]);
unset($params[self::PARENT_REQUEST]);
}
/**
* Called when a request receives a redirect response
*
* @param Event $event Event emitted
*/
public function onRequestSent(Event $event)
{
$response = $event['response'];
$request = $event['request'];
// Only act on redirect requests with Location headers
if (!$response || $request->getParams()->get(self::DISABLE)) {
return;
}
// Trace the original request based on parameter history
$original = $this->getOriginalRequest($request);
// Terminating condition to set the effective repsonse on the original request
if (!$response->isRedirect() || !$response->hasHeader('Location')) {
if ($request !== $original) {
// This is a terminating redirect response, so set it on the original request
$response->getParams()->set(self::REDIRECT_COUNT, $original->getParams()->get(self::REDIRECT_COUNT));
$original->setResponse($response);
$response->setEffectiveUrl($request->getUrl());
}
return;
}
$this->sendRedirectRequest($original, $request, $response);
}
/**
* Get the original request that initiated a series of redirects
*
* @param RequestInterface $request Request to get the original request from
*
* @return RequestInterface
*/
protected function getOriginalRequest(RequestInterface $request)
{
$original = $request;
// The number of redirects is held on the original request, so determine which request that is
while ($parent = $original->getParams()->get(self::PARENT_REQUEST)) {
$original = $parent;
}
return $original;
}
/**
* Create a redirect request for a specific request object
*
* Takes into account strict RFC compliant redirection (e.g. redirect POST with POST) vs doing what most clients do
* (e.g. redirect POST with GET).
*
* @param RequestInterface $request Request being redirected
* @param RequestInterface $original Original request
* @param int $statusCode Status code of the redirect
* @param string $location Location header of the redirect
*
* @return RequestInterface Returns a new redirect request
* @throws CouldNotRewindStreamException If the body needs to be rewound but cannot
*/
protected function createRedirectRequest(
RequestInterface $request,
$statusCode,
$location,
RequestInterface $original
) {
$redirectRequest = null;
$strict = $original->getParams()->get(self::STRICT_REDIRECTS);
// 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
if ($request instanceof EntityEnclosingRequestInterface && !$strict && $statusCode <= 302) {
$redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET');
} else {
$redirectRequest = clone $request;
}
$redirectRequest->setIsRedirect(true);
// Always use the same response body when redirecting
$redirectRequest->setResponseBody($request->getResponseBody());
$location = Url::factory($location);
// If the location is not absolute, then combine it with the original URL
if (!$location->isAbsolute()) {
$originalUrl = $redirectRequest->getUrl(true);
// Remove query string parameters and just take what is present on the redirect Location header
$originalUrl->getQuery()->clear();
$location = $originalUrl->combine((string) $location);
}
$redirectRequest->setUrl($location);
// Add the parent request to the request before it sends (make sure it's before the onRequestClone event too)
$redirectRequest->getEventDispatcher()->addListener(
'request.before_send',
$func = function ($e) use (&$func, $request, $redirectRequest) {
$redirectRequest->getEventDispatcher()->removeListener('request.before_send', $func);
$e['request']->getParams()->set(RedirectPlugin::PARENT_REQUEST, $request);
}
);
// Rewind the entity body of the request if needed
if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) {
$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->ftell() && !$body->rewind()) {
throw new CouldNotRewindStreamException(
'Unable to rewind the non-seekable entity body of the request after redirecting. cURL probably '
. 'sent part of body before the redirect occurred. Try adding acustom rewind function using on the '
. 'entity body of the request using setRewindFunction().'
);
}
}
return $redirectRequest;
}
/**
* Prepare the request for redirection and enforce the maximum number of allowed redirects per client
*
* @param RequestInterface $original Origina request
* @param RequestInterface $request Request to prepare and validate
* @param Response $response The current response
*
* @return RequestInterface
*/
protected function prepareRedirection(RequestInterface $original, RequestInterface $request, Response $response)
{
$params = $original->getParams();
// This is a new redirect, so increment the redirect counter
$current = $params[self::REDIRECT_COUNT] + 1;
$params[self::REDIRECT_COUNT] = $current;
// Use a provided maximum value or default to a max redirect count of 5
$max = isset($params[self::MAX_REDIRECTS]) ? $params[self::MAX_REDIRECTS] : $this->defaultMaxRedirects;
// Throw an exception if the redirect count is exceeded
if ($current > $max) {
$this->throwTooManyRedirectsException($original, $max);
return false;
} else {
// Create a redirect request based on the redirect rules set on the request
return $this->createRedirectRequest(
$request,
$response->getStatusCode(),
trim($response->getLocation()),
$original
);
}
}
/**
* Send a redirect request and handle any errors
*
* @param RequestInterface $original The originating request
* @param RequestInterface $request The current request being redirected
* @param Response $response The response of the current request
*
* @throws BadResponseException|\Exception
*/
protected function sendRedirectRequest(RequestInterface $original, RequestInterface $request, Response $response)
{
// Validate and create a redirect request based on the original request and current response
if ($redirectRequest = $this->prepareRedirection($original, $request, $response)) {
try {
$redirectRequest->send();
} catch (BadResponseException $e) {
$e->getResponse();
if (!$e->getResponse()) {
throw $e;
}
}
}
}
/**
* Throw a too many redirects exception for a request
*
* @param RequestInterface $original Request
* @param int $max Max allowed redirects
*
* @throws TooManyRedirectsException when too many redirects have been issued
*/
protected function throwTooManyRedirectsException(RequestInterface $original, $max)
{
$original->getEventDispatcher()->addListener(
'request.complete',
$func = function ($e) use (&$func, $original, $max) {
$original->getEventDispatcher()->removeListener('request.complete', $func);
$str = "{$max} redirects were issued for this request:\n" . $e['request']->getRawHeaders();
throw new TooManyRedirectsException($str);
}
);
}
}
Guzzle-3.7.0/Guzzle/Http/StaticClient.php 0000644 233176441610067500000011047 12155472567 021733 0 ustar dowling ANT\Domain Users createRequest($method, $url, null, null, $options);
if (isset($options['stream'])) {
if ($options['stream'] instanceof StreamRequestFactoryInterface) {
return $options['stream']->fromRequest($request);
} elseif ($options['stream'] == true) {
$streamFactory = new PhpStreamRequestFactory();
return $streamFactory->fromRequest($request);
}
}
return $request->send();
}
/**
* Send a GET request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function get($url, $options = array())
{
return self::request('GET', $url, $options);
}
/**
* Send a HEAD request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function head($url, $options = array())
{
return self::request('HEAD', $url, $options);
}
/**
* Send a DELETE request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function delete($url, $options = array())
{
return self::request('DELETE', $url, $options);
}
/**
* Send a POST request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function post($url, $options = array())
{
return self::request('POST', $url, $options);
}
/**
* Send a PUT request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function put($url, $options = array())
{
return self::request('PUT', $url, $options);
}
/**
* Send a PATCH request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function patch($url, $options = array())
{
return self::request('PATCH', $url, $options);
}
/**
* Send an OPTIONS request
*
* @param string $url URL of the request
* @param array $options Array of request options
*
* @return \Guzzle\Http\Message\Response
* @see Guzzle::request for a list of available options
*/
public static function options($url, $options = array())
{
return self::request('OPTIONS', $url, $options);
}
}
Guzzle-3.7.0/Guzzle/Http/Url.php 0000644 233176441610067500000032214 12155472567 020106 0 ustar dowling ANT\Domain Users null, 'host' => null, 'path' => null, 'port' => null, 'query' => null,
'user' => null, 'pass' => null, 'fragment' => null);
$parts = parse_url($url) + $defaults;
// Convert the query string into a QueryString object
if ($parts['query'] || 0 !== strlen($parts['query'])) {
$parts['query'] = QueryString::fromString($parts['query']);
}
return new self($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 (isset($parts['scheme'])) {
$scheme = $parts['scheme'];
$url .= $scheme . ':';
}
if (isset($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'])
&& !(($scheme == 'http' && $parts['port'] == 80) || ($scheme == 'https' && $parts['port'] == 443))
) {
$url .= ':' . $parts['port'];
}
}
// Add the path component if present
if (isset($parts['path']) && 0 !== strlen($parts['path'])) {
// Always ensure that the path begins with '/' if set and something is before the path
if ($url && $parts['path'][0] != '/' && substr($url, -1) != '/') {
$url .= '/';
}
$url .= $parts['path'];
}
// Add the query string if present
if (isset($parts['query'])) {
$url .= '?' . $parts['query'];
}
// 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 QueryString|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, QueryString $query = null, $fragment = null)
{
$this->scheme = $scheme;
$this->host = $host;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->fragment = $fragment;
if (!$query) {
$this->query = new QueryString();
} else {
$this->setQuery($query);
}
$this->setPath($path);
}
/**
* Clone the URL
*/
public function __clone()
{
$this->query = clone $this->query;
}
/**
* Returns the URL as a URL string
*
* @return string
*/
public function __toString()
{
return self::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->getPath(),
'query' => (string) $this->query ?: null,
'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);
}
return $this;
}
/**
* 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
*
* @return Url
*/
public function setScheme($scheme)
{
$this->scheme = $scheme;
return $this;
}
/**
* 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
*
* @return Url
*/
public function setPort($port)
{
$this->port = $port;
return $this;
}
/**
* Get the port part of the URl. Will return the default port for a given scheme if no port has been set.
*
* @return int|null
*/
public function getPort()
{
if ($this->port) {
return $this->port;
} elseif ($this->scheme == 'http') {
return 80;
} elseif ($this->scheme == 'https') {
return 443;
}
return null;
}
/**
* Set the path part of the URL
*
* @param array|string $path Path string or array of path segments
*
* @return Url
*/
public function setPath($path)
{
if (is_array($path)) {
$this->path = '/' . implode('/', $path);
} else {
$this->path = (string) $path;
}
return $this;
}
/**
* Normalize the URL so that double slashes and relative paths are removed
*
* @return Url
*/
public function normalizePath()
{
if (!$this->path || $this->path == '/' || $this->path == '*') {
return $this;
}
// Replace // and /./ with /
$this->path = str_replace(array('/./', '//'), '/', $this->path);
// Remove dot segments
if (strpos($this->path, '..') !== false) {
// Remove trailing relative paths if possible
$segments = $this->getPathSegments();
$last = end($segments);
$trailingSlash = false;
if ($last === '') {
array_pop($segments);
$trailingSlash = true;
}
while ($last == '..' || $last == '.') {
if ($last == '..') {
array_pop($segments);
$last = array_pop($segments);
}
if ($last == '.' || $last == '') {
$last = array_pop($segments);
}
}
$this->path = implode('/', $segments);
if ($trailingSlash) {
$this->path .= '/';
}
}
return $this;
}
/**
* Add a relative path to the currently set path
*
* @param string $relativePath Relative path to add
*
* @return Url
*/
public function addPath($relativePath)
{
if (!$relativePath || $relativePath == '/') {
return $this;
}
// Add a leading slash if needed
if ($relativePath[0] != '/') {
$relativePath = '/' . $relativePath;
}
return $this->setPath(str_replace('//', '/', $this->getPath() . $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 array_slice(explode('/', $this->getPath()), 1);
}
/**
* Set the password part of the URL
*
* @param string $password Password to set
*
* @return Url
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* 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
*
* @return Url
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* 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 QueryString object
*
* @return QueryString
*/
public function getQuery()
{
return $this->query;
}
/**
* Set the query part of the URL
*
* @param QueryString|string|array $query Query to set
*
* @return Url
*/
public function setQuery($query)
{
if (is_string($query)) {
$output = null;
parse_str($query, $output);
$this->query = new QueryString($output);
} elseif (is_array($query)) {
$this->query = new QueryString($query);
} elseif ($query instanceof QueryString) {
$this->query = $query;
}
return $this;
}
/**
* 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
*
* @return Url
*/
public function setFragment($fragment)
{
$this->fragment = $fragment;
return $this;
}
/**
* Check if this is an absolute URL
*
* @return bool
*/
public function isAbsolute()
{
return $this->scheme && $this->host;
}
/**
* Combine the URL with another URL. 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 = self::factory($url);
// Use the more absolute URL as the base URL
if (!$this->isAbsolute() && $url->isAbsolute()) {
$url = $url->combine($this);
}
// Passing a URL with a scheme overrides everything
if ($buffer = $url->getScheme()) {
$this->scheme = $buffer;
$this->host = $url->getHost();
$this->port = $url->getPort();
$this->username = $url->getUsername();
$this->password = $url->getPassword();
$this->path = $url->getPath();
$this->query = $url->getQuery();
$this->fragment = $url->getFragment();
return $this;
}
// Setting a host overrides the entire rest of the URL
if ($buffer = $url->getHost()) {
$this->host = $buffer;
$this->port = $url->getPort();
$this->username = $url->getUsername();
$this->password = $url->getPassword();
$this->path = $url->getPath();
$this->fragment = $url->getFragment();
return $this;
}
$path = $url->getPath();
$query = $url->getQuery();
if (!$path) {
if (count($query)) {
$this->query = $query;
}
} else {
if ($path[0] == '/') {
$this->path = $path;
} else {
$this->path .= '/' . $path;
}
$this->normalizePath();
$this->query = $query;
}
$this->fragment = $url->getFragment();
return $this;
}
}
Guzzle-3.7.0/Guzzle/Http/Curl/CurlHandle.php 0000644 233176441610067500000035766 12155472567 022311 0 ustar dowling ANT\Domain Users getCurlOptions();
$mediator = new RequestMediator($request, $requestCurlOptions->get('emit_io'));
$tempContentLength = null;
$method = $request->getMethod();
$bodyAsString = $requestCurlOptions->get(self::BODY_AS_STRING);
// Array of default cURL options.
$curlOptions = array(
CURLOPT_URL => $request->getUrl(),
CURLOPT_CONNECTTIMEOUT => 150,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_HEADER => false,
CURLOPT_PORT => $request->getPort(),
CURLOPT_HTTPHEADER => array(),
CURLOPT_WRITEFUNCTION => array($mediator, 'writeResponseBody'),
CURLOPT_HEADERFUNCTION => array($mediator, 'receiveResponseHeader'),
CURLOPT_HTTP_VERSION => $request->getProtocolVersion() === '1.0'
? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1,
// Verifies the authenticity of the peer's certificate
CURLOPT_SSL_VERIFYPEER => 1,
// Certificate must indicate that the server is the server to which you meant to connect
CURLOPT_SSL_VERIFYHOST => 2
);
if (defined('CURLOPT_PROTOCOLS')) {
// Allow only HTTP and HTTPS protocols
$curlOptions[CURLOPT_PROTOCOLS] = CURLPROTO_HTTP | CURLPROTO_HTTPS;
}
// Add CURLOPT_ENCODING if Accept-Encoding header is provided
if ($acceptEncodingHeader = $request->getHeader('Accept-Encoding')) {
$curlOptions[CURLOPT_ENCODING] = (string) $acceptEncodingHeader;
// Let cURL set the Accept-Encoding header, prevents duplicate values
$request->removeHeader('Accept-Encoding');
}
// Enable curl debug information if the 'debug' param was set
if ($requestCurlOptions->get('debug')) {
$curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+');
// @codeCoverageIgnoreStart
if (false === $curlOptions[CURLOPT_STDERR]) {
throw new RuntimeException('Unable to create a stream for CURLOPT_STDERR');
}
// @codeCoverageIgnoreEnd
$curlOptions[CURLOPT_VERBOSE] = true;
}
// Specify settings according to the HTTP method
if ($method == 'GET') {
$curlOptions[CURLOPT_HTTPGET] = true;
} elseif ($method == 'HEAD') {
$curlOptions[CURLOPT_NOBODY] = true;
// HEAD requests do not use a write function
unset($curlOptions[CURLOPT_WRITEFUNCTION]);
} elseif (!($request instanceof EntityEnclosingRequest)) {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
} else {
$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;
// Handle sending raw bodies in a request
if ($request->getBody()) {
// You can send the body as a string using curl's CURLOPT_POSTFIELDS
if ($bodyAsString) {
$curlOptions[CURLOPT_POSTFIELDS] = (string) $request->getBody();
// Allow curl to add the Content-Length for us to account for the times when
// POST redirects are followed by GET requests
if ($tempContentLength = $request->getHeader('Content-Length')) {
$tempContentLength = (int) (string) $tempContentLength;
}
// Remove the curl generated Content-Type header if none was set manually
if (!$request->hasHeader('Content-Type')) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type:';
}
} else {
$curlOptions[CURLOPT_UPLOAD] = true;
// Let cURL handle setting the Content-Length header
if ($tempContentLength = $request->getHeader('Content-Length')) {
$tempContentLength = (int) (string) $tempContentLength;
$curlOptions[CURLOPT_INFILESIZE] = $tempContentLength;
}
// Add a callback for curl to read data to send with the request only if a body was specified
$curlOptions[CURLOPT_READFUNCTION] = array($mediator, 'readRequestBody');
// Attempt to seek to the start of the stream
$request->getBody()->seek(0);
}
} else {
// Special handling for POST specific fields and files
$postFields = false;
if (count($request->getPostFiles())) {
$postFields = $request->getPostFields()->useUrlEncoding(false)->urlEncode();
foreach ($request->getPostFiles() as $key => $data) {
$prefixKeys = count($data) > 1;
foreach ($data as $index => $file) {
// Allow multiple files in the same key
$fieldKey = $prefixKeys ? "{$key}[{$index}]" : $key;
$postFields[$fieldKey] = $file->getCurlValue();
}
}
} elseif (count($request->getPostFields())) {
$postFields = (string) $request->getPostFields()->useUrlEncoding(true);
}
if ($postFields !== false) {
if ($method == 'POST') {
unset($curlOptions[CURLOPT_CUSTOMREQUEST]);
$curlOptions[CURLOPT_POST] = true;
}
$curlOptions[CURLOPT_POSTFIELDS] = $postFields;
$request->removeHeader('Content-Length');
}
}
// If the Expect header is not present, prevent curl from adding it
if (!$request->hasHeader('Expect')) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:';
}
}
// If a Content-Length header was specified but we want to allow curl to set one for us
if (null !== $tempContentLength) {
$request->removeHeader('Content-Length');
}
// Set custom cURL options
foreach ($requestCurlOptions->toArray() as $key => $value) {
if (is_numeric($key)) {
$curlOptions[$key] = $value;
}
}
// Do not set an Accept header by default
if (!isset($curlOptions[CURLOPT_ENCODING])) {
$curlOptions[CURLOPT_HTTPHEADER][] = 'Accept:';
}
// Add any custom headers to the request. Empty headers will cause curl to not send the header at all.
foreach ($request->getHeaderLines() as $line) {
$curlOptions[CURLOPT_HTTPHEADER][] = $line;
}
// Add the content-length header back if it was temporarily removed
if ($tempContentLength) {
$request->setHeader('Content-Length', $tempContentLength);
}
// Apply the options to a new cURL handle.
$handle = curl_init();
// Enable the progress function if the 'progress' param was set
if ($requestCurlOptions->get('progress')) {
// Wrap the function in a function that provides the curl handle to the mediator's progress function
// Using this rather than injecting the handle into the mediator prevents a circular reference
$curlOptions[CURLOPT_PROGRESSFUNCTION] = function () use ($mediator, $handle) {
$args = func_get_args();
$args[] = $handle;
call_user_func_array(array($mediator, 'progress'), $args);
};
$curlOptions[CURLOPT_NOPROGRESS] = false;
}
curl_setopt_array($handle, $curlOptions);
return new static($handle, $curlOptions);
}
/**
* Construct a new CurlHandle object that wraps a cURL handle
*
* @param resource $handle Configured cURL handle resource
* @param Collection|array $options Curl options to use with the handle
*
* @throws InvalidArgumentException
*/
public function __construct($handle, $options)
{
if (!is_resource($handle)) {
throw new InvalidArgumentException('Invalid handle provided');
}
if (is_array($options)) {
$this->options = new Collection($options);
} elseif ($options instanceof Collection) {
$this->options = $options;
} else {
throw new InvalidArgumentException('Expected array or Collection');
}
$this->handle = $handle;
}
/**
* Destructor
*/
public function __destruct()
{
$this->close();
}
/**
* Close the curl handle
*/
public function close()
{
if (is_resource($this->handle)) {
curl_close($this->handle);
}
$this->handle = null;
}
/**
* Check if the handle is available and still OK
*
* @return bool
*/
public function isAvailable()
{
return is_resource($this->handle);
}
/**
* Get the last error that occurred on the cURL handle
*
* @return string
*/
public function getError()
{
return $this->isAvailable() ? curl_error($this->handle) : '';
}
/**
* Get the last error number that occurred on the cURL handle
*
* @return int
*/
public function getErrorNo()
{
if ($this->errorNo) {
return $this->errorNo;
}
return $this->isAvailable() ? curl_errno($this->handle) : CURLE_OK;
}
/**
* Set the curl error number
*
* @param int $error Error number to set
*
* @return CurlHandle
*/
public function setErrorNo($error)
{
$this->errorNo = $error;
return $this;
}
/**
* Get cURL curl_getinfo data
*
* @param int $option Option to retrieve. Pass null to retrieve all data as an array.
*
* @return array|mixed
*/
public function getInfo($option = null)
{
if (!is_resource($this->handle)) {
return null;
}
if (null !== $option) {
return curl_getinfo($this->handle, $option) ?: null;
}
return curl_getinfo($this->handle) ?: array();
}
/**
* Get the stderr output
*
* @param bool $asResource Set to TRUE to get an fopen resource
*
* @return string|resource|null
*/
public function getStderr($asResource = false)
{
$stderr = $this->getOptions()->get(CURLOPT_STDERR);
if (!$stderr) {
return null;
}
if ($asResource) {
return $stderr;
}
fseek($stderr, 0);
$e = stream_get_contents($stderr);
fseek($stderr, 0, SEEK_END);
return $e;
}
/**
* Get the URL that this handle is connecting to
*
* @return Url
*/
public function getUrl()
{
return Url::factory($this->options->get(CURLOPT_URL));
}
/**
* Get the wrapped curl handle
*
* @return resource|null Returns the cURL handle or null if it was closed
*/
public function getHandle()
{
return $this->isAvailable() ? $this->handle : null;
}
/**
* Get the cURL setopt options of the handle. Changing values in the return object will have no effect on the curl
* handle after it is created.
*
* @return Collection
*/
public function getOptions()
{
return $this->options;
}
/**
* Update a request based on the log messages of the CurlHandle
*
* @param RequestInterface $request Request to update
*/
public function updateRequestFromTransfer(RequestInterface $request)
{
if (!$request->getResponse()) {
return;
}
// Update the transfer stats of the response
$request->getResponse()->setInfo($this->getInfo());
if (!$log = $this->getStderr(true)) {
return;
}
// Parse the cURL stderr output for outgoing requests
$headers = '';
fseek($log, 0);
while (($line = fgets($log)) !== false) {
if ($line && $line[0] == '>') {
$headers = substr(trim($line), 2) . "\r\n";
while (($line = fgets($log)) !== false) {
if ($line[0] == '*' || $line[0] == '<') {
break;
} else {
$headers .= trim($line) . "\r\n";
}
}
}
}
// Add request headers to the request exactly as they were sent
if ($headers) {
$parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($headers);
if (!empty($parsed['headers'])) {
$request->setHeaders(array());
foreach ($parsed['headers'] as $name => $value) {
$request->setHeader($name, $value);
}
}
if (!empty($parsed['version'])) {
$request->setProtocolVersion($parsed['version']);
}
}
}
/**
* Parse the config and replace curl.* configurators into the constant based values so it can be used elsewhere
*
* @param array|Collection $config The configuration we want to parse
*
* @return array
*/
public static function parseCurlConfig($config)
{
$curlOptions = array();
foreach ($config as $key => $value) {
if (is_string($key) && defined($key)) {
// Convert constants represented as string to constant int values
$key = constant($key);
}
if (is_string($value) && defined($value)) {
$value = constant($value);
}
$curlOptions[$key] = $value;
}
return $curlOptions;
}
}
Guzzle-3.7.0/Guzzle/Http/Curl/CurlMulti.php 0000644 233176441610067500000032502 12155472567 022171 0 ustar dowling ANT\Domain Users array('CURLM_BAD_HANDLE', 'The passed-in handle is not a valid CURLM handle.'),
CURLM_BAD_EASY_HANDLE => array('CURLM_BAD_EASY_HANDLE', "An easy handle was not good/valid. It could mean that it isn't an easy handle at all, or possibly that the handle already is in used by this or another multi handle."),
CURLM_OUT_OF_MEMORY => array('CURLM_OUT_OF_MEMORY', 'You are doomed.'),
CURLM_INTERNAL_ERROR => array('CURLM_INTERNAL_ERROR', 'This can only be returned if libcurl bugs. Please report it to us!')
);
public function __construct()
{
$this->multiHandle = curl_multi_init();
// @codeCoverageIgnoreStart
if ($this->multiHandle === false) {
throw new CurlException('Unable to create multi handle');
}
// @codeCoverageIgnoreEnd
$this->reset();
}
public function __destruct()
{
if (is_resource($this->multiHandle)) {
curl_multi_close($this->multiHandle);
}
}
public function add(RequestInterface $request)
{
$this->requests[] = $request;
// If requests are currently transferring and this is async, then the
// request must be prepared now as the send() method is not called.
$this->beforeSend($request);
$this->dispatch(self::ADD_REQUEST, array('request' => $request));
return $this;
}
public function all()
{
return $this->requests;
}
public function remove(RequestInterface $request)
{
$this->removeHandle($request);
foreach ($this->requests as $i => $r) {
if ($request === $r) {
unset($this->requests[$i]);
$this->requests = array_values($this->requests);
$this->dispatch(self::REMOVE_REQUEST, array('request' => $request));
return true;
}
}
return false;
}
public function reset($hard = false)
{
// Remove each request
if ($this->requests) {
foreach ($this->requests as $request) {
$this->remove($request);
}
}
$this->handles = new \SplObjectStorage();
$this->requests = $this->resourceHash = $this->exceptions = $this->successful = array();
}
public function send()
{
$this->perform();
$exceptions = $this->exceptions;
$successful = $this->successful;
$this->reset();
if ($exceptions) {
$this->throwMultiException($exceptions, $successful);
}
}
public function count()
{
return count($this->requests);
}
/**
* Build and throw a MultiTransferException
*
* @param array $exceptions Exceptions encountered
* @param array $successful Successful requests
* @throws MultiTransferException
*/
protected function throwMultiException(array $exceptions, array $successful)
{
$multiException = new MultiTransferException('Errors during multi transfer');
while ($e = array_shift($exceptions)) {
$multiException->add($e['exception']);
$multiException->addFailedRequest($e['request']);
}
// Add successful requests
foreach ($successful as $request) {
if (!$multiException->containsRequest($request)) {
$multiException->addSuccessfulRequest($request);
}
}
throw $multiException;
}
/**
* Prepare for sending
*
* @param RequestInterface $request Request to prepare
* @throws \Exception on error preparing the request
*/
protected function beforeSend(RequestInterface $request)
{
try {
$state = $request->setState(RequestInterface::STATE_TRANSFER);
if ($state == RequestInterface::STATE_TRANSFER) {
// Add the request curl handle to the multi handle
$this->checkCurlResult(curl_multi_add_handle($this->multiHandle, $this->createCurlHandle($request)->getHandle()));
} else {
// Requests might decide they don't need to be sent just before transfer (e.g. CachePlugin)
$this->remove($request);
if ($state == RequestInterface::STATE_COMPLETE) {
$this->successful[] = $request;
}
}
} catch (\Exception $e) {
// Queue the exception to be thrown when sent
$this->removeErroredRequest($request, $e);
}
}
/**
* Create a curl handle for a request
*
* @param RequestInterface $request Request
*
* @return CurlHandle
*/
protected function createCurlHandle(RequestInterface $request)
{
$wrapper = CurlHandle::factory($request);
$this->handles[$request] = $wrapper;
$this->resourceHash[(int) $wrapper->getHandle()] = $request;
return $wrapper;
}
/**
* Get the data from the multi handle
*/
protected function perform()
{
if (!$this->requests) {
return;
}
// Initialize the handles with a very quick select timeout
$active = $mrc = null;
$this->executeHandles($active, $mrc, 0.001);
$event = new Event(array('curl_multi' => $this));
$this->processMessages();
while ($this->requests) {
// Notify each request as polling
$blocking = $total = 0;
foreach ($this->requests as $request) {
++$total;
$event['request'] = $request;
$request->getEventDispatcher()->dispatch(self::POLLING_REQUEST, $event);
// The blocking variable just has to be non-falsey to block the loop
if ($request->getParams()->hasKey(self::BLOCKING)) {
++$blocking;
}
}
if ($blocking == $total) {
// Sleep to prevent eating CPU because no requests are actually pending a select call
usleep(500);
} else {
do {
$this->executeHandles($active, $mrc, 1);
} while ($active);
}
$this->processMessages();
}
}
/**
* Process any received curl multi messages
*/
private function processMessages()
{
// Get messages from curl handles
while ($done = curl_multi_info_read($this->multiHandle)) {
try {
$request = $this->resourceHash[(int) $done['handle']];
$this->processResponse($request, $this->handles[$request], $done);
$this->successful[] = $request;
} catch (MultiTransferException $e) {
$this->removeErroredRequest($request, $e, false);
throw $e;
} catch (\Exception $e) {
$this->removeErroredRequest($request, $e);
}
}
}
/**
* Execute and select curl handles until there is activity
*
* @param int $active Active value to update
* @param int $mrc Multi result value to update
* @param int $timeout Select timeout in seconds
*/
private function executeHandles(&$active, &$mrc, $timeout = 1)
{
do {
$mrc = curl_multi_exec($this->multiHandle, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM && $active);
$this->checkCurlResult($mrc);
// @codeCoverageIgnoreStart
// Select the curl handles until there is any activity on any of the open file descriptors
// See https://github.com/php/php-src/blob/master/ext/curl/multi.c#L170
if ($active && $mrc == CURLM_OK && curl_multi_select($this->multiHandle, $timeout) == -1) {
// Perform a usleep if a previously executed select returned -1
// @see https://bugs.php.net/bug.php?id=61141
usleep(100);
}
// @codeCoverageIgnoreEnd
}
/**
* Remove a request that encountered an exception
*
* @param RequestInterface $request Request to remove
* @param \Exception $e Exception encountered
* @param bool $buffer Set to false to not buffer the exception
*/
protected function removeErroredRequest(RequestInterface $request, \Exception $e = null, $buffer = true)
{
if ($buffer) {
$this->exceptions[] = array('request' => $request, 'exception' => $e);
}
$this->remove($request);
$this->dispatch(self::MULTI_EXCEPTION, array('exception' => $e, 'all_exceptions' => $this->exceptions));
}
/**
* Check for errors and fix headers of a request based on a curl response
*
* @param RequestInterface $request Request to process
* @param CurlHandle $handle Curl handle object
* @param array $curl Array returned from curl_multi_info_read
*
* @throws CurlException on Curl error
*/
protected function processResponse(RequestInterface $request, CurlHandle $handle, array $curl)
{
// Set the transfer stats on the response
$handle->updateRequestFromTransfer($request);
// Check if a cURL exception occurred, and if so, notify things
$curlException = $this->isCurlException($request, $handle, $curl);
// Always remove completed curl handles. They can be added back again
// via events if needed (e.g. ExponentialBackoffPlugin)
$this->removeHandle($request);
if (!$curlException) {
$state = $request->setState(RequestInterface::STATE_COMPLETE, array('handle' => $handle));
// Only remove the request if it wasn't resent as a result of the state change
if ($state != RequestInterface::STATE_TRANSFER) {
$this->remove($request);
}
} else {
// Set the state of the request to an error
$state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $curlException));
// Allow things to ignore the error if possible
if ($state != RequestInterface::STATE_TRANSFER) {
$this->remove($request);
}
// The error was not handled, so fail
if ($state == RequestInterface::STATE_ERROR) {
/** @var CurlException $curlException */
throw $curlException;
}
}
}
/**
* Remove a curl handle from the curl multi object
*
* @param RequestInterface $request Request that owns the handle
*/
protected function removeHandle(RequestInterface $request)
{
if (isset($this->handles[$request])) {
$handle = $this->handles[$request];
unset($this->handles[$request]);
unset($this->resourceHash[(int) $handle->getHandle()]);
curl_multi_remove_handle($this->multiHandle, $handle->getHandle());
$handle->close();
}
}
/**
* Check if a cURL transfer resulted in what should be an exception
*
* @param RequestInterface $request Request to check
* @param CurlHandle $handle Curl handle object
* @param array $curl Array returned from curl_multi_info_read
*
* @return CurlException|bool
*/
private function isCurlException(RequestInterface $request, CurlHandle $handle, array $curl)
{
if (CURLM_OK == $curl['result'] || CURLM_CALL_MULTI_PERFORM == $curl['result']) {
return false;
}
$handle->setErrorNo($curl['result']);
$e = new CurlException(sprintf('[curl] %s: %s [url] %s',
$handle->getErrorNo(), $handle->getError(), $handle->getUrl()));
$e->setCurlHandle($handle)
->setRequest($request)
->setCurlInfo($handle->getInfo())
->setError($handle->getError(), $handle->getErrorNo());
return $e;
}
/**
* Throw an exception for a cURL multi response if needed
*
* @param int $code Curl response code
* @throws CurlException
*/
private function checkCurlResult($code)
{
if ($code != CURLM_OK && $code != CURLM_CALL_MULTI_PERFORM) {
throw new CurlException(isset($this->multiErrors[$code])
? "cURL error: {$code} ({$this->multiErrors[$code][0]}): cURL message: {$this->multiErrors[$code][1]}"
: 'Unexpected cURL error: ' . $code
);
}
}
}
Guzzle-3.7.0/Guzzle/Http/Curl/CurlMultiInterface.php 0000644 233176441610067500000003075 12155472567 024015 0 ustar dowling ANT\Domain Users maxHandles = $maxHandles;
// You can get some weird "Too many open files" errors when sending a large amount of requests in parallel.
// These two statements autoload classes before a system runs out of file descriptors so that you can get back
// valuable error messages if you run out.
class_exists('Guzzle\Http\Message\Response');
class_exists('Guzzle\Http\Exception\CurlException');
}
public function add(RequestInterface $request)
{
$this->queued[] = $request;
return $this;
}
public function all()
{
$requests = $this->queued;
foreach ($this->handles as $handle) {
$requests = array_merge($requests, $handle->all());
}
return $requests;
}
public function remove(RequestInterface $request)
{
foreach ($this->queued as $i => $r) {
if ($request === $r) {
unset($this->queued[$i]);
return true;
}
}
foreach ($this->handles as $handle) {
if ($handle->remove($request)) {
return true;
}
}
return false;
}
public function reset($hard = false)
{
$this->queued = array();
$this->groups = array();
foreach ($this->handles as $handle) {
$handle->reset();
}
if ($hard) {
$this->handles = array();
}
return $this;
}
public function send()
{
if ($this->queued) {
$group = $this->getAvailableHandle();
// Add this handle to a list of handles than is claimed
$this->groups[] = $group;
while ($request = array_shift($this->queued)) {
$group->add($request);
}
try {
$group->send();
array_pop($this->groups);
$this->cleanupHandles();
} catch (\Exception $e) {
// Remove the group and cleanup if an exception was encountered and no more requests in group
if (!$group->count()) {
array_pop($this->groups);
$this->cleanupHandles();
}
throw $e;
}
}
}
public function count()
{
return count($this->all());
}
/**
* Get an existing available CurlMulti handle or create a new one
*
* @return CurlMulti
*/
protected function getAvailableHandle()
{
// Grab a handle that is not claimed
foreach ($this->handles as $h) {
if (!in_array($h, $this->groups, true)) {
return $h;
}
}
// All are claimed, so create one
$handle = new CurlMulti();
$handle->setEventDispatcher($this->getEventDispatcher());
$this->handles[] = $handle;
return $handle;
}
/**
* Trims down unused CurlMulti handles to limit the number of open connections
*/
protected function cleanupHandles()
{
if ($diff = max(0, count($this->handles) - $this->maxHandles)) {
for ($i = count($this->handles) - 1; $i > 0 && $diff > 0; $i--) {
if (!count($this->handles[$i])) {
unset($this->handles[$i]);
$diff--;
}
}
$this->handles = array_values($this->handles);
}
}
}
Guzzle-3.7.0/Guzzle/Http/Curl/CurlVersion.php 0000644 233176441610067500000003267 12155472567 022532 0 ustar dowling ANT\Domain Users version) {
$this->version = curl_version();
}
return $this->version;
}
/**
* Get a specific type of curl information
*
* @param string $type Version information to retrieve. This value is one of:
* - version_number: cURL 24 bit version number
* - version: cURL version number, as a string
* - ssl_version_number: OpenSSL 24 bit version number
* - ssl_version: OpenSSL version number, as a string
* - libz_version: zlib version number, as a string
* - host: Information about the host where cURL was built
* - features: A bitmask of the CURL_VERSION_XXX constants
* - protocols: An array of protocols names supported by cURL
*
* @return string|float|bool if the $type is found, and false if not found
*/
public function get($type)
{
$version = $this->getAll();
return isset($version[$type]) ? $version[$type] : false;
}
}
Guzzle-3.7.0/Guzzle/Http/Curl/RequestMediator.php 0000644 233176441610067500000010412 12155472567 023362 0 ustar dowling ANT\Domain Users request = $request;
$this->emitIo = $emitIo;
}
/**
* Receive a response header from curl
*
* @param resource $curl Curl handle
* @param string $header Received header
*
* @return int
*/
public function receiveResponseHeader($curl, $header)
{
static $normalize = array("\r", "\n");
$length = strlen($header);
$header = str_replace($normalize, '', $header);
if (strpos($header, 'HTTP/') === 0) {
$startLine = explode(' ', $header, 3);
$code = $startLine[1];
$status = isset($startLine[2]) ? $startLine[2] : '';
// Only download the body of the response to the specified response
// body when a successful response is received.
if ($code >= 200 && $code < 300) {
$body = $this->request->getResponseBody();
} else {
$body = EntityBody::factory();
}
$response = new Response($code, null, $body);
$response->setStatus($code, $status);
$this->request->startResponse($response);
$this->request->dispatch('request.receive.status_line', array(
'request' => $this,
'line' => $header,
'status_code' => $code,
'reason_phrase' => $status
));
} elseif ($pos = strpos($header, ':')) {
$this->request->getResponse()->addHeader(
trim(substr($header, 0, $pos)),
trim(substr($header, $pos + 1))
);
}
return $length;
}
/**
* Received a progress notification
*
* @param int $downloadSize Total download size
* @param int $downloaded Amount of bytes downloaded
* @param int $uploadSize Total upload size
* @param int $uploaded Amount of bytes uploaded
* @param resource $handle CurlHandle object
*/
public function progress($downloadSize, $downloaded, $uploadSize, $uploaded, $handle = null)
{
$this->request->dispatch('curl.callback.progress', array(
'request' => $this->request,
'handle' => $handle,
'download_size' => $downloadSize,
'downloaded' => $downloaded,
'upload_size' => $uploadSize,
'uploaded' => $uploaded
));
}
/**
* Write data to the response body of a request
*
* @param resource $curl Curl handle
* @param string $write Data that was received
*
* @return int
*/
public function writeResponseBody($curl, $write)
{
if ($this->emitIo) {
$this->request->dispatch('curl.callback.write', array(
'request' => $this->request,
'write' => $write
));
}
return $this->request->getResponse()->getBody()->write($write);
}
/**
* Read data from the request body and send it to curl
*
* @param resource $ch Curl handle
* @param resource $fd File descriptor
* @param int $length Amount of data to read
*
* @return string
*/
public function readRequestBody($ch, $fd, $length)
{
$read = '';
if ($this->request->getBody()) {
$read = $this->request->getBody()->read($length);
if ($this->emitIo) {
$this->request->dispatch('curl.callback.read', array(
'request' => $this->request,
'read' => $read
));
}
}
return !$read ? '' : $read;
}
}
Guzzle-3.7.0/Guzzle/Http/Exception/BadResponseException.php 0000644 233176441610067500000003521 12155472567 025365 0 ustar dowling ANT\Domain Users isClientError()) {
$label = 'Client error response';
$class = __NAMESPACE__ . '\\ClientErrorResponseException';
} elseif ($response->isServerError()) {
$label = 'Server error response';
$class = __NAMESPACE__ . '\\ServerErrorResponseException';
} else {
$label = 'Unsuccessful response';
$class = __CLASS__;
$e = new self();
}
$message = $label . PHP_EOL . implode(PHP_EOL, array(
'[status code] ' . $response->getStatusCode(),
'[reason phrase] ' . $response->getReasonPhrase(),
'[url] ' . $request->getUrl(),
));
$e = new $class($message);
$e->setResponse($response);
$e->setRequest($request);
return $e;
}
/**
* Set the response that caused the exception
*
* @param Response $response Response to set
*/
public function setResponse(Response $response)
{
$this->response = $response;
}
/**
* Get the response that caused the exception
*
* @return Response
*/
public function getResponse()
{
return $this->response;
}
}
Guzzle-3.7.0/Guzzle/Http/Exception/ClientErrorResponseException.php 0000644 233176441610067500000000260 12155472567 027124 0 ustar dowling ANT\Domain Users curlError = $error;
$this->curlErrorNo = $number;
return $this;
}
/**
* Set the associated curl handle
*
* @param CurlHandle $handle Curl handle
*
* @return self
*/
public function setCurlHandle(CurlHandle $handle)
{
$this->handle = $handle;
return $this;
}
/**
* Get the associated cURL handle
*
* @return CurlHandle|null
*/
public function getCurlHandle()
{
return $this->handle;
}
/**
* Get the associated cURL error message
*
* @return string|null
*/
public function getError()
{
return $this->curlError;
}
/**
* Get the associated cURL error number
*
* @return int|null
*/
public function getErrorNo()
{
return $this->curlErrorNo;
}
/**
* Returns curl information about the transfer
*
* @return array
*/
public function getCurlInfo()
{
return $this->curlInfo;
}
/**
* Set curl transfer information
*
* @param array $info Array of curl transfer information
*
* @return self
* @link http://php.net/manual/en/function.curl-getinfo.php
*/
public function setCurlInfo(array $info)
{
$this->curlInfo = $info;
return $this;
}
}
Guzzle-3.7.0/Guzzle/Http/Exception/HttpException.php 0000644 233176441610067500000000256 12155472567 024101 0 ustar dowling ANT\Domain Users successfulRequests, $this->failedRequests);
}
/**
* Add to the array of successful requests
*
* @param RequestInterface $request Successful request
*
* @return self
*/
public function addSuccessfulRequest(RequestInterface $request)
{
$this->successfulRequests[] = $request;
return $this;
}
/**
* Add to the array of failed requests
*
* @param RequestInterface $request Failed request
*
* @return self
*/
public function addFailedRequest(RequestInterface $request)
{
$this->failedRequests[] = $request;
return $this;
}
/**
* Set all of the successful requests
*
* @param array Array of requests
*
* @return self
*/
public function setSuccessfulRequests(array $requests)
{
$this->successfulRequests = $requests;
return $this;
}
/**
* Set all of the failed requests
*
* @param array Array of requests
*
* @return self
*/
public function setFailedRequests(array $requests)
{
$this->failedRequests = $requests;
return $this;
}
/**
* Get an array of successful requests sent in the multi transfer
*
* @return array
*/
public function getSuccessfulRequests()
{
return $this->successfulRequests;
}
/**
* Get an array of failed requests sent in the multi transfer
*
* @return array
*/
public function getFailedRequests()
{
return $this->failedRequests;
}
/**
* Check if the exception object contains a request
*
* @param RequestInterface $request Request to check
*
* @return bool
*/
public function containsRequest(RequestInterface $request)
{
return in_array($request, $this->failedRequests, true) || in_array($request, $this->successfulRequests, true);
}
}
Guzzle-3.7.0/Guzzle/Http/Exception/RequestException.php 0000644 233176441610067500000001406 12155472567 024610 0 ustar dowling ANT\Domain Users request = $request;
return $this;
}
/**
* Get the request that caused the exception
*
* @return RequestInterface
*/
public function getRequest()
{
return $this->request;
}
}
Guzzle-3.7.0/Guzzle/Http/Exception/ServerErrorResponseException.php 0000644 233176441610067500000000260 12155472567 027154 0 ustar dowling ANT\Domain Users params = new Collection();
$this->headerFactory = new HeaderFactory();
$this->headers = new HeaderCollection();
}
/**
* Set the header factory to use to create headers
*
* @param HeaderFactoryInterface $factory
*
* @return self
*/
public function setHeaderFactory(HeaderFactoryInterface $factory)
{
$this->headerFactory = $factory;
return $this;
}
public function getParams()
{
return $this->params;
}
public function addHeader($header, $value)
{
if (isset($this->headers[$header])) {
$this->headers[$header]->add($value);
} elseif ($value instanceof HeaderInterface) {
$this->headers[$header] = $value;
} else {
$this->headers[$header] = $this->headerFactory->createHeader($header, $value);
}
return $this;
}
public function addHeaders(array $headers)
{
foreach ($headers as $key => $value) {
$this->addHeader($key, $value);
}
return $this;
}
public function getHeader($header)
{
return $this->headers[$header];
}
public function getHeaders()
{
return $this->headers;
}
public function getHeaderLines()
{
$headers = array();
foreach ($this->headers as $value) {
$headers[] = $value->getName() . ': ' . $value;
}
return $headers;
}
public function setHeader($header, $value)
{
unset($this->headers[$header]);
$this->addHeader($header, $value);
return $this;
}
public function setHeaders(array $headers)
{
$this->headers->clear();
foreach ($headers as $key => $value) {
$this->addHeader($key, $value);
}
return $this;
}
public function hasHeader($header)
{
return isset($this->headers[$header]);
}
public function removeHeader($header)
{
unset($this->headers[$header]);
return $this;
}
/**
* @deprecated Use $message->getHeader()->parseParams()
* @codeCoverageIgnore
*/
public function getTokenizedHeader($header, $token = ';')
{
Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader()->parseParams()');
if ($this->hasHeader($header)) {
$data = new Collection();
foreach ($this->getHeader($header)->parseParams() as $values) {
foreach ($values as $key => $value) {
if ($value === '') {
$data->set($data->count(), $key);
} else {
$data->add($key, $value);
}
}
}
return $data;
}
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function setTokenizedHeader($header, $data, $token = ';')
{
Version::warn(__METHOD__ . ' is deprecated.');
return $this;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getCacheControlDirective($directive)
{
Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->getDirective()');
if (!($header = $this->getHeader('Cache-Control'))) {
return null;
}
return $header->getDirective($directive);
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function hasCacheControlDirective($directive)
{
Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->hasDirective()');
if ($header = $this->getHeader('Cache-Control')) {
return $header->hasDirective($directive);
} else {
return false;
}
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function addCacheControlDirective($directive, $value = true)
{
Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->addDirective()');
if (!($header = $this->getHeader('Cache-Control'))) {
$this->addHeader('Cache-Control', '');
$header = $this->getHeader('Cache-Control');
}
$header->addDirective($directive, $value);
return $this;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function removeCacheControlDirective($directive)
{
Version::warn(__METHOD__ . ' is deprecated. Use $message->getHeader(\'Cache-Control\')->removeDirective()');
if ($header = $this->getHeader('Cache-Control')) {
$header->removeDirective($directive);
}
return $this;
}
}
Guzzle-3.7.0/Guzzle/Http/Message/EntityEnclosingRequest.php 0000644 233176441610067500000016747 12155472567 025434 0 ustar dowling ANT\Domain Users postFields = new QueryString();
parent::__construct($method, $url, $headers);
}
/**
* @return string
*/
public function __toString()
{
// Only attempt to include the POST data if it's only fields
if (count($this->postFields) && empty($this->postFiles)) {
return parent::__toString() . (string) $this->postFields;
}
return parent::__toString() . $this->body;
}
public function setState($state, array $context = array())
{
parent::setState($state, $context);
if ($state == self::STATE_TRANSFER && !$this->body && !count($this->postFields) && !count($this->postFiles)) {
$this->setHeader('Content-Length', 0)->removeHeader('Transfer-Encoding');
}
return $this->state;
}
public function setBody($body, $contentType = null)
{
$this->body = EntityBody::factory($body);
// Auto detect the Content-Type from the path of the request if possible
if ($contentType === null && !$this->hasHeader('Content-Type')) {
$contentType = $this->body->getContentType() ?: Mimetypes::getInstance()->fromFilename($this->getPath());
}
if ($contentType) {
$this->setHeader('Content-Type', $contentType);
}
// Always add the Expect 100-Continue header if the body cannot be rewound. This helps with redirects.
if (!$this->body->isSeekable() && $this->expectCutoff !== false) {
$this->setHeader('Expect', '100-Continue');
}
// Set the Content-Length header if it can be determined
$size = $this->body->getContentLength();
if ($size !== null && $size !== false) {
$this->setHeader('Content-Length', $size);
if ($size > $this->expectCutoff) {
$this->setHeader('Expect', '100-Continue');
}
} elseif (!$this->hasHeader('Content-Length')) {
if ('1.1' == $this->protocolVersion) {
$this->setHeader('Transfer-Encoding', 'chunked');
} else {
throw new RequestException(
'Cannot determine Content-Length and cannot use chunked Transfer-Encoding when using HTTP/1.0'
);
}
}
return $this;
}
public function getBody()
{
return $this->body;
}
/**
* Set the size that the entity body of the request must exceed before adding the Expect: 100-Continue header.
*
* @param int|bool $size Cutoff in bytes. Set to false to never send the expect header (even with non-seekable data)
*
* @return self
*/
public function setExpectHeaderCutoff($size)
{
$this->expectCutoff = $size;
if ($size === false || !$this->body) {
$this->removeHeader('Expect');
} elseif ($this->body && $this->body->getSize() && $this->body->getSize() > $size) {
$this->setHeader('Expect', '100-Continue');
}
return $this;
}
public function configureRedirects($strict = false, $maxRedirects = 5)
{
$this->getParams()->set(RedirectPlugin::STRICT_REDIRECTS, $strict);
if ($maxRedirects == 0) {
$this->getParams()->set(RedirectPlugin::DISABLE, true);
} else {
$this->getParams()->set(RedirectPlugin::MAX_REDIRECTS, $maxRedirects);
}
return $this;
}
public function getPostField($field)
{
return $this->postFields->get($field);
}
public function getPostFields()
{
return $this->postFields;
}
public function setPostField($key, $value)
{
$this->postFields->set($key, $value);
$this->processPostFields();
return $this;
}
public function addPostFields($fields)
{
$this->postFields->merge($fields);
$this->processPostFields();
return $this;
}
public function removePostField($field)
{
$this->postFields->remove($field);
$this->processPostFields();
return $this;
}
public function getPostFiles()
{
return $this->postFiles;
}
public function getPostFile($fieldName)
{
return isset($this->postFiles[$fieldName]) ? $this->postFiles[$fieldName] : null;
}
public function removePostFile($fieldName)
{
unset($this->postFiles[$fieldName]);
$this->processPostFields();
return $this;
}
public function addPostFile($field, $filename = null, $contentType = null)
{
$data = null;
if ($field instanceof PostFileInterface) {
$data = $field;
} elseif (is_array($filename)) {
// Allow multiple values to be set in a single key
foreach ($filename as $file) {
$this->addPostFile($field, $file, $contentType);
}
return $this;
} elseif (!is_string($filename)) {
throw new RequestException('The path to a file must be a string');
} elseif (!empty($filename)) {
// Adding an empty file will cause cURL to error out
$data = new PostFile($field, $filename, $contentType);
}
if ($data) {
if (!isset($this->postFiles[$data->getFieldName()])) {
$this->postFiles[$data->getFieldName()] = array($data);
} else {
$this->postFiles[$data->getFieldName()][] = $data;
}
$this->processPostFields();
}
return $this;
}
public function addPostFiles(array $files)
{
foreach ($files as $key => $file) {
if ($file instanceof PostFileInterface) {
$this->addPostFile($file, null, null, false);
} elseif (is_string($file)) {
// Convert non-associative array keys into 'file'
if (is_numeric($key)) {
$key = 'file';
}
$this->addPostFile($key, $file, null, false);
} else {
throw new RequestException('File must be a string or instance of PostFileInterface');
}
}
return $this;
}
/**
* Determine what type of request should be sent based on post fields
*/
protected function processPostFields()
{
if (!$this->postFiles) {
$this->removeHeader('Expect')->setHeader('Content-Type', self::URL_ENCODED);
} else {
$this->setHeader('Content-Type', self::MULTIPART);
if ($this->expectCutoff !== false) {
$this->setHeader('Expect', '100-Continue');
}
}
}
}
Guzzle-3.7.0/Guzzle/Http/Message/EntityEnclosingRequestInterface.php 0000644 233176441610067500000010175 12155472567 027242 0 ustar dowling ANT\Domain Users filenames where filename can be a string or PostFileInterface
*
* @return self
*/
public function addPostFiles(array $files);
/**
* Configure how redirects are handled for the request
*
* @param bool $strict Set to true to follow strict RFC compliance when redirecting POST requests. Most
* browsers with follow a 301-302 redirect for a POST request with a GET request. This is
* the default behavior of Guzzle. Enable strict redirects to redirect these responses
* with a POST rather than a GET request.
* @param int $maxRedirects Specify the maximum number of allowed redirects. Set to 0 to disable redirects.
*
* @return self
*/
public function configureRedirects($strict = false, $maxRedirects = 5);
}
Guzzle-3.7.0/Guzzle/Http/Message/Header.php 0000644 233176441610067500000010051 12155472567 022113 0 ustar dowling ANT\Domain Users header = trim($header);
$this->glue = $glue;
foreach ((array) $values as $value) {
foreach ((array) $value as $v) {
$this->values[] = $v;
}
}
}
public function __toString()
{
return implode($this->glue . ' ', $this->toArray());
}
public function add($value)
{
$this->values[] = $value;
return $this;
}
public function getName()
{
return $this->header;
}
public function setName($name)
{
$this->header = $name;
return $this;
}
public function setGlue($glue)
{
$this->glue = $glue;
return $this;
}
public function getGlue()
{
return $this->glue;
}
/**
* Normalize the header to be a single header with an array of values.
*
* If any values of the header contains the glue string value (e.g. ","), then the value will be exploded into
* multiple entries in the header.
*
* @return self
*/
public function normalize()
{
$values = $this->toArray();
for ($i = 0, $total = count($values); $i < $total; $i++) {
if (strpos($values[$i], $this->glue) !== false) {
foreach (explode($this->glue, $values[$i]) as $v) {
$values[] = trim($v);
}
unset($values[$i]);
}
}
$this->values = array_values($values);
return $this;
}
public function hasValue($searchValue)
{
return in_array($searchValue, $this->toArray());
}
public function removeValue($searchValue)
{
$this->values = array_values(array_filter($this->values, function ($value) use ($searchValue) {
return $value != $searchValue;
}));
return $this;
}
public function toArray()
{
return $this->values;
}
public function count()
{
return count($this->toArray());
}
public function getIterator()
{
return new \ArrayIterator($this->toArray());
}
/**
* {@inheritdoc}
* @todo Do not split semicolons when enclosed in quotes (e.g. foo="baz;bar")
*/
public function parseParams()
{
$params = array();
$callback = array($this, 'trimHeader');
// Normalize the header into a single array and iterate over all values
foreach ($this->normalize()->toArray() as $val) {
$part = array();
foreach (explode(';', $val) as $kvp) {
$pieces = array_map($callback, explode('=', $kvp, 2));
$part[$pieces[0]] = isset($pieces[1]) ? $pieces[1] : '';
}
$params[] = $part;
}
return $params;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function hasExactHeader($header)
{
Version::warn(__METHOD__ . ' is deprecated');
return $this->header == $header;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function raw()
{
Version::warn(__METHOD__ . ' is deprecated. Use toArray()');
return $this->toArray();
}
/**
* Trim a header by removing excess spaces and wrapping quotes
*
* @param $str
*
* @return string
*/
protected function trimHeader($str)
{
static $trimmed = "\"' \n\t";
return trim($str, $trimmed);
}
}
Guzzle-3.7.0/Guzzle/Http/Message/MessageInterface.php 0000644 233176441610067500000004420 12155472567 024133 0 ustar dowling ANT\Domain Users fieldName = $fieldName;
$this->setFilename($filename);
$this->contentType = $contentType ?: $this->guessContentType();
}
public function setFieldName($name)
{
$this->fieldName = $name;
return $this;
}
public function getFieldName()
{
return $this->fieldName;
}
public function setFilename($filename)
{
// Remove leading @ symbol
if (strpos($filename, '@') === 0) {
$filename = substr($filename, 1);
}
if (!is_readable($filename)) {
throw new InvalidArgumentException("Unable to open {$filename} for reading");
}
$this->filename = $filename;
return $this;
}
public function getFilename()
{
return $this->filename;
}
public function setContentType($type)
{
$this->contentType = $type;
return $this;
}
public function getContentType()
{
return $this->contentType;
}
public function getCurlValue()
{
// PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
// See: https://wiki.php.net/rfc/curl-file-upload
if (function_exists('curl_file_create')) {
return curl_file_create($this->filename, $this->contentType, basename($this->filename));
}
// Use the old style if using an older version of PHP
$value = "@{$this->filename};filename=" . basename($this->filename);
if ($this->contentType) {
$value .= ';type=' . $this->contentType;
}
return $value;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getCurlString()
{
Version::warn(__METHOD__ . ' is deprecated. Use getCurlValue()');
return $this->getCurlValue();
}
/**
* Determine the Content-Type of the file
*/
protected function guessContentType()
{
return Mimetypes::getInstance()->fromFilename($this->filename) ?: 'application/octet-stream';
}
}
Guzzle-3.7.0/Guzzle/Http/Message/PostFileInterface.php 0000644 233176441610067500000002321 12155472567 024272 0 ustar dowling ANT\Domain Users method = strtoupper($method);
$this->curlOptions = new Collection();
$this->setUrl($url);
if ($headers) {
// Special handling for multi-value headers
foreach ($headers as $key => $value) {
// Deal with collisions with Host and Authorization
if ($key == 'host' || $key == 'Host') {
$this->setHeader($key, $value);
} elseif ($value instanceof HeaderInterface) {
$this->addHeader($key, $value);
} else {
foreach ((array) $value as $v) {
$this->addHeader($key, $v);
}
}
}
}
$this->setState(self::STATE_NEW);
}
public function __clone()
{
if ($this->eventDispatcher) {
$this->eventDispatcher = clone $this->eventDispatcher;
}
$this->curlOptions = clone $this->curlOptions;
$this->params = clone $this->params;
$this->url = clone $this->url;
$this->response = $this->responseBody = null;
$this->headers = clone $this->headers;
$this->setState(RequestInterface::STATE_NEW);
$this->dispatch('request.clone', array('request' => $this));
}
/**
* Get the HTTP request as a string
*
* @return string
*/
public function __toString()
{
return $this->getRawHeaders() . "\r\n\r\n";
}
/**
* Default method that will throw exceptions if an unsuccessful response is received.
*
* @param Event $event Received
* @throws BadResponseException if the response is not successful
*/
public static function onRequestError(Event $event)
{
$e = BadResponseException::factory($event['request'], $event['response']);
$event['request']->setState(self::STATE_ERROR, array('exception' => $e) + $event->toArray());
throw $e;
}
public function setClient(ClientInterface $client)
{
$this->client = $client;
return $this;
}
public function getClient()
{
return $this->client;
}
public function getRawHeaders()
{
$protocolVersion = $this->protocolVersion ?: '1.1';
return trim($this->method . ' ' . $this->getResource()) . ' '
. strtoupper(str_replace('https', 'http', $this->url->getScheme()))
. '/' . $protocolVersion . "\r\n" . implode("\r\n", $this->getHeaderLines());
}
public function setUrl($url)
{
if ($url instanceof Url) {
$this->url = $url;
} else {
$this->url = Url::factory($url);
}
// Update the port and host header
$this->setPort($this->url->getPort());
if ($this->url->getUsername() || $this->url->getPassword()) {
$this->setAuth($this->url->getUsername(), $this->url->getPassword());
// Remove the auth info from the URL
$this->url->setUsername(null);
$this->url->setPassword(null);
}
return $this;
}
public function send()
{
if (!$this->client) {
throw new RuntimeException('A client must be set on the request');
}
return $this->client->send($this);
}
public function getResponse()
{
return $this->response;
}
public function getQuery($asString = false)
{
return $asString
? (string) $this->url->getQuery()
: $this->url->getQuery();
}
public function getMethod()
{
return $this->method;
}
public function getScheme()
{
return $this->url->getScheme();
}
public function setScheme($scheme)
{
$this->url->setScheme($scheme);
return $this;
}
public function getHost()
{
return $this->url->getHost();
}
public function setHost($host)
{
$this->url->setHost($host);
$this->setPort($this->url->getPort());
return $this;
}
public function getProtocolVersion()
{
return $this->protocolVersion;
}
public function setProtocolVersion($protocol)
{
$this->protocolVersion = $protocol;
return $this;
}
public function getPath()
{
return '/' . ltrim($this->url->getPath(), '/');
}
public function setPath($path)
{
$this->url->setPath($path);
return $this;
}
public function getPort()
{
return $this->url->getPort();
}
public function setPort($port)
{
$this->url->setPort($port);
// Include the port in the Host header if it is not the default port for the scheme of the URL
$scheme = $this->url->getScheme();
if (($scheme == 'http' && $port != 80) || ($scheme == 'https' && $port != 443)) {
$this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost() . ':' . $port);
} else {
$this->headers['host'] = $this->headerFactory->createHeader('Host', $this->url->getHost());
}
return $this;
}
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function setAuth($user, $password = '', $scheme = CURLAUTH_BASIC)
{
static $authMap = array(
'basic' => CURLAUTH_BASIC,
'digest' => CURLAUTH_DIGEST,
'ntlm' => CURLAUTH_NTLM,
'any' => CURLAUTH_ANY
);
// If we got false or null, disable authentication
if (!$user) {
$this->password = $this->username = null;
$this->removeHeader('Authorization');
$this->getCurlOptions()->remove(CURLOPT_HTTPAUTH);
return $this;
}
if (!is_numeric($scheme)) {
$scheme = strtolower($scheme);
if (!isset($authMap[$scheme])) {
throw new InvalidArgumentException($scheme . ' is not a valid authentication type');
}
$scheme = $authMap[$scheme];
}
$this->username = $user;
$this->password = $password;
// Bypass CURL when using basic auth to promote connection reuse
if ($scheme == CURLAUTH_BASIC) {
$this->getCurlOptions()->remove(CURLOPT_HTTPAUTH);
$this->setHeader('Authorization', 'Basic ' . base64_encode($this->username . ':' . $this->password));
} else {
$this->getCurlOptions()
->set(CURLOPT_HTTPAUTH, $scheme)
->set(CURLOPT_USERPWD, $this->username . ':' . $this->password);
}
return $this;
}
public function getResource()
{
$resource = $this->getPath();
if ($query = (string) $this->url->getQuery()) {
$resource .= '?' . $query;
}
return $resource;
}
public function getUrl($asObject = false)
{
return $asObject ? clone $this->url : (string) $this->url;
}
public function getState()
{
return $this->state;
}
public function setState($state, array $context = array())
{
$oldState = $this->state;
$this->state = $state;
switch ($state) {
case self::STATE_NEW:
$this->response = null;
break;
case self::STATE_TRANSFER:
if ($oldState !== $state) {
// Fix Content-Length and Transfer-Encoding collisions
if ($this->hasHeader('Transfer-Encoding') && $this->hasHeader('Content-Length')) {
$this->removeHeader('Transfer-Encoding');
}
$this->dispatch('request.before_send', array('request' => $this));
}
break;
case self::STATE_COMPLETE:
if ($oldState !== $state) {
$this->processResponse($context);
$this->responseBody = null;
}
break;
case self::STATE_ERROR:
if (isset($context['exception'])) {
$this->dispatch('request.exception', array(
'request' => $this,
'response' => isset($context['response']) ? $context['response'] : $this->response,
'exception' => isset($context['exception']) ? $context['exception'] : null
));
}
}
return $this->state;
}
public function getCurlOptions()
{
return $this->curlOptions;
}
public function startResponse(Response $response)
{
$this->state = self::STATE_TRANSFER;
$response->setEffectiveUrl((string) $this->getUrl());
$this->response = $response;
return $this;
}
public function setResponse(Response $response, $queued = false)
{
$response->setEffectiveUrl((string) $this->url);
if ($queued) {
$ed = $this->getEventDispatcher();
$ed->addListener('request.before_send', $f = function ($e) use ($response, &$f, $ed) {
$e['request']->setResponse($response);
$ed->removeListener('request.before_send', $f);
}, -9999);
} else {
$this->response = $response;
// If a specific response body is specified, then use it instead of the response's body
if ($this->responseBody && !$this->responseBody->getCustomData('default') && !$response->isRedirect()) {
$this->getResponseBody()->write((string) $this->response->getBody());
} else {
$this->responseBody = $this->response->getBody();
}
$this->setState(self::STATE_COMPLETE);
}
return $this;
}
public function setResponseBody($body)
{
// Attempt to open a file for writing if a string was passed
if (is_string($body)) {
// @codeCoverageIgnoreStart
if (!($body = fopen($body, 'w+'))) {
throw new InvalidArgumentException('Could not open ' . $body . ' for writing');
}
// @codeCoverageIgnoreEnd
}
$this->responseBody = EntityBody::factory($body);
return $this;
}
public function getResponseBody()
{
if ($this->responseBody === null) {
$this->responseBody = EntityBody::factory()->setCustomData('default', true);
}
return $this->responseBody;
}
/**
* Determine if the response body is repeatable (readable + seekable)
*
* @return bool
* @deprecated Use getResponseBody()->isSeekable()
* @codeCoverageIgnore
*/
public function isResponseBodyRepeatable()
{
Version::warn(__METHOD__ . ' is deprecated. Use $request->getResponseBody()->isRepeatable()');
return !$this->responseBody ? true : $this->responseBody->isRepeatable();
}
public function getCookies()
{
if ($cookie = $this->getHeader('Cookie')) {
$data = ParserRegistry::getInstance()->getParser('cookie')->parseCookie($cookie);
return $data['cookies'];
}
return array();
}
public function getCookie($name)
{
$cookies = $this->getCookies();
return isset($cookies[$name]) ? $cookies[$name] : null;
}
public function addCookie($name, $value)
{
if (!$this->hasHeader('Cookie')) {
$this->setHeader('Cookie', "{$name}={$value}");
} else {
$this->getHeader('Cookie')->add("{$name}={$value}");
}
// Always use semicolons to separate multiple cookie headers
$this->getHeader('Cookie')->setGlue(';');
return $this;
}
public function removeCookie($name)
{
if ($cookie = $this->getHeader('Cookie')) {
foreach ($cookie as $cookieValue) {
if (strpos($cookieValue, $name . '=') === 0) {
$cookie->removeValue($cookieValue);
}
}
}
return $this;
}
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
$this->eventDispatcher->addListener('request.error', array(__CLASS__, 'onRequestError'), -255);
return $this;
}
public function getEventDispatcher()
{
if (!$this->eventDispatcher) {
$this->setEventDispatcher(new EventDispatcher());
}
return $this->eventDispatcher;
}
public function dispatch($eventName, array $context = array())
{
$context['request'] = $this;
$this->getEventDispatcher()->dispatch($eventName, new Event($context));
}
public function addSubscriber(EventSubscriberInterface $subscriber)
{
$this->getEventDispatcher()->addSubscriber($subscriber);
return $this;
}
/**
* {@inheritdoc}
* Adds a check for Host header changes
*/
public function addHeader($header, $value)
{
parent::addHeader($header, $value);
if ($header == 'host' || $header == 'Host') {
$this->setHost((string) $this->getHeader('Host'));
}
return $this;
}
/**
* Get an array containing the request and response for event notifications
*
* @return array
*/
protected function getEventArray()
{
return array(
'request' => $this,
'response' => $this->response
);
}
/**
* Process a received response
*
* @param array $context Contextual information
* @throws RequestException|BadResponseException on unsuccessful responses
*/
protected function processResponse(array $context = array())
{
if (!$this->response) {
// If no response, then processResponse shouldn't have been called
$e = new RequestException('Error completing request');
$e->setRequest($this);
throw $e;
}
$this->state = self::STATE_COMPLETE;
// A request was sent, but we don't know if we'll send more or if the final response will be successful
$this->dispatch('request.sent', $this->getEventArray() + $context);
// Some response processors will remove the response or reset the state (example: ExponentialBackoffPlugin)
if ($this->state == RequestInterface::STATE_COMPLETE) {
// The request completed, so the HTTP transaction is complete
$this->dispatch('request.complete', $this->getEventArray());
// If the response is bad, allow listeners to modify it or throw exceptions. You can change the response by
// modifying the Event object in your listeners or calling setResponse() on the request
if ($this->response->isError()) {
$event = new Event($this->getEventArray());
$this->getEventDispatcher()->dispatch('request.error', $event);
// Allow events of request.error to quietly change the response
if ($event['response'] !== $this->response) {
$this->response = $event['response'];
}
}
// If a successful response was received, dispatch an event
if ($this->response->isSuccessful()) {
$this->dispatch('request.success', $this->getEventArray());
}
}
}
/**
* @deprecated Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy
* @codeCoverageIgnore
*/
public function canCache()
{
Version::warn(__METHOD__ . ' is deprecated. Use Guzzle\Plugin\Cache\DefaultCanCacheStrategy.');
if (class_exists('Guzzle\Plugin\Cache\DefaultCanCacheStrategy')) {
$canCache = new \Guzzle\Plugin\Cache\DefaultCanCacheStrategy();
return $canCache->canCacheRequest($this);
} else {
return false;
}
}
/**
* @deprecated Use the history plugin (not emitting a warning as this is built-into the RedirectPlugin for now)
* @codeCoverageIgnore
*/
public function setIsRedirect($isRedirect)
{
$this->isRedirect = $isRedirect;
return $this;
}
/**
* @deprecated Use the history plugin
* @codeCoverageIgnore
*/
public function isRedirect()
{
Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin to track this.');
return $this->isRedirect;
}
}
Guzzle-3.7.0/Guzzle/Http/Message/RequestFactory.php 0000644 233176441610067500000027615 12155472567 023721 0 ustar dowling ANT\Domain Users methods = array_flip(get_class_methods(__CLASS__));
}
public function fromMessage($message)
{
$parsed = ParserRegistry::getInstance()->getParser('message')->parseRequest($message);
if (!$parsed) {
return false;
}
$request = $this->fromParts($parsed['method'], $parsed['request_url'],
$parsed['headers'], $parsed['body'], $parsed['protocol'],
$parsed['version']);
// EntityEnclosingRequest adds an "Expect: 100-Continue" header when using a raw request body for PUT or POST
// requests. This factory method should accurately reflect the message, so here we are removing the Expect
// header if one was not supplied in the message.
if (!isset($parsed['headers']['Expect']) && !isset($parsed['headers']['expect'])) {
$request->removeHeader('Expect');
}
return $request;
}
public function fromParts(
$method,
array $urlParts,
$headers = null,
$body = null,
$protocol = 'HTTP',
$protocolVersion = '1.1'
) {
return $this->create($method, Url::buildUrl($urlParts), $headers, $body)
->setProtocolVersion($protocolVersion);
}
public function create($method, $url, $headers = null, $body = null, array $options = array())
{
$method = strtoupper($method);
if ($method == 'GET' || $method == 'HEAD' || $method == 'TRACE' || $method == 'OPTIONS') {
// Handle non-entity-enclosing request methods
$request = new $this->requestClass($method, $url, $headers);
if ($body) {
// The body is where the response body will be stored
$type = gettype($body);
if ($type == 'string' || $type == 'resource' || $type == 'object') {
$request->setResponseBody($body);
}
}
} else {
// Create an entity enclosing request by default
$request = new $this->entityEnclosingRequestClass($method, $url, $headers);
if ($body) {
// Add POST fields and files to an entity enclosing request if an array is used
if (is_array($body) || $body instanceof Collection) {
// Normalize PHP style cURL uploads with a leading '@' symbol
foreach ($body as $key => $value) {
if (is_string($value) && substr($value, 0, 1) == '@') {
$request->addPostFile($key, $value);
unset($body[$key]);
}
}
// Add the fields if they are still present and not all files
$request->addPostFields($body);
} else {
// Add a raw entity body body to the request
$request->setBody($body, (string) $request->getHeader('Content-Type'));
if ((string) $request->getHeader('Transfer-Encoding') == 'chunked') {
$request->removeHeader('Content-Length');
}
}
}
}
if ($options) {
$this->applyOptions($request, $options);
}
return $request;
}
/**
* Clone a request while changing the method. Emulates the behavior of
* {@see Guzzle\Http\Message\Request::clone}, but can change the HTTP method.
*
* @param RequestInterface $request Request to clone
* @param string $method Method to set
*
* @return RequestInterface
*/
public function cloneRequestWithMethod(RequestInterface $request, $method)
{
// Create the request with the same client if possible
if ($client = $request->getClient()) {
$cloned = $request->getClient()->createRequest($method, $request->getUrl(), $request->getHeaders());
} else {
$cloned = $this->create($method, $request->getUrl(), $request->getHeaders());
}
$cloned->getCurlOptions()->replace($request->getCurlOptions()->toArray());
$cloned->setEventDispatcher(clone $request->getEventDispatcher());
// Ensure that that the Content-Length header is not copied if changing to GET or HEAD
if (!($cloned instanceof EntityEnclosingRequestInterface)) {
$cloned->removeHeader('Content-Length');
} elseif ($request instanceof EntityEnclosingRequestInterface) {
$cloned->setBody($request->getBody());
}
$cloned->getParams()->replace($request->getParams()->toArray());
$cloned->dispatch('request.clone', array('request' => $cloned));
return $cloned;
}
public function applyOptions(RequestInterface $request, array $options = array(), $flags = self::OPTIONS_NONE)
{
// Iterate over each key value pair and attempt to apply a config using function visitors
foreach ($options as $key => $value) {
$method = "visit_{$key}";
if (isset($this->methods[$method])) {
$this->{$method}($request, $value, $flags);
}
}
}
protected function visit_headers(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('headers value must be an array');
}
if ($flags & self::OPTIONS_AS_DEFAULTS) {
// Merge headers in but do not overwrite existing values
foreach ($value as $key => $header) {
if (!$request->hasHeader($key)) {
$request->setHeader($key, $header);
}
}
} else {
$request->addHeaders($value);
}
}
protected function visit_body(RequestInterface $request, $value, $flags)
{
if ($request instanceof EntityEnclosingRequestInterface) {
$request->setBody($value);
} else {
throw new InvalidArgumentException('Attempting to set a body on a non-entity-enclosing request');
}
}
protected function visit_allow_redirects(RequestInterface $request, $value, $flags)
{
if ($value === false) {
$request->getParams()->set(RedirectPlugin::DISABLE, true);
}
}
protected function visit_auth(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('auth value must be an array');
}
$request->setAuth($value[0], isset($value[1]) ? $value[1] : null, isset($value[2]) ? $value[2] : 'basic');
}
protected function visit_query(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('query value must be an array');
}
if ($flags & self::OPTIONS_AS_DEFAULTS) {
// Merge query string values in but do not overwrite existing values
$query = $request->getQuery();
$query->overwriteWith(array_diff_key($value, $query->toArray()));
} else {
$request->getQuery()->overwriteWith($value);
}
}
protected function visit_cookies(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('cookies value must be an array');
}
foreach ($value as $name => $v) {
$request->addCookie($name, $v);
}
}
protected function visit_events(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('events value must be an array');
}
foreach ($value as $name => $method) {
if (is_array($method)) {
$request->getEventDispatcher()->addListener($name, $method[0], $method[1]);
} else {
$request->getEventDispatcher()->addListener($name, $method);
}
}
}
protected function visit_plugins(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('plugins value must be an array');
}
foreach ($value as $plugin) {
$request->addSubscriber($plugin);
}
}
protected function visit_exceptions(RequestInterface $request, $value, $flags)
{
if ($value === false || $value === 0) {
$dispatcher = $request->getEventDispatcher();
foreach ($dispatcher->getListeners('request.error') as $listener) {
if ($listener[0] == 'Guzzle\Http\Message\Request' && $listener[1] = 'onRequestError') {
$dispatcher->removeListener('request.error', $listener);
break;
}
}
}
}
protected function visit_save_to(RequestInterface $request, $value, $flags)
{
$request->setResponseBody($value);
}
protected function visit_params(RequestInterface $request, $value, $flags)
{
if (!is_array($value)) {
throw new InvalidArgumentException('params value must be an array');
}
$request->getParams()->overwriteWith($value);
}
protected function visit_timeout(RequestInterface $request, $value, $flags)
{
$request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, $value * 1000);
}
protected function visit_connect_timeout(RequestInterface $request, $value, $flags)
{
$request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT_MS, $value * 1000);
}
protected function visit_debug(RequestInterface $request, $value, $flags)
{
if (class_exists('Guzzle\Plugin\Log\LogPlugin')) {
$request->addSubscriber(LogPlugin::getDebugPlugin());
} else {
// @codeCoverageIgnoreStart
$request->getCurlOptions()->set(CURLOPT_VERBOSE, true);
// @codeCoverageIgnoreEnd
}
}
protected function visit_verify(RequestInterface $request, $value, $flags)
{
$curl = $request->getCurlOptions();
if ($value === true || is_string($value)) {
$curl[CURLOPT_SSL_VERIFYHOST] = 2;
$curl[CURLOPT_SSL_VERIFYPEER] = true;
if ($value !== true) {
$curl[CURLOPT_CAINFO] = $value;
}
} elseif ($value === false) {
unset($curl[CURLOPT_CAINFO]);
$curl[CURLOPT_SSL_VERIFYHOST] = 0;
$curl[CURLOPT_SSL_VERIFYPEER] = false;
}
}
protected function visit_proxy(RequestInterface $request, $value, $flags)
{
$request->getCurlOptions()->set(CURLOPT_PROXY, $value, $flags);
}
}
Guzzle-3.7.0/Guzzle/Http/Message/RequestFactoryInterface.php 0000644 233176441610067500000011521 12155472567 025527 0 ustar dowling ANT\Domain Users '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 EntityBodyInterface The response body */
protected $body;
/** @var string The reason phrase of the response (human readable code) */
protected $reasonPhrase;
/** @var string The status code of the response */
protected $statusCode;
/** @var array Information about the request */
protected $info = array();
/** @var string The effective URL that returned this response */
protected $effectiveUrl;
/** @var array Cacheable response codes (see RFC 2616:13.4) */
protected static $cacheResponseCodes = array(200, 203, 206, 300, 301, 410);
/**
* Create a new Response based on a raw response message
*
* @param string $message Response message
*
* @return self|bool Returns false on error
*/
public static function fromMessage($message)
{
$data = ParserRegistry::getInstance()->getParser('message')->parseResponse($message);
if (!$data) {
return false;
}
$response = new static($data['code'], $data['headers'], $data['body']);
$response->setProtocol($data['protocol'], $data['version'])
->setStatus($data['code'], $data['reason_phrase']);
// Set the appropriate Content-Length if the one set is inaccurate (e.g. setting to X)
$contentLength = (string) $response->getHeader('Content-Length');
$actualLength = strlen($data['body']);
if (strlen($data['body']) > 0 && $contentLength != $actualLength) {
$response->setHeader('Content-Length', $actualLength);
}
return $response;
}
/**
* Construct the response
*
* @param string $statusCode The response status code (e.g. 200, 404, etc)
* @param ToArrayInterface|array $headers The response headers
* @param string|resource|EntityBodyInterface $body The body of the response
*
* @throws BadResponseException if an invalid response code is given
*/
public function __construct($statusCode, $headers = null, $body = null)
{
parent::__construct();
$this->setStatus($statusCode);
$this->body = EntityBody::factory($body !== null ? $body : '');
if ($headers) {
if (is_array($headers)) {
$this->setHeaders($headers);
} elseif ($headers instanceof ToArrayInterface) {
$this->setHeaders($headers->toArray());
} else {
throw new BadResponseException('Invalid headers argument received');
}
}
}
/**
* @return string
*/
public function __toString()
{
return $this->getMessage();
}
public function serialize()
{
return json_encode(array(
'status' => $this->statusCode,
'body' => (string) $this->body,
'headers' => $this->headers->toArray()
));
}
public function unserialize($serialize)
{
$data = json_decode($serialize, true);
$this->__construct($data['status'], $data['headers'], $data['body']);
}
/**
* Get the response entity body
*
* @param bool $asString Set to TRUE to return a string of the body rather than a full body object
*
* @return EntityBodyInterface|string
*/
public function getBody($asString = false)
{
return $asString ? (string) $this->body : $this->body;
}
/**
* Set the response entity body
*
* @param EntityBodyInterface|string $body Body to set
*
* @return self
*/
public function setBody($body)
{
$this->body = EntityBody::factory($body);
return $this;
}
/**
* Set the protocol and protocol version of the response
*
* @param string $protocol Response protocol
* @param string $version Protocol version
*
* @return self
*/
public function setProtocol($protocol, $version)
{
$this->protocol = $protocol;
$this->protocolVersion = $version;
return $this;
}
/**
* Get the protocol used for the response (e.g. HTTP)
*
* @return string
*/
public function getProtocol()
{
return $this->protocol;
}
/**
* Get the HTTP protocol version
*
* @return string
*/
public function getProtocolVersion()
{
return $this->protocolVersion;
}
/**
* Get a cURL transfer information
*
* @param string $key A single statistic to check
*
* @return array|string|null Returns all stats if no key is set, a single stat if a key is set, or null if a key
* is set and not found
* @link http://www.php.net/manual/en/function.curl-getinfo.php
*/
public function getInfo($key = null)
{
if ($key === null) {
return $this->info;
} elseif (array_key_exists($key, $this->info)) {
return $this->info[$key];
} else {
return null;
}
}
/**
* Set the transfer information
*
* @param array $info Array of cURL transfer stats
*
* @return self
*/
public function setInfo(array $info)
{
$this->info = $info;
return $this;
}
/**
* Set the response status
*
* @param int $statusCode Response status code to set
* @param string $reasonPhrase Response reason phrase
*
* @return self
* @throws BadResponseException when an invalid response code is received
*/
public function setStatus($statusCode, $reasonPhrase = '')
{
$this->statusCode = (int) $statusCode;
if (!$reasonPhrase && isset(self::$statusTexts[$this->statusCode])) {
$this->reasonPhrase = self::$statusTexts[$this->statusCode];
} else {
$this->reasonPhrase = $reasonPhrase;
}
return $this;
}
/**
* Get the response status code
*
* @return integer
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* Get the entire response as a string
*
* @return string
*/
public function getMessage()
{
$message = $this->getRawHeaders();
// Only include the body in the message if the size is < 2MB
$size = $this->body->getSize();
if ($size < 2097152) {
$message .= (string) $this->body;
}
return $message;
}
/**
* Get the the raw message headers as a string
*
* @return string
*/
public function getRawHeaders()
{
$headers = 'HTTP/1.1 ' . $this->statusCode . ' ' . $this->reasonPhrase . "\r\n";
$lines = $this->getHeaderLines();
if (!empty($lines)) {
$headers .= implode("\r\n", $lines) . "\r\n";
}
return $headers . "\r\n";
}
/**
* Get the response reason phrase- a human readable version of the numeric
* status code
*
* @return string
*/
public function getReasonPhrase()
{
return $this->reasonPhrase;
}
/**
* Get the Accept-Ranges HTTP header
*
* @return string Returns what partial content range types this server supports.
*/
public function getAcceptRanges()
{
return (string) $this->getHeader('Accept-Ranges');
}
/**
* Calculate the age of the response
*
* @return integer
*/
public function calculateAge()
{
$age = $this->getHeader('Age');
if ($age === null && $this->getDate()) {
$age = time() - strtotime($this->getDate());
}
return $age === null ? null : (int) (string) $age;
}
/**
* Get the Age HTTP header
*
* @return integer|null Returns the age the object has been in a proxy cache in seconds.
*/
public function getAge()
{
return (string) $this->getHeader('Age');
}
/**
* Get the Allow HTTP header
*
* @return string|null Returns valid actions for a specified resource. To be used for a 405 Method not allowed.
*/
public function getAllow()
{
return (string) $this->getHeader('Allow');
}
/**
* Check if an HTTP method is allowed by checking the Allow response header
*
* @param string $method Method to check
*
* @return bool
*/
public function isMethodAllowed($method)
{
$allow = $this->getHeader('Allow');
if ($allow) {
foreach (explode(',', $allow) as $allowable) {
if (!strcasecmp(trim($allowable), $method)) {
return true;
}
}
}
return false;
}
/**
* Get the Cache-Control HTTP header
*
* @return string
*/
public function getCacheControl()
{
return (string) $this->getHeader('Cache-Control');
}
/**
* Get the Connection HTTP header
*
* @return string
*/
public function getConnection()
{
return (string) $this->getHeader('Connection');
}
/**
* Get the Content-Encoding HTTP header
*
* @return string|null
*/
public function getContentEncoding()
{
return (string) $this->getHeader('Content-Encoding');
}
/**
* Get the Content-Language HTTP header
*
* @return string|null Returns the language the content is in.
*/
public function getContentLanguage()
{
return (string) $this->getHeader('Content-Language');
}
/**
* Get the Content-Length HTTP header
*
* @return integer Returns the length of the response body in bytes
*/
public function getContentLength()
{
return (int) (string) $this->getHeader('Content-Length');
}
/**
* Get the Content-Location HTTP header
*
* @return string|null Returns an alternate location for the returned data (e.g /index.htm)
*/
public function getContentLocation()
{
return (string) $this->getHeader('Content-Location');
}
/**
* Get the Content-Disposition HTTP header
*
* @return string|null Returns the Content-Disposition header
*/
public function getContentDisposition()
{
return (string) $this->getHeader('Content-Disposition');
}
/**
* Get the Content-MD5 HTTP header
*
* @return string|null Returns a Base64-encoded binary MD5 sum of the content of the response.
*/
public function getContentMd5()
{
return (string) $this->getHeader('Content-MD5');
}
/**
* Get the Content-Range HTTP header
*
* @return string Returns where in a full body message this partial message belongs (e.g. bytes 21010-47021/47022).
*/
public function getContentRange()
{
return (string) $this->getHeader('Content-Range');
}
/**
* Get the Content-Type HTTP header
*
* @return string Returns the mime type of this content.
*/
public function getContentType()
{
return (string) $this->getHeader('Content-Type');
}
/**
* Checks if the Content-Type is of a certain type. This is useful if the
* Content-Type header contains charset information and you need to know if
* the Content-Type matches a particular type.
*
* @param string $type Content type to check against
*
* @return bool
*/
public function isContentType($type)
{
return stripos($this->getHeader('Content-Type'), $type) !== false;
}
/**
* Get the Date HTTP header
*
* @return string|null Returns the date and time that the message was sent.
*/
public function getDate()
{
return (string) $this->getHeader('Date');
}
/**
* Get the ETag HTTP header
*
* @return string|null Returns an identifier for a specific version of a resource, often a Message digest.
*/
public function getEtag()
{
return (string) $this->getHeader('ETag');
}
/**
* Get the Expires HTTP header
*
* @return string|null Returns the date/time after which the response is considered stale.
*/
public function getExpires()
{
return (string) $this->getHeader('Expires');
}
/**
* Get the Last-Modified HTTP header
*
* @return string|null Returns the last modified date for the requested object, in RFC 2822 format
* (e.g. Tue, 15 Nov 1994 12:45:26 GMT)
*/
public function getLastModified()
{
return (string) $this->getHeader('Last-Modified');
}
/**
* Get the Location HTTP header
*
* @return string|null Used in redirection, or when a new resource has been created.
*/
public function getLocation()
{
return (string) $this->getHeader('Location');
}
/**
* Get the Pragma HTTP header
*
* @return Header|null Returns the implementation-specific headers that may have various effects anywhere along
* the request-response chain.
*/
public function getPragma()
{
return (string) $this->getHeader('Pragma');
}
/**
* Get the Proxy-Authenticate HTTP header
*
* @return string|null Authentication to access the proxy (e.g. Basic)
*/
public function getProxyAuthenticate()
{
return (string) $this->getHeader('Proxy-Authenticate');
}
/**
* Get the Retry-After HTTP header
*
* @return int|null If an entity is temporarily unavailable, this instructs the client to try again after a
* specified period of time.
*/
public function getRetryAfter()
{
return (string) $this->getHeader('Retry-After');
}
/**
* Get the Server HTTP header
*
* @return string|null A name for the server
*/
public function getServer()
{
return (string) $this->getHeader('Server');
}
/**
* Get the Set-Cookie HTTP header
*
* @return string|null An HTTP cookie.
*/
public function getSetCookie()
{
return (string) $this->getHeader('Set-Cookie');
}
/**
* Get the Trailer HTTP header
*
* @return string|null The Trailer general field value indicates that the given set of header fields is present in
* the trailer of a message encoded with chunked transfer-coding.
*/
public function getTrailer()
{
return (string) $this->getHeader('Trailer');
}
/**
* Get the Transfer-Encoding HTTP header
*
* @return string|null The form of encoding used to safely transfer the entity to the user
*/
public function getTransferEncoding()
{
return (string) $this->getHeader('Transfer-Encoding');
}
/**
* Get the Vary HTTP header
*
* @return string|null Tells downstream proxies how to match future request headers to decide whether the cached
* response can be used rather than requesting a fresh one from the origin server.
*/
public function getVary()
{
return (string) $this->getHeader('Vary');
}
/**
* Get the Via HTTP header
*
* @return string|null Informs the client of proxies through which the response was sent.
*/
public function getVia()
{
return (string) $this->getHeader('Via');
}
/**
* Get the Warning HTTP header
*
* @return string|null A general warning about possible problems with the entity body
*/
public function getWarning()
{
return (string) $this->getHeader('Warning');
}
/**
* Get the WWW-Authenticate HTTP header
*
* @return string|null Indicates the authentication scheme that should be used to access the requested entity
*/
public function getWwwAuthenticate()
{
return (string) $this->getHeader('WWW-Authenticate');
}
/**
* Checks if HTTP Status code is a Client Error (4xx)
*
* @return bool
*/
public function isClientError()
{
return $this->statusCode >= 400 && $this->statusCode < 500;
}
/**
* Checks if HTTP Status code is Server OR Client Error (4xx or 5xx)
*
* @return boolean
*/
public function isError()
{
return $this->isClientError() || $this->isServerError();
}
/**
* Checks if HTTP Status code is Information (1xx)
*
* @return bool
*/
public function isInformational()
{
return $this->statusCode < 200;
}
/**
* Checks if HTTP Status code is a Redirect (3xx)
*
* @return bool
*/
public function isRedirect()
{
return $this->statusCode >= 300 && $this->statusCode < 400;
}
/**
* Checks if HTTP Status code is Server Error (5xx)
*
* @return bool
*/
public function isServerError()
{
return $this->statusCode >= 500 && $this->statusCode < 600;
}
/**
* Checks if HTTP Status code is Successful (2xx | 304)
*
* @return bool
*/
public function isSuccessful()
{
return ($this->statusCode >= 200 && $this->statusCode < 300) || $this->statusCode == 304;
}
/**
* Check if the response can be cached based on the response headers
*
* @return bool Returns TRUE if the response can be cached or false if not
*/
public function canCache()
{
// Check if the response is cacheable based on the code
if (!in_array((int) $this->getStatusCode(), self::$cacheResponseCodes)) {
return false;
}
// Make sure a valid body was returned and can be cached
if ((!$this->getBody()->isReadable() || !$this->getBody()->isSeekable())
&& ($this->getContentLength() > 0 || $this->getTransferEncoding() == 'chunked')) {
return false;
}
// Never cache no-store resources (this is a private cache, so private
// can be cached)
if ($this->getHeader('Cache-Control') && $this->getHeader('Cache-Control')->hasDirective('no-store')) {
return false;
}
return $this->isFresh() || $this->getFreshness() === null || $this->canValidate();
}
/**
* Gets the number of seconds from the current time in which this response is still considered fresh
*
* @return int|null Returns the number of seconds
*/
public function getMaxAge()
{
if ($header = $this->getHeader('Cache-Control')) {
// s-max-age, then max-age, then Expires
if ($age = $header->getDirective('s-maxage')) {
return $age;
}
if ($age = $header->getDirective('max-age')) {
return $age;
}
}
if ($this->getHeader('Expires')) {
return strtotime($this->getExpires()) - time();
}
return null;
}
/**
* Check if the response is considered fresh.
*
* A response is considered fresh when its age is less than or equal to the freshness lifetime (maximum age) of the
* response.
*
* @return bool|null
*/
public function isFresh()
{
$fresh = $this->getFreshness();
return $fresh === null ? null : $fresh >= 0;
}
/**
* Check if the response can be validated against the origin server using a conditional GET request.
*
* @return bool
*/
public function canValidate()
{
return $this->getEtag() || $this->getLastModified();
}
/**
* Get the freshness of the response by returning the difference of the maximum lifetime of the response and the
* age of the response (max-age - age).
*
* Freshness values less than 0 mean that the response is no longer fresh and is ABS(freshness) seconds expired.
* Freshness values of greater than zero is the number of seconds until the response is no longer fresh. A NULL
* result means that no freshness information is available.
*
* @return int
*/
public function getFreshness()
{
$maxAge = $this->getMaxAge();
$age = $this->calculateAge();
return $maxAge && $age ? ($maxAge - $age) : null;
}
/**
* Parse the JSON response body and return an array
*
* @return array|string|int|bool|float
* @throws RuntimeException if the response body is not in JSON format
*/
public function json()
{
$data = json_decode((string) $this->body, true);
if (JSON_ERROR_NONE !== json_last_error()) {
throw new RuntimeException('Unable to parse response body into JSON: ' . json_last_error());
}
return $data === null ? array() : $data;
}
/**
* Parse the XML response body and return a SimpleXMLElement
*
* @return \SimpleXMLElement
* @throws RuntimeException if the response body is not in XML format
*/
public function xml()
{
try {
// Allow XML to be retrieved even if there is no response body
$xml = new \SimpleXMLElement((string) $this->body ?: '');
} catch (\Exception $e) {
throw new RuntimeException('Unable to parse response body into XML: ' . $e->getMessage());
}
return $xml;
}
/**
* Get the redirect count of this response
*
* @return int
*/
public function getRedirectCount()
{
return (int) $this->params->get(RedirectPlugin::REDIRECT_COUNT);
}
/**
* Set the effective URL that resulted in this response (e.g. the last redirect URL)
*
* @param string $url The effective URL
*
* @return self
*/
public function setEffectiveUrl($url)
{
$this->effectiveUrl = $url;
return $this;
}
/**
* Get the effective URL that resulted in this response (e.g. the last redirect URL)
*
* @return string
*/
public function getEffectiveUrl()
{
return $this->effectiveUrl;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getPreviousResponse()
{
Version::warn(__METHOD__ . ' is deprecated. Use the HistoryPlugin.');
return null;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function setRequest($request)
{
Version::warn(__METHOD__ . ' is deprecated');
return $this;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function getRequest()
{
Version::warn(__METHOD__ . ' is deprecated');
return null;
}
}
Guzzle-3.7.0/Guzzle/Http/Message/Header/CacheControl.php 0000644 233176441610067500000005366 12155472567 024474 0 ustar dowling ANT\Domain Users directives = null;
}
public function removeValue($searchValue)
{
parent::removeValue($searchValue);
$this->directives = null;
}
/**
* Check if a specific cache control directive exists
*
* @param string $param Directive to retrieve
*
* @return bool
*/
public function hasDirective($param)
{
$directives = $this->getDirectives();
return isset($directives[$param]);
}
/**
* Get a specific cache control directive
*
* @param string $param Directive to retrieve
*
* @return string|bool|null
*/
public function getDirective($param)
{
$directives = $this->getDirectives();
return isset($directives[$param]) ? $directives[$param] : null;
}
/**
* Add a cache control directive
*
* @param string $param Directive to add
* @param string $value Value to set
*
* @return self
*/
public function addDirective($param, $value)
{
$directives = $this->getDirectives();
$directives[$param] = $value;
$this->updateFromDirectives($directives);
return $this;
}
/**
* Remove a cache control directive by name
*
* @param string $param Directive to remove
*
* @return self
*/
public function removeDirective($param)
{
$directives = $this->getDirectives();
unset($directives[$param]);
$this->updateFromDirectives($directives);
return $this;
}
/**
* Get an associative array of cache control directives
*
* @return array
*/
public function getDirectives()
{
if ($this->directives === null) {
$this->directives = array();
foreach ($this->parseParams() as $collection) {
foreach ($collection as $key => $value) {
$this->directives[$key] = $value === '' ? true : $value;
}
}
}
return $this->directives;
}
/**
* Updates the header value based on the parsed directives
*
* @param array $directives Array of cache control directives
*/
protected function updateFromDirectives(array $directives)
{
$this->directives = $directives;
$this->values = array();
foreach ($directives as $key => $value) {
$this->values[] = $value === true ? $key : "{$key}={$value}";
}
}
}
Guzzle-3.7.0/Guzzle/Http/Message/Header/HeaderCollection.php 0000644 233176441610067500000004076 12155472567 025331 0 ustar dowling ANT\Domain Users headers = $headers;
}
public function __clone()
{
foreach ($this->headers as &$header) {
$header = clone $header;
}
}
/**
* Clears the header collection
*/
public function clear()
{
$this->headers = array();
}
/**
* Set a header on the collection
*
* @param HeaderInterface $header Header to add
*
* @return self
*/
public function add(HeaderInterface $header)
{
$this->headers[strtolower($header->getName())] = $header;
return $this;
}
/**
* Get an array of header objects
*
* @return array
*/
public function getAll()
{
return $this->headers;
}
/**
* Alias of offsetGet
*/
public function get($key)
{
return $this->offsetGet($key);
}
public function count()
{
return count($this->headers);
}
public function offsetExists($offset)
{
return isset($this->headers[strtolower($offset)]);
}
public function offsetGet($offset)
{
$l = strtolower($offset);
return isset($this->headers[$l]) ? $this->headers[$l] : null;
}
public function offsetSet($offset, $value)
{
$this->add($value);
}
public function offsetUnset($offset)
{
unset($this->headers[strtolower($offset)]);
}
public function getIterator()
{
return new \ArrayIterator($this->headers);
}
public function toArray()
{
$result = array();
foreach ($this->headers as $header) {
$result[$header->getName()] = $header->toArray();
}
return $result;
}
}
Guzzle-3.7.0/Guzzle/Http/Message/Header/HeaderFactory.php 0000644 233176441610067500000001206 12155472567 024635 0 ustar dowling ANT\Domain Users 'Guzzle\Http\Message\Header\CacheControl',
'link' => 'Guzzle\Http\Message\Header\Link',
);
public function createHeader($header, $value = null)
{
$lowercase = strtolower($header);
return isset($this->mapping[$lowercase])
? new $this->mapping[$lowercase]($header, $value)
: new Header($header, $value);
}
}
Guzzle-3.7.0/Guzzle/Http/Message/Header/HeaderFactoryInterface.php 0000644 233176441610067500000000643 12155472567 026462 0 ustar dowling ANT\Domain Users ", "rel=\"{$rel}\"");
foreach ($params as $k => $v) {
$values[] = "{$k}=\"{$v}\"";
}
return $this->add(implode('; ', $values));
}
/**
* Check if a specific link exists for a given rel attribute
*
* @param string $rel rel value
*
* @return bool
*/
public function hasLink($rel)
{
return $this->getLink($rel) !== null;
}
/**
* Get a specific link for a given rel attribute
*
* @param string $rel Rel value
*
* @return array|null
*/
public function getLink($rel)
{
foreach ($this->getLinks() as $link) {
if (isset($link['rel']) && $link['rel'] == $rel) {
return $link;
}
}
return null;
}
/**
* Get an associative array of links
*
* For example:
* Link: ; rel=front; type="image/jpeg", ; rel=back; type="image/jpeg"
*
*
* var_export($response->getLinks());
* array(
* array(
* 'url' => 'http:/.../front.jpeg',
* 'rel' => 'back',
* 'type' => 'image/jpeg',
* )
* )
*
*
* @return array
*/
public function getLinks()
{
$links = $this->parseParams();
foreach ($links as &$link) {
$key = key($link);
unset($link[$key]);
$link['url'] = trim($key, '<> ');
}
return $links;
}
}
Guzzle-3.7.0/Guzzle/Http/QueryAggregator/CommaAggregator.php 0000644 233176441610067500000001010 12155472567 025501 0 ustar dowling ANT\Domain Users isUrlEncoding()) {
return array($query->encodeValue($key) => implode(',', array_map(array($query, 'encodeValue'), $value)));
} else {
return array($key => implode(',', $value));
}
}
}
Guzzle-3.7.0/Guzzle/Http/QueryAggregator/DuplicateAggregator.php 0000644 233176441610067500000001074 12155472567 026371 0 ustar dowling ANT\Domain Users isUrlEncoding()) {
return array($query->encodeValue($key) => array_map(array($query, 'encodeValue'), $value));
} else {
return array($key => $value);
}
}
}
Guzzle-3.7.0/Guzzle/Http/QueryAggregator/PhpAggregator.php 0000644 233176441610067500000001164 12155472567 025206 0 ustar dowling ANT\Domain Users $v) {
$k = "{$key}[{$k}]";
if (is_array($v)) {
$ret = array_merge($ret, self::aggregate($k, $v, $query));
} else {
$ret[$query->encodeValue($k)] = $query->encodeValue($v);
}
}
return $ret;
}
}
Guzzle-3.7.0/Guzzle/Http/QueryAggregator/QueryAggregatorInterface.php 0000644 233176441610067500000001236 12155472567 027405 0 ustar dowling ANT\Domain Users array(),
'camel' => array()
);
/** @var int Max entries per cache */
protected $maxCacheSize;
/** @var InflectorInterface Decorated inflector */
protected $decoratedInflector;
/**
* @param InflectorInterface $inflector Inflector being decorated
* @param int $maxCacheSize Maximum number of cached items to hold per cache
*/
public function __construct(InflectorInterface $inflector, $maxCacheSize = 500)
{
$this->decoratedInflector = $inflector;
$this->maxCacheSize = $maxCacheSize;
}
public function snake($word)
{
if (!isset($this->cache['snake'][$word])) {
$this->pruneCache('snake');
$this->cache['snake'][$word] = $this->decoratedInflector->snake($word);
}
return $this->cache['snake'][$word];
}
/**
* Converts strings from snake_case to upper CamelCase
*
* @param string $word Value to convert into upper CamelCase
*
* @return string
*/
public function camel($word)
{
if (!isset($this->cache['camel'][$word])) {
$this->pruneCache('camel');
$this->cache['camel'][$word] = $this->decoratedInflector->camel($word);
}
return $this->cache['camel'][$word];
}
/**
* Prune one of the named caches by removing 20% of the cache if it is full
*
* @param string $cache Type of cache to prune
*/
protected function pruneCache($cache)
{
if (count($this->cache[$cache]) == $this->maxCacheSize) {
$this->cache[$cache] = array_slice($this->cache[$cache], $this->maxCacheSize * 0.2);
}
}
}
Guzzle-3.7.0/Guzzle/Inflection/PreComputedInflector.php 0000644 233176441610067500000003353 12155472567 024616 0 ustar dowling ANT\Domain Users array(),
'camel' => array()
);
/** @var InflectorInterface Decorated inflector */
protected $decoratedInflector;
/**
* @param InflectorInterface $inflector Inflector being decorated
* @param array $snake Hash of pre-computed camel to snake
* @param array $camel Hash of pre-computed snake to camel
* @param bool $mirror Mirror snake and camel reflections
*/
public function __construct(InflectorInterface $inflector, array $snake = array(), array $camel = array(), $mirror = false)
{
if ($mirror) {
$camel = array_merge(array_flip($snake), $camel);
$snake = array_merge(array_flip($camel), $snake);
}
$this->decoratedInflector = $inflector;
$this->mapping = array(
'snake' => $snake,
'camel' => $camel
);
}
public function snake($word)
{
return isset($this->mapping['snake'][$word])
? $this->mapping['snake'][$word]
: $this->decoratedInflector->snake($word);
}
/**
* Converts strings from snake_case to upper CamelCase
*
* @param string $word Value to convert into upper CamelCase
*
* @return string
*/
public function camel($word)
{
return isset($this->mapping['camel'][$word])
? $this->mapping['camel'][$word]
: $this->decoratedInflector->camel($word);
}
}
Guzzle-3.7.0/Guzzle/Iterator/AppendIterator.php 0000644 233176441610067500000000674 12155472567 023144 0 ustar dowling ANT\Domain Users getArrayIterator()->append($iterator);
}
}
Guzzle-3.7.0/Guzzle/Iterator/ChunkedIterator.php 0000644 233176441610067500000002067 12155472567 023314 0 ustar dowling ANT\Domain Users chunkSize = $chunkSize;
}
public function rewind()
{
$this->next();
}
public function next()
{
$this->chunk = array();
$inner = $this->getInnerIterator();
for ($i = 0; $i < $this->chunkSize && $inner->valid(); $i++) {
$this->chunk[] = $inner->current();
$inner->next();
}
}
public function current()
{
return $this->chunk;
}
public function valid()
{
return !empty($this->chunk);
}
}
Guzzle-3.7.0/Guzzle/Iterator/FilterIterator.php 0000644 233176441610067500000001735 12155472567 023161 0 ustar dowling ANT\Domain Users callback = $callback;
}
public function accept()
{
return call_user_func($this->callback, $this->current());
}
}
Guzzle-3.7.0/Guzzle/Iterator/MapIterator.php 0000644 233176441610067500000001524 12155472567 022445 0 ustar dowling ANT\Domain Users callback = $callback;
}
public function current()
{
return call_user_func($this->callback, parent::current());
}
}
Guzzle-3.7.0/Guzzle/Iterator/MethodProxyIterator.php 0000644 233176441610067500000001142 12155472567 024206 0 ustar dowling ANT\Domain Users getInnerIterator();
while ($i instanceof \OuterIterator) {
$i = $i->getInnerIterator();
}
return call_user_func_array(array($i, $name), $args);
}
}
Guzzle-3.7.0/Guzzle/Iterator/README.md 0000644 233176441610067500000001232 12155472567 020760 0 ustar dowling ANT\Domain Users Guzzle Iterator
===============
Provides useful Iterators and Iterator decorators
- ChunkedIterator: Pulls out chunks from an inner iterator and yields the chunks as arrays
- FilterIterator: Used when PHP 5.4's CallbackFilterIterator is not available
- MapIterator: Maps values before yielding
- MethodProxyIterator: Proxies missing method calls to the innermost iterator
### Installing via Composer
```bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
# Add Guzzle as a dependency
php composer.phar require guzzle/iterator:~3.0
```
After installing, you need to require Composer's autoloader:
```php
require 'vendor/autoload.php';
```
Guzzle-3.7.0/Guzzle/Log/AbstractLogAdapter.php 0000644 233176441610067500000000440 12155472567 022650 0 ustar dowling ANT\Domain Users log;
}
}
Guzzle-3.7.0/Guzzle/Log/ArrayLogAdapter.php 0000644 233176441610067500000001147 12155472567 022170 0 ustar dowling ANT\Domain Users logs[] = array('message' => $message, 'priority' => $priority, 'extras' => $extras);
}
/**
* Get logged entries
*
* @return array
*/
public function getLogs()
{
return $this->logs;
}
/**
* Clears logged entries
*/
public function clearLogs()
{
$this->logs = array();
}
}
Guzzle-3.7.0/Guzzle/Log/ClosureLogAdapter.php 0000644 233176441610067500000001107 12155472567 022522 0 ustar dowling ANT\Domain Users log = $logObject;
}
public function log($message, $priority = LOG_INFO, $extras = array())
{
call_user_func($this->log, $message, $priority, $extras);
}
}
Guzzle-3.7.0/Guzzle/Log/LogAdapterInterface.php 0000644 233176441610067500000000753 12155472567 023014 0 ustar dowling ANT\Domain Users >>>>>>>\n{request}\n<<<<<<<<\n{response}\n--------\n{curl_stderr}";
const SHORT_FORMAT = '[{ts}] "{method} {resource} {protocol}/{version}" {code}';
/**
* @var string Template used to format log messages
*/
protected $template;
/**
* @param string $template Log message template
*/
public function __construct($template = self::DEFAULT_FORMAT)
{
$this->template = $template ?: self::DEFAULT_FORMAT;
}
/**
* Set the template to use for logging
*
* @param string $template Log message template
*
* @return self
*/
public function setTemplate($template)
{
$this->template = $template;
return $this;
}
/**
* Returns a formatted message
*
* @param RequestInterface $request Request that was sent
* @param Response $response Response that was received
* @param CurlHandle $handle Curl handle associated with the message
* @param array $customData Associative array of custom template data
*
* @return string
*/
public function format(
RequestInterface $request,
Response $response = null,
CurlHandle $handle = null,
array $customData = array()
) {
$cache = $customData;
return preg_replace_callback(
'/{\s*([A-Za-z_\-\.0-9]+)\s*}/',
function (array $matches) use ($request, $response, $handle, &$cache) {
if (array_key_exists($matches[1], $cache)) {
return $cache[$matches[1]];
}
$result = '';
switch ($matches[1]) {
case 'request':
$result = (string) $request;
break;
case 'response':
$result = (string) $response;
break;
case 'req_body':
$result = $request instanceof EntityEnclosingRequestInterface
? (string) $request->getBody() : '';
break;
case 'res_body':
$result = $response ? $response->getBody(true) : '';
break;
case 'ts':
$result = gmdate('c');
break;
case 'method':
$result = $request->getMethod();
break;
case 'url':
$result = (string) $request->getUrl();
break;
case 'resource':
$result = $request->getResource();
break;
case 'protocol':
$result = 'HTTP';
break;
case 'version':
$result = $request->getProtocolVersion();
break;
case 'host':
$result = $request->getHost();
break;
case 'hostname':
$result = gethostname();
break;
case 'port':
$result = $request->getPort();
break;
case 'code':
$result = $response ? $response->getStatusCode() : '';
break;
case 'phrase':
$result = $response ? $response->getReasonPhrase() : '';
break;
case 'connect_time':
$result = $handle && $handle->getInfo(CURLINFO_CONNECT_TIME)
? $handle->getInfo(CURLINFO_CONNECT_TIME)
: ($response ? $response->getInfo('connect_time') : '');
break;
case 'total_time':
$result = $handle && $handle->getInfo(CURLINFO_TOTAL_TIME)
? $handle->getInfo(CURLINFO_TOTAL_TIME)
: ($response ? $response->getInfo('total_time') : '');
break;
case 'curl_error':
$result = $handle ? $handle->getError() : '';
break;
case 'curl_code':
$result = $handle ? $handle->getErrorNo() : '';
break;
case 'curl_stderr':
$result = $handle ? $handle->getStderr() : '';
break;
default:
if (strpos($matches[1], 'req_header_') === 0) {
$result = $request->getHeader(substr($matches[1], 11));
} elseif ($response && strpos($matches[1], 'res_header_') === 0) {
$result = $response->getHeader(substr($matches[1], 11));
}
}
$cache[$matches[1]] = $result;
return $result;
},
$this->template
);
}
}
Guzzle-3.7.0/Guzzle/Log/MonologLogAdapter.php 0000644 233176441610067500000001332 12155472567 022520 0 ustar dowling ANT\Domain Users Logger::DEBUG,
LOG_INFO => Logger::INFO,
LOG_WARNING => Logger::WARNING,
LOG_ERR => Logger::ERROR,
LOG_CRIT => Logger::CRITICAL,
LOG_ALERT => Logger::ALERT
);
public function __construct(Logger $logObject)
{
$this->log = $logObject;
}
public function log($message, $priority = LOG_INFO, $extras = array())
{
$this->log->addRecord(self::$mapping[$priority], $message);
}
}
Guzzle-3.7.0/Guzzle/Log/PsrLogAdapter.php 0000644 233176441610067500000001536 12155472567 021660 0 ustar dowling ANT\Domain Users LogLevel::DEBUG,
LOG_INFO => LogLevel::INFO,
LOG_WARNING => LogLevel::WARNING,
LOG_ERR => LogLevel::ERROR,
LOG_CRIT => LogLevel::CRITICAL,
LOG_ALERT => LogLevel::ALERT
);
public function __construct(LoggerInterface $logObject)
{
$this->log = $logObject;
}
public function log($message, $priority = LOG_INFO, $extras = array())
{
$this->log->log(self::$mapping[$priority], $message, $extras);
}
}
Guzzle-3.7.0/Guzzle/Log/Zf1LogAdapter.php 0000644 233176441610067500000000755 12155472567 021556 0 ustar dowling ANT\Domain Users log = $logObject;
Version::warn(__CLASS__ . ' is deprecated');
}
public function log($message, $priority = LOG_INFO, $extras = array())
{
$this->log->log($message, $priority, $extras);
}
}
Guzzle-3.7.0/Guzzle/Log/Zf2LogAdapter.php 0000644 233176441610067500000000611 12155472567 021546 0 ustar dowling ANT\Domain Users log = $logObject;
}
public function log($message, $priority = LOG_INFO, $extras = array())
{
$this->log->log($priority, $message, $extras);
}
}
Guzzle-3.7.0/Guzzle/Parser/ParserRegistry.php 0000644 233176441610067500000003635 12155472567 022653 0 ustar dowling ANT\Domain Users 'Guzzle\\Parser\\Message\\MessageParser',
'cookie' => 'Guzzle\\Parser\\Cookie\\CookieParser',
'url' => 'Guzzle\\Parser\\Url\\UrlParser',
'uri_template' => 'Guzzle\\Parser\\UriTemplate\\UriTemplate',
);
/**
* @return self
* @codeCoverageIgnore
*/
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new static;
}
return self::$instance;
}
public function __construct()
{
// Use the PECL URI template parser if available
if (extension_loaded('uri_template')) {
$this->mapping['uri_template'] = 'Guzzle\\Parser\\UriTemplate\\PeclUriTemplate';
}
}
/**
* Get a parser by name from an instance
*
* @param string $name Name of the parser to retrieve
*
* @return mixed|null
*/
public function getParser($name)
{
if (!isset($this->instances[$name])) {
if (!isset($this->mapping[$name])) {
return null;
}
$class = $this->mapping[$name];
$this->instances[$name] = new $class();
}
return $this->instances[$name];
}
/**
* Register a custom parser by name with the register
*
* @param string $name Name or handle of the parser to register
* @param mixed $parser Instantiated parser to register
*/
public function registerParser($name, $parser)
{
$this->instances[$name] = $parser;
}
}
Guzzle-3.7.0/Guzzle/Parser/Cookie/CookieParser.php 0000644 233176441610067500000005747 12155472567 023473 0 ustar dowling ANT\Domain Users 'Domain',
'path' => 'Path',
'max_age' => 'Max-Age',
'expires' => 'Expires',
'version' => 'Version',
'secure' => 'Secure',
'port' => 'Port',
'discard' => 'Discard',
'comment' => 'Comment',
'comment_url' => 'Comment-Url',
'http_only' => 'HttpOnly'
);
public function parseCookie($cookie, $host = null, $path = null, $decode = false)
{
// Explode the cookie string using a series of semicolons
$pieces = array_filter(array_map('trim', explode(';', $cookie)));
// The name of the cookie (first kvp) must include an equal sign.
if (empty($pieces) || !strpos($pieces[0], '=')) {
return false;
}
// Create the default return array
$data = array_merge(array_fill_keys(array_keys(self::$cookieParts), null), array(
'cookies' => array(),
'data' => array(),
'path' => $path ?: '/',
'http_only' => false,
'discard' => false,
'domain' => $host
));
$foundNonCookies = 0;
// Add the cookie pieces into the parsed data array
foreach ($pieces as $part) {
$cookieParts = explode('=', $part, 2);
$key = trim($cookieParts[0]);
if (count($cookieParts) == 1) {
// Can be a single value (e.g. secure, httpOnly)
$value = true;
} else {
// Be sure to strip wrapping quotes
$value = trim($cookieParts[1], " \n\r\t\0\x0B\"");
if ($decode) {
$value = urldecode($value);
}
}
// Only check for non-cookies when cookies have been found
if (!empty($data['cookies'])) {
foreach (self::$cookieParts as $mapValue => $search) {
if (!strcasecmp($search, $key)) {
$data[$mapValue] = $mapValue == 'port' ? array_map('trim', explode(',', $value)) : $value;
$foundNonCookies++;
continue 2;
}
}
}
// If cookies have not yet been retrieved, or this value was not found in the pieces array, treat it as a
// cookie. IF non-cookies have been parsed, then this isn't a cookie, it's cookie data. Cookies then data.
$data[$foundNonCookies ? 'data' : 'cookies'][$key] = $value;
}
// Calculate the expires date
if (!$data['expires'] && $data['max_age']) {
$data['expires'] = time() + (int) $data['max_age'];
}
return $data;
}
}
Guzzle-3.7.0/Guzzle/Parser/Cookie/CookieParserInterface.php 0000644 233176441610067500000002714 12155472567 025303 0 ustar dowling ANT\Domain Users $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;
}
}
Guzzle-3.7.0/Guzzle/Parser/Message/MessageParser.php 0000644 233176441610067500000006404 12155472567 024010 0 ustar dowling ANT\Domain Users parseMessage($message);
// 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 = array(
'method' => strtoupper($parts['start_line'][0]),
'protocol' => $protocol,
'version' => $version,
'headers' => $parts['headers'],
'body' => $parts['body']
);
$parsed['request_url'] = $this->getUrlPartsFromMessage($parts['start_line'][1], $parsed);
return $parsed;
}
public function parseResponse($message)
{
if (!$message) {
return false;
}
$parts = $this->parseMessage($message);
list($protocol, $version) = explode('/', trim($parts['start_line'][0]));
return array(
'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
*/
protected function parseMessage($message)
{
$startLine = null;
$headers = array();
$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] = array($headers[$key], $value);
} else {
$headers[$key][] = $value;
}
}
}
return array(
'start_line' => $startLine,
'headers' => $headers,
'body' => $body
);
}
}
Guzzle-3.7.0/Guzzle/Parser/Message/MessageParserInterface.php 0000644 233176441610067500000001267 12155472567 025633 0 ustar dowling ANT\Domain Users $parts->requestMethod,
'protocol' => 'HTTP',
'version' => number_format($parts->httpVersion, 1),
'headers' => $parts->headers,
'body' => $parts->body
);
$parsed['request_url'] = $this->getUrlPartsFromMessage($parts->requestUrl, $parsed);
return $parsed;
}
public function parseResponse($message)
{
if (!$message) {
return false;
}
$parts = http_parse_message($message);
return array(
'protocol' => 'HTTP',
'version' => number_format($parts->httpVersion, 1),
'code' => $parts->responseCode,
'reason_phrase' => $parts->responseStatus,
'headers' => $parts->headers,
'body' => $parts->body
);
}
}
Guzzle-3.7.0/Guzzle/Parser/UriTemplate/PeclUriTemplate.php 0000644 233176441610067500000001264 12155472567 025154 0 ustar dowling ANT\Domain Users true, '#' => true, '.' => true, '/' => true, ';' => true, '?' => true, '&' => true
);
/** @var array Delimiters */
private static $delims = array(
':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '='
);
/** @var array Percent encoded delimiters */
private static $delimsPct = array(
'%3A', '%2F', '%3F', '%23', '%5B', '%5D', '%40', '%21', '%24', '%26', '%27', '%28', '%29', '%2A', '%2B', '%2C',
'%3B', '%3D'
);
public function expand($template, array $variables)
{
$this->template = $template;
$this->variables = $variables;
// Check to ensure that the preg_* function is needed
if (false === strpos($this->template, '{')) {
return $this->template;
}
return preg_replace_callback(self::$regex, array($this, 'expandMatch'), $this->template);
}
/**
* Parse an expression into parts
*
* @param string $expression Expression to parse
*
* @return array Returns an associative array of parts
*/
private function parseExpression($expression)
{
// Check for URI operators
$operator = '';
if (isset(self::$operatorHash[$expression[0]])) {
$operator = $expression[0];
$expression = substr($expression, 1);
}
$values = explode(',', $expression);
foreach ($values as &$value) {
$value = trim($value);
$varspec = array();
$substrPos = strpos($value, ':');
if ($substrPos) {
$varspec['value'] = substr($value, 0, $substrPos);
$varspec['modifier'] = ':';
$varspec['position'] = (int) substr($value, $substrPos + 1);
} elseif (substr($value, -1) == '*') {
$varspec['modifier'] = '*';
$varspec['value'] = substr($value, 0, -1);
} else {
$varspec['value'] = (string) $value;
$varspec['modifier'] = '';
}
$value = $varspec;
}
return array(
'operator' => $operator,
'values' => $values
);
}
/**
* Process an expansion
*
* @param array $matches Matches met in the preg_replace_callback
*
* @return string Returns the replacement string
*/
private function expandMatch(array $matches)
{
static $rfc1738to3986 = array(
'+' => '%20',
'%7e' => '~'
);
$parsed = self::parseExpression($matches[1]);
$replacements = array();
$prefix = $parsed['operator'];
$joiner = $parsed['operator'];
$useQueryString = false;
if ($parsed['operator'] == '?') {
$joiner = '&';
$useQueryString = true;
} elseif ($parsed['operator'] == '&') {
$useQueryString = true;
} elseif ($parsed['operator'] == '#') {
$joiner = ',';
} elseif ($parsed['operator'] == ';') {
$useQueryString = true;
} elseif ($parsed['operator'] == '' || $parsed['operator'] == '+') {
$joiner = ',';
$prefix = '';
}
foreach ($parsed['values'] as $value) {
if (!array_key_exists($value['value'], $this->variables) || $this->variables[$value['value']] === null) {
continue;
}
$variable = $this->variables[$value['value']];
$actuallyUseQueryString = $useQueryString;
$expanded = '';
if (is_array($variable)) {
$isAssoc = $this->isAssoc($variable);
$kvp = array();
foreach ($variable as $key => $var) {
if ($isAssoc) {
$key = rawurlencode($key);
$isNestedArray = is_array($var);
} else {
$isNestedArray = false;
}
if (!$isNestedArray) {
$var = rawurlencode($var);
if ($parsed['operator'] == '+' || $parsed['operator'] == '#') {
$var = $this->decodeReserved($var);
}
}
if ($value['modifier'] == '*') {
if ($isAssoc) {
if ($isNestedArray) {
// Nested arrays must allow for deeply nested structures
$var = strtr(http_build_query(array($key => $var)), $rfc1738to3986);
} else {
$var = $key . '=' . $var;
}
} elseif ($key > 0 && $actuallyUseQueryString) {
$var = $value['value'] . '=' . $var;
}
}
$kvp[$key] = $var;
}
if (empty($variable)) {
$actuallyUseQueryString = false;
} elseif ($value['modifier'] == '*') {
$expanded = implode($joiner, $kvp);
if ($isAssoc) {
// Don't prepend the value name when using the explode modifier with an associative array
$actuallyUseQueryString = false;
}
} else {
if ($isAssoc) {
// When an associative array is encountered and the explode modifier is not set, then the
// result must be a comma separated list of keys followed by their respective values.
foreach ($kvp as $k => &$v) {
$v = $k . ',' . $v;
}
}
$expanded = implode(',', $kvp);
}
} else {
if ($value['modifier'] == ':') {
$variable = substr($variable, 0, $value['position']);
}
$expanded = rawurlencode($variable);
if ($parsed['operator'] == '+' || $parsed['operator'] == '#') {
$expanded = $this->decodeReserved($expanded);
}
}
if ($actuallyUseQueryString) {
if (!$expanded && $joiner != '&') {
$expanded = $value['value'];
} else {
$expanded = $value['value'] . '=' . $expanded;
}
}
$replacements[] = $expanded;
}
$ret = implode($joiner, $replacements);
if ($ret && $prefix) {
return $prefix . $ret;
}
return $ret;
}
/**
* Determines if an array is associative
*
* @param array $array Array to check
*
* @return bool
*/
private function isAssoc(array $array)
{
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
/**
* Removes percent encoding on reserved characters (used with + and # modifiers)
*
* @param string $string String to fix
*
* @return string
*/
private function decodeReserved($string)
{
return str_replace(self::$delimsPct, self::$delims, $string);
}
}
Guzzle-3.7.0/Guzzle/Parser/UriTemplate/UriTemplateInterface.php 0000644 233176441610067500000000776 12155472567 026200 0 ustar dowling ANT\Domain Users utf8 = $utf8;
}
public function parseUrl($url)
{
Version::warn(__CLASS__ . ' is deprecated. Just use parse_url()');
static $defaults = array('scheme' => null, 'host' => null, 'path' => null, 'port' => null, 'query' => null,
'user' => null, 'pass' => null, 'fragment' => null);
$parts = parse_url($url);
// Need to handle query parsing specially for UTF-8 requirements
if ($this->utf8 && isset($parts['query'])) {
$queryPos = strpos($url, '?');
if (isset($parts['fragment'])) {
$parts['query'] = substr($url, $queryPos + 1, strpos($url, '#') - $queryPos - 1);
} else {
$parts['query'] = substr($url, $queryPos + 1);
}
}
return $parts + $defaults;
}
}
Guzzle-3.7.0/Guzzle/Parser/Url/UrlParserInterface.php 0000644 233176441610067500000001024 12155472567 024156 0 ustar dowling ANT\Domain Users 'onBeforeSend',
'request.exception' => 'onRequestTimeout',
'request.sent' => 'onRequestSent',
'curl.callback.progress' => 'onCurlProgress'
);
}
/**
* Event used to ensure that progress callback are emitted from the curl handle's request mediator.
*
* @param Event $event
*/
public function onBeforeSend(Event $event)
{
// Ensure that progress callbacks are dispatched
$event['request']->getCurlOptions()->set('progress', true);
}
/**
* Event emitted when a curl progress function is called. When the amount of data uploaded == the amount of data to
* upload OR any bytes have been downloaded, then time the request out after 1ms because we're done with
* transmitting the request, and tell curl not download a body.
*
* @param Event $event
*/
public function onCurlProgress(Event $event)
{
if ($event['handle'] &&
($event['downloaded'] || ($event['uploaded'] && $event['upload_size'] === $event['uploaded']))
) {
// Timeout after 1ms
curl_setopt($event['handle'], CURLOPT_TIMEOUT_MS, 1);
// Even if the response is quick, tell curl not to download the body
curl_setopt($event['handle'], CURLOPT_NOBODY, true);
}
}
/**
* Event emitted when a curl exception occurs. Ignore the exception and set a mock response.
*
* @param Event $event
*/
public function onRequestTimeout(Event $event)
{
if ($event['exception'] instanceof CurlException) {
$event['request']->setResponse(new Response(200, array(
'X-Guzzle-Async' => 'Did not wait for the response'
)));
}
}
/**
* Event emitted when a request completes because it took less than 1ms. Add an X-Guzzle-Async header to notify the
* caller that there is no body in the message.
*
* @param Event $event
*/
public function onRequestSent(Event $event)
{
// Let the caller know this was meant to be async
$event['request']->getResponse()->setHeader('X-Guzzle-Async', 'Did not wait for the response');
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/AbstractBackoffStrategy.php 0000644 233176441610067500000006111 12155472567 025755 0 ustar dowling ANT\Domain Users next = $next;
}
/**
* Get the next backoff strategy in the chain
*
* @return AbstractBackoffStrategy|null
*/
public function getNext()
{
return $this->next;
}
public function getBackoffPeriod(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
) {
$delay = $this->getDelay($retries, $request, $response, $e);
if ($delay === false) {
// The strategy knows that this must not be retried
return false;
} elseif ($delay === null) {
// If the strategy is deferring a decision and the next strategy will not make a decision then return false
return !$this->next || !$this->next->makesDecision()
? false
: $this->next->getBackoffPeriod($retries, $request, $response, $e);
} elseif ($delay === true) {
// if the strategy knows that it must retry but is deferring to the next to determine the delay
if (!$this->next) {
return 0;
} else {
$next = $this->next;
while ($next->makesDecision() && $next->getNext()) {
$next = $next->getNext();
}
return !$next->makesDecision() ? $next->getBackoffPeriod($retries, $request, $response, $e) : 0;
}
} else {
return $delay;
}
}
/**
* Check if the strategy does filtering and makes decisions on whether or not to retry.
*
* Strategies that return false will never retry if all of the previous strategies in a chain defer on a backoff
* decision.
*
* @return bool
*/
abstract public function makesDecision();
/**
* Implement the concrete strategy
*
* @param int $retries Number of retries of the request
* @param RequestInterface $request Request that was sent
* @param Response $response Response that was received. Note that there may not be a response
* @param HttpException $e Exception that was encountered if any
*
* @return bool|int|null Returns false to not retry or the number of seconds to delay between retries. Return true
* or null to defer to the next strategy if available, and if not, return 0.
*/
abstract protected function getDelay(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
);
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/AbstractErrorCodeBackoffStrategy.php 0000644 233176441610067500000002025 12155472567 027562 0 ustar dowling ANT\Domain Users errorCodes = array_fill_keys($codes ?: static::$defaultErrorCodes, 1);
$this->next = $next;
}
/**
* Get the default failure codes to retry
*
* @return array
*/
public static function getDefaultFailureCodes()
{
return static::$defaultErrorCodes;
}
public function makesDecision()
{
return true;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/BackoffLogger.php 0000644 233176441610067500000004421 12155472567 023710 0 ustar dowling ANT\Domain Users logger = $logger;
$this->formatter = $formatter ?: new MessageFormatter(self::DEFAULT_FORMAT);
}
public static function getSubscribedEvents()
{
return array(BackoffPlugin::RETRY_EVENT => 'onRequestRetry');
}
/**
* Set the template to use for logging
*
* @param string $template Log message template
*
* @return self
*/
public function setTemplate($template)
{
$this->formatter->setTemplate($template);
return $this;
}
/**
* Called when a request is being retried
*
* @param Event $event Event emitted
*/
public function onRequestRetry(Event $event)
{
$this->logger->log($this->formatter->format(
$event['request'],
$event['response'],
$event['handle'],
array(
'retries' => $event['retries'],
'delay' => $event['delay']
)
));
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/BackoffPlugin.php 0000644 233176441610067500000010415 12155472567 023727 0 ustar dowling ANT\Domain Users strategy = $strategy;
}
/**
* Retrieve a basic truncated exponential backoff plugin that will retry HTTP errors and cURL errors
*
* @param int $maxRetries Maximum number of retries
* @param array $httpCodes HTTP response codes to retry
* @param array $curlCodes cURL error codes to retry
*
* @return self
*/
public static function getExponentialBackoff(
$maxRetries = 3,
array $httpCodes = null,
array $curlCodes = null
) {
return new self(new TruncatedBackoffStrategy($maxRetries,
new HttpBackoffStrategy($httpCodes,
new CurlBackoffStrategy($curlCodes,
new ExponentialBackoffStrategy()
)
)
));
}
public static function getAllEvents()
{
return array(self::RETRY_EVENT);
}
public static function getSubscribedEvents()
{
return array(
'request.sent' => 'onRequestSent',
'request.exception' => 'onRequestSent',
CurlMultiInterface::POLLING_REQUEST => 'onRequestPoll'
);
}
/**
* Called when a request has been sent and isn't finished processing
*
* @param Event $event
*/
public function onRequestSent(Event $event)
{
$request = $event['request'];
$response = $event['response'];
$exception = $event['exception'];
$params = $request->getParams();
$retries = (int) $params->get(self::RETRY_PARAM);
$delay = $this->strategy->getBackoffPeriod($retries, $request, $response, $exception);
if ($delay !== false) {
// Calculate how long to wait until the request should be retried
$params->set(self::RETRY_PARAM, ++$retries)
->set(self::DELAY_PARAM, microtime(true) + $delay);
// Send the request again
$request->setState(RequestInterface::STATE_TRANSFER);
$this->dispatch(self::RETRY_EVENT, array(
'request' => $request,
'response' => $response,
'handle' => $exception ? $exception->getCurlHandle() : null,
'retries' => $retries,
'delay' => $delay
));
}
}
/**
* Called when a request is polling in the curl multi object
*
* @param Event $event
*/
public function onRequestPoll(Event $event)
{
$request = $event['request'];
$delay = $request->getParams()->get(self::DELAY_PARAM);
// If the duration of the delay has passed, retry the request using the pool
if (null !== $delay && microtime(true) >= $delay) {
// Remove the request from the pool and then add it back again. This is required for cURL to know that we
// want to retry sending the easy handle.
$request->getParams()->remove(self::DELAY_PARAM);
// Rewind the request body if possible
if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()) {
$request->getBody()->seek(0);
}
$multi = $event['curl_multi'];
$multi->remove($request);
$multi->add($request);
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/BackoffStrategyInterface.php 0000644 233176441610067500000001743 12155472567 026120 0 ustar dowling ANT\Domain Users callback = $callback;
$this->decision = (bool) $decision;
$this->next = $next;
}
public function makesDecision()
{
return $this->decision;
}
protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
return call_user_func($this->callback, $retries, $request, $response, $e);
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/ConstantBackoffStrategy.php 0000644 233176441610067500000001607 12155472567 026010 0 ustar dowling ANT\Domain Users delay = $delay;
}
public function makesDecision()
{
return false;
}
protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
return $this->delay;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/CurlBackoffStrategy.php 0000644 233176441610067500000001713 12155472567 025122 0 ustar dowling ANT\Domain Users errorCodes[$e->getErrorNo()]) ? true : null;
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/ExponentialBackoffStrategy.php 0000644 233176441610067500000001216 12155472567 026501 0 ustar dowling ANT\Domain Users isSuccessful()) {
return false;
} else {
return isset($this->errorCodes[$response->getStatusCode()]) ? true : null;
}
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/LinearBackoffStrategy.php 0000644 233176441610067500000001615 12155472567 025430 0 ustar dowling ANT\Domain Users step = $step;
}
public function makesDecision()
{
return false;
}
protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
return $retries * $this->step;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/ReasonPhraseBackoffStrategy.php 0000644 233176441610067500000001256 12155472567 026611 0 ustar dowling ANT\Domain Users errorCodes[$response->getReasonPhrase()]) ? true : null;
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Backoff/TruncatedBackoffStrategy.php 0000644 233176441610067500000001717 12155472567 026152 0 ustar dowling ANT\Domain Users max = $maxRetries;
$this->next = $next;
}
public function makesDecision()
{
return true;
}
protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
return $retries < $this->max ? null : false;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/CacheKeyProviderInterface.php 0000644 233176441610067500000000365 12155472567 025700 0 ustar dowling ANT\Domain Users new DefaultCacheStorage($options));
} elseif ($options instanceof CacheStorageInterface) {
$options = array('storage' => $options);
} elseif ($options) {
$options = array('storage' => new DefaultCacheStorage(CacheAdapterFactory::fromCache($options)));
} elseif (!class_exists('Doctrine\Common\Cache\ArrayCache')) {
// @codeCoverageIgnoreStart
throw new InvalidArgumentException('No cache was provided and Doctrine is not installed');
// @codeCoverageIgnoreEnd
}
}
$this->autoPurge = isset($options['auto_purge']) ? $options['auto_purge'] : false;
// Add a cache storage if a cache adapter was provided
$this->storage = isset($options['storage'])
? $options['storage']
: new DefaultCacheStorage(new DoctrineCacheAdapter(new ArrayCache()));
if (!isset($options['can_cache'])) {
$this->canCache = new DefaultCanCacheStrategy();
} else {
$this->canCache = is_callable($options['can_cache'])
? new CallbackCanCacheStrategy($options['can_cache'])
: $options['can_cache'];
}
// Use the provided revalidation strategy or the default
$this->revalidation = isset($options['revalidation'])
? $options['revalidation']
: new DefaultRevalidation($this->storage, $this->canCache);
}
public static function getSubscribedEvents()
{
return array(
'request.before_send' => array('onRequestBeforeSend', -255),
'request.sent' => array('onRequestSent', 255),
'request.error' => array('onRequestError', 0),
'request.exception' => array('onRequestException', 0),
);
}
/**
* Check if a response in cache will satisfy the request before sending
*
* @param Event $event
*/
public function onRequestBeforeSend(Event $event)
{
$request = $event['request'];
$request->addHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION));
if (!$this->canCache->canCacheRequest($request)) {
switch ($request->getMethod()) {
case 'PURGE':
$this->purge($request);
$request->setResponse(new Response(200, array(), 'purged'));
break;
case 'PUT':
case 'POST':
case 'DELETE':
case 'PATCH':
if ($this->autoPurge) {
$this->purge($request);
}
}
return;
}
if ($response = $this->storage->fetch($request)) {
$params = $request->getParams();
$params['cache.lookup'] = true;
$response->setHeader(
'Age',
time() - strtotime($response->getDate() ? : $response->getLastModified() ?: 'now')
);
// Validate that the response satisfies the request
if ($this->canResponseSatisfyRequest($request, $response)) {
if (!isset($params['cache.hit'])) {
$params['cache.hit'] = true;
}
$request->setResponse($response);
}
}
}
/**
* If possible, store a response in cache after sending
*
* @param Event $event
*/
public function onRequestSent(Event $event)
{
$request = $event['request'];
$response = $event['response'];
if ($request->getParams()->get('cache.hit') === null &&
$this->canCache->canCacheRequest($request) &&
$this->canCache->canCacheResponse($response)
) {
$this->storage->cache($request, $response);
}
$this->addResponseHeaders($request, $response);
}
/**
* If possible, return a cache response on an error
*
* @param Event $event
*/
public function onRequestError(Event $event)
{
$request = $event['request'];
if (!$this->canCache->canCacheRequest($request)) {
return;
}
if ($response = $this->storage->fetch($request)) {
$response->setHeader(
'Age',
time() - strtotime($response->getLastModified() ? : $response->getDate() ?: 'now')
);
if ($this->canResponseSatisfyFailedRequest($request, $response)) {
$request->getParams()->set('cache.hit', 'error');
$this->addResponseHeaders($request, $response);
$event['response'] = $response;
$event->stopPropagation();
}
}
}
/**
* If possible, set a cache response on a cURL exception
*
* @param Event $event
*
* @return null
*/
public function onRequestException(Event $event)
{
if (!$event['exception'] instanceof CurlException) {
return;
}
$request = $event['request'];
if (!$this->canCache->canCacheRequest($request)) {
return;
}
if ($response = $this->storage->fetch($request)) {
$response->setHeader('Age', time() - strtotime($response->getDate() ? : 'now'));
if (!$this->canResponseSatisfyFailedRequest($request, $response)) {
return;
}
$request->getParams()->set('cache.hit', 'error');
$request->setResponse($response);
$this->addResponseHeaders($request, $response);
$event->stopPropagation();
}
}
/**
* Check if a cache response satisfies a request's caching constraints
*
* @param RequestInterface $request Request to validate
* @param Response $response Response to validate
*
* @return bool
*/
public function canResponseSatisfyRequest(RequestInterface $request, Response $response)
{
$responseAge = $response->calculateAge();
$reqc = $request->getHeader('Cache-Control');
$resc = $response->getHeader('Cache-Control');
// Check the request's max-age header against the age of the response
if ($reqc && $reqc->hasDirective('max-age') &&
$responseAge > $reqc->getDirective('max-age')) {
return false;
}
// Check the response's max-age header
if ($response->isFresh() === false) {
$maxStale = $reqc ? $reqc->getDirective('max-stale') : null;
if (null !== $maxStale) {
if ($maxStale !== true && $response->getFreshness() < (-1 * $maxStale)) {
return false;
}
} elseif ($resc && $resc->hasDirective('max-age')
&& $responseAge > $resc->getDirective('max-age')
) {
return false;
}
}
if ($this->revalidation->shouldRevalidate($request, $response)) {
try {
return $this->revalidation->revalidate($request, $response);
} catch (CurlException $e) {
$request->getParams()->set('cache.hit', 'error');
return $this->canResponseSatisfyFailedRequest($request, $response);
}
}
return true;
}
/**
* Check if a cache response satisfies a failed request's caching constraints
*
* @param RequestInterface $request Request to validate
* @param Response $response Response to validate
*
* @return bool
*/
public function canResponseSatisfyFailedRequest(RequestInterface $request, Response $response)
{
$reqc = $request->getHeader('Cache-Control');
$resc = $response->getHeader('Cache-Control');
$requestStaleIfError = $reqc ? $reqc->getDirective('stale-if-error') : null;
$responseStaleIfError = $resc ? $resc->getDirective('stale-if-error') : null;
if (!$requestStaleIfError && !$responseStaleIfError) {
return false;
}
if (is_numeric($requestStaleIfError) && $response->getAge() - $response->getMaxAge() > $requestStaleIfError) {
return false;
}
if (is_numeric($responseStaleIfError) && $response->getAge() - $response->getMaxAge() > $responseStaleIfError) {
return false;
}
return true;
}
/**
* Purge all cache entries for a given URL
*
* @param string $url URL to purge
*/
public function purge($url)
{
// BC compatibility with previous version that accepted a Request object
$url = $url instanceof RequestInterface ? $url->getUrl() : $url;
$this->storage->purge($url);
}
/**
* Add the plugin's headers to a response
*
* @param RequestInterface $request Request
* @param Response $response Response to add headers to
*/
protected function addResponseHeaders(RequestInterface $request, Response $response)
{
$params = $request->getParams();
$response->setHeader('Via', sprintf('%s GuzzleCache/%s', $request->getProtocolVersion(), Version::VERSION));
$lookup = ($params['cache.lookup'] === true ? 'HIT' : 'MISS') . ' from GuzzleCache';
if ($header = $response->getHeader('X-Cache-Lookup')) {
// Don't add duplicates
$values = $header->toArray();
$values[] = $lookup;
$response->setHeader('X-Cache-Lookup', array_unique($values));
} else {
$response->setHeader('X-Cache-Lookup', $lookup);
}
if ($params['cache.hit'] === true) {
$xcache = 'HIT from GuzzleCache';
} elseif ($params['cache.hit'] == 'error') {
$xcache = 'HIT_ERROR from GuzzleCache';
} else {
$xcache = 'MISS from GuzzleCache';
}
if ($header = $response->getHeader('X-Cache')) {
// Don't add duplicates
$values = $header->toArray();
$values[] = $xcache;
$response->setHeader('X-Cache', array_unique($values));
} else {
$response->setHeader('X-Cache', $xcache);
}
if ($response->isFresh() === false) {
$response->addHeader('Warning', sprintf('110 GuzzleCache/%s "Response is stale"', Version::VERSION));
if ($params['cache.hit'] === 'error') {
$response->addHeader('Warning', sprintf('111 GuzzleCache/%s "Revalidation failed"', Version::VERSION));
}
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/CacheStorageInterface.php 0000644 233176441610067500000001725 12155472567 025042 0 ustar dowling ANT\Domain Users requestCallback = $requestCallback;
$this->responseCallback = $responseCallback;
}
public function canCacheRequest(RequestInterface $request)
{
return $this->requestCallback
? call_user_func($this->requestCallback, $request)
: parent::canCache($request);
}
public function canCacheResponse(Response $response)
{
return $this->responseCallback
? call_user_func($this->responseCallback, $response)
: parent::canCacheResponse($response);
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/CanCacheStrategyInterface.php 0000644 233176441610067500000001211 12155472567 025650 0 ustar dowling ANT\Domain Users getParams()->get(self::CACHE_KEY);
if (!$key) {
$cloned = clone $request;
$cloned->removeHeader('Cache-Control');
// Check to see how and if the key should be filtered
foreach (explode(';', $request->getParams()->get(self::CACHE_KEY_FILTER)) as $part) {
$pieces = array_map('trim', explode('=', $part));
if (isset($pieces[1])) {
foreach (array_map('trim', explode(',', $pieces[1])) as $remove) {
if ($pieces[0] == 'header') {
$cloned->removeHeader($remove);
} elseif ($pieces[0] == 'query') {
$cloned->getQuery()->remove($remove);
}
}
}
}
$raw = (string) $cloned;
$key = 'GZ' . md5($raw);
$request->getParams()->set(self::CACHE_KEY, $key)->set(self::CACHE_KEY_RAW, $raw);
}
return $key;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/DefaultCacheStorage.php 0000644 233176441610067500000017462 12155472567 024533 0 ustar dowling ANT\Domain Users cache = CacheAdapterFactory::fromCache($cache);
$this->defaultTtl = $defaultTtl;
$this->keyPrefix = $keyPrefix;
}
public function cache(RequestInterface $request, Response $response)
{
$currentTime = time();
$ttl = $request->getParams()->get('cache.override_ttl') ?: $response->getMaxAge() ?: $this->defaultTtl;
if ($cacheControl = $response->getHeader('Cache-Control')) {
$stale = $cacheControl->getDirective('stale-if-error');
$ttl += $stale == true ? $ttl : $stale;
}
// Determine which manifest key should be used
$key = $this->getCacheKey($request);
$persistedRequest = $this->persistHeaders($request);
$entries = array();
if ($manifest = $this->cache->fetch($key)) {
// Determine which cache entries should still be in the cache
$vary = $response->getVary();
foreach (unserialize($manifest) as $entry) {
// Check if the entry is expired
if ($entry[4] < $currentTime) {
continue;
}
$entry[1]['vary'] = isset($entry[1]['vary']) ? $entry[1]['vary'] : '';
if ($vary != $entry[1]['vary'] || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) {
$entries[] = $entry;
}
}
}
// Persist the response body if needed
$bodyDigest = null;
if ($response->getBody() && $response->getBody()->getContentLength() > 0) {
$bodyDigest = $this->getBodyKey($request->getUrl(), $response->getBody());
$this->cache->save($bodyDigest, (string) $response->getBody(), $ttl);
}
array_unshift($entries, array(
$persistedRequest,
$this->persistHeaders($response),
$response->getStatusCode(),
$bodyDigest,
$currentTime + $ttl
));
$this->cache->save($key, serialize($entries));
}
public function delete(RequestInterface $request)
{
$key = $this->getCacheKey($request);
if ($entries = $this->cache->fetch($key)) {
// Delete each cached body
foreach (unserialize($entries) as $entry) {
if ($entry[3]) {
$this->cache->delete($entry[3]);
}
}
$this->cache->delete($key);
}
}
public function purge($url)
{
foreach (array('GET', 'HEAD', 'POST', 'PUT', 'DELETE') as $method) {
$this->delete(new Request($method, $url));
}
}
public function fetch(RequestInterface $request)
{
$key = $this->getCacheKey($request);
if (!($entries = $this->cache->fetch($key))) {
return null;
}
$match = null;
$headers = $this->persistHeaders($request);
$entries = unserialize($entries);
foreach ($entries as $index => $entry) {
if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'] : '', $headers, $entry[0])) {
$match = $entry;
break;
}
}
if (!$match) {
return null;
}
// Ensure that the response is not expired
$response = null;
if ($match[4] < time()) {
$response = -1;
} else {
$response = new Response($match[2], $match[1]);
if ($match[3]) {
if ($body = $this->cache->fetch($match[3])) {
$response->setBody($body);
} else {
// The response is not valid because the body was somehow deleted
$response = -1;
}
}
}
if ($response === -1) {
// Remove the entry from the metadata and update the cache
unset($entries[$index]);
if ($entries) {
$this->cache->save($key, serialize($entries));
} else {
$this->cache->delete($key);
}
return null;
}
return $response;
}
/**
* Hash a request URL into a string that returns cache metadata
*
* @param RequestInterface $request
*
* @return string
*/
protected function getCacheKey(RequestInterface $request)
{
// Allow cache.key_filter to trim down the URL cache key by removing generate query string values (e.g. auth)
if ($filter = $request->getParams()->get('cache.key_filter')) {
$url = $request->getUrl(true);
foreach (explode(',', $filter) as $remove) {
$url->getQuery()->remove(trim($remove));
}
} else {
$url = $request->getUrl();
}
return $this->keyPrefix . md5($request->getMethod() . ' ' . $url);
}
/**
* Create a cache key for a response's body
*
* @param string $url URL of the entry
* @param EntityBodyInterface $body Response body
*
* @return string
*/
protected function getBodyKey($url, EntityBodyInterface $body)
{
return $this->keyPrefix . md5($url) . $body->getContentMd5();
}
/**
* Determines whether two Request HTTP header sets are non-varying
*
* @param string $vary Response vary header
* @param array $r1 HTTP header array
* @param array $r2 HTTP header array
*
* @return bool
*/
private function requestsMatch($vary, $r1, $r2)
{
if ($vary) {
foreach (explode(',', $vary) as $header) {
$key = trim(strtolower($header));
$v1 = isset($r1[$key]) ? $r1[$key] : null;
$v2 = isset($r2[$key]) ? $r2[$key] : null;
if ($v1 !== $v2) {
return false;
}
}
}
return true;
}
/**
* Creates an array of cacheable and normalized message headers
*
* @param MessageInterface $message
*
* @return array
*/
private function persistHeaders(MessageInterface $message)
{
// Headers are excluded from the caching (see RFC 2616:13.5.1)
static $noCache = array(
'age' => true,
'connection' => true,
'keep-alive' => true,
'proxy-authenticate' => true,
'proxy-authorization' => true,
'te' => true,
'trailers' => true,
'transfer-encoding' => true,
'upgrade' => true,
'set-cookie' => true,
'set-cookie2' => true
);
// Clone the response to not destroy any necessary headers when caching
$headers = $message->getHeaders()->getAll();
$headers = array_diff_key($headers, $noCache);
// Cast the headers to a string
$headers = array_map(function ($h) { return (string) $h; }, $headers);
return $headers;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/DefaultCanCacheStrategy.php 0000644 233176441610067500000001614 12155472567 025343 0 ustar dowling ANT\Domain Users getMethod() != RequestInterface::GET && $request->getMethod() != RequestInterface::HEAD) {
return false;
}
// Never cache requests when using no-store
if ($request->hasHeader('Cache-Control') && $request->getHeader('Cache-Control')->hasDirective('no-store')) {
return false;
}
return true;
}
public function canCacheResponse(Response $response)
{
return $response->isSuccessful() && $response->canCache();
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/DefaultRevalidation.php 0000644 233176441610067500000014250 12155472567 024614 0 ustar dowling ANT\Domain Users storage = $cache;
$this->canCache = $canCache ?: new DefaultCanCacheStrategy();
}
public function revalidate(RequestInterface $request, Response $response)
{
try {
$revalidate = $this->createRevalidationRequest($request, $response);
$validateResponse = $revalidate->send();
if ($validateResponse->getStatusCode() == 200) {
return $this->handle200Response($request, $validateResponse);
} elseif ($validateResponse->getStatusCode() == 304) {
return $this->handle304Response($request, $validateResponse, $response);
}
} catch (BadResponseException $e) {
$this->handleBadResponse($e);
}
// Other exceptions encountered in the revalidation request are ignored
// in hopes that sending a request to the origin server will fix it
return false;
}
public function shouldRevalidate(RequestInterface $request, Response $response)
{
if ($request->getMethod() != RequestInterface::GET) {
return false;
}
$reqCache = $request->getHeader('Cache-Control');
$resCache = $response->getHeader('Cache-Control');
$revalidate = $request->getHeader('Pragma') == 'no-cache' ||
($reqCache && ($reqCache->hasDirective('no-cache') || $reqCache->hasDirective('must-revalidate'))) ||
($resCache && ($resCache->hasDirective('no-cache') || $resCache->hasDirective('must-revalidate')));
// Use the strong ETag validator if available and the response contains no Cache-Control directive
if (!$revalidate && !$reqCache && $response->hasHeader('ETag')) {
$revalidate = true;
}
return $revalidate;
}
/**
* Handles a bad response when attempting to revalidate
*
* @param BadResponseException $e Exception encountered
*
* @throws BadResponseException
*/
protected function handleBadResponse(BadResponseException $e)
{
// 404 errors mean the resource no longer exists, so remove from
// cache, and prevent an additional request by throwing the exception
if ($e->getResponse()->getStatusCode() == 404) {
$this->storage->delete($e->getRequest());
throw $e;
}
}
/**
* Creates a request to use for revalidation
*
* @param RequestInterface $request Request
* @param Response $response Response to revalidate
*
* @return RequestInterface returns a revalidation request
*/
protected function createRevalidationRequest(RequestInterface $request, Response $response)
{
$revalidate = clone $request;
$revalidate->removeHeader('Pragma')
->removeHeader('Cache-Control')
->setHeader('If-Modified-Since', $response->getLastModified() ?: $response->getDate());
if ($response->getEtag()) {
$revalidate->setHeader('If-None-Match', '"' . $response->getEtag() . '"');
}
// Remove any cache plugins that might be on the request to prevent infinite recursive revalidations
$dispatcher = $revalidate->getEventDispatcher();
foreach ($dispatcher->getListeners() as $eventName => $listeners) {
foreach ($listeners as $listener) {
if ($listener[0] instanceof CachePlugin) {
$dispatcher->removeListener($eventName, $listener);
}
}
}
return $revalidate;
}
/**
* Handles a 200 response response from revalidating. The server does not support validation, so use this response.
*
* @param RequestInterface $request Request that was sent
* @param Response $validateResponse Response received
*
* @return bool Returns true if valid, false if invalid
*/
protected function handle200Response(RequestInterface $request, Response $validateResponse)
{
$request->setResponse($validateResponse);
if ($this->canCache->canCacheResponse($validateResponse)) {
$this->storage->cache($request, $validateResponse);
}
return false;
}
/**
* Handle a 304 response and ensure that it is still valid
*
* @param RequestInterface $request Request that was sent
* @param Response $validateResponse Response received
* @param Response $response Original cached response
*
* @return bool Returns true if valid, false if invalid
*/
protected function handle304Response(RequestInterface $request, Response $validateResponse, Response $response)
{
static $replaceHeaders = array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified');
// Make sure that this response has the same ETag
if ($validateResponse->getEtag() != $response->getEtag()) {
return false;
}
// Replace cached headers with any of these headers from the
// origin server that might be more up to date
$modified = false;
foreach ($replaceHeaders as $name) {
if ($validateResponse->hasHeader($name)) {
$modified = true;
$response->setHeader($name, $validateResponse->getHeader($name));
}
}
// Store the updated response in cache
if ($modified && $this->canCache->canCacheResponse($response)) {
$this->storage->cache($request, $response);
}
return true;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cache/DenyRevalidation.php 0000644 233176441610067500000000626 12155472567 024131 0 ustar dowling ANT\Domain Users '',
'value' => '',
'domain' => '',
'path' => '/',
'expires' => null,
'max_age' => 0,
'comment' => null,
'comment_url' => null,
'port' => array(),
'version' => null,
'secure' => false,
'discard' => false,
'http_only' => false
);
$this->data = array_merge($defaults, $data);
// Extract the expires value and turn it into a UNIX timestamp if needed
if (!$this->getExpires() && $this->getMaxAge()) {
// Calculate the expires date
$this->setExpires(time() + (int) $this->getMaxAge());
} elseif ($this->getExpires() && !is_numeric($this->getExpires())) {
$this->setExpires(strtotime($this->getExpires()));
}
}
/**
* Get the cookie as an array
*
* @return array
*/
public function toArray()
{
return $this->data;
}
/**
* Get the cookie name
*
* @return string
*/
public function getName()
{
return $this->data['name'];
}
/**
* Set the cookie name
*
* @param string $name Cookie name
*
* @return Cookie
*/
public function setName($name)
{
return $this->setData('name', $name);
}
/**
* Get the cookie value
*
* @return string
*/
public function getValue()
{
return $this->data['value'];
}
/**
* Set the cookie value
*
* @param string $value Cookie value
*
* @return Cookie
*/
public function setValue($value)
{
return $this->setData('value', $value);
}
/**
* Get the domain
*
* @return string|null
*/
public function getDomain()
{
return $this->data['domain'];
}
/**
* Set the domain of the cookie
*
* @param string $domain
*
* @return Cookie
*/
public function setDomain($domain)
{
return $this->setData('domain', $domain);
}
/**
* Get the path
*
* @return string
*/
public function getPath()
{
return $this->data['path'];
}
/**
* Set the path of the cookie
*
* @param string $path Path of the cookie
*
* @return Cookie
*/
public function setPath($path)
{
return $this->setData('path', $path);
}
/**
* Maximum lifetime of the cookie in seconds
*
* @return int|null
*/
public function getMaxAge()
{
return $this->data['max_age'];
}
/**
* Set the max-age of the cookie
*
* @param int $maxAge Max age of the cookie in seconds
*
* @return Cookie
*/
public function setMaxAge($maxAge)
{
return $this->setData('max_age', $maxAge);
}
/**
* The UNIX timestamp when the cookie expires
*
* @return mixed
*/
public function getExpires()
{
return $this->data['expires'];
}
/**
* Set the unix timestamp for which the cookie will expire
*
* @param int $timestamp Unix timestamp
*
* @return Cookie
*/
public function setExpires($timestamp)
{
return $this->setData('expires', $timestamp);
}
/**
* Version of the cookie specification. RFC 2965 is 1
*
* @return mixed
*/
public function getVersion()
{
return $this->data['version'];
}
/**
* Set the cookie version
*
* @param string|int $version Version to set
*
* @return Cookie
*/
public function setVersion($version)
{
return $this->setData('version', $version);
}
/**
* Get whether or not this is a secure cookie
*
* @return null|bool
*/
public function getSecure()
{
return $this->data['secure'];
}
/**
* Set whether or not the cookie is secure
*
* @param bool $secure Set to true or false if secure
*
* @return Cookie
*/
public function setSecure($secure)
{
return $this->setData('secure', (bool) $secure);
}
/**
* Get whether or not this is a session cookie
*
* @return null|bool
*/
public function getDiscard()
{
return $this->data['discard'];
}
/**
* Set whether or not this is a session cookie
*
* @param bool $discard Set to true or false if this is a session cookie
*
* @return Cookie
*/
public function setDiscard($discard)
{
return $this->setData('discard', $discard);
}
/**
* Get the comment
*
* @return string|null
*/
public function getComment()
{
return $this->data['comment'];
}
/**
* Set the comment of the cookie
*
* @param string $comment Cookie comment
*
* @return Cookie
*/
public function setComment($comment)
{
return $this->setData('comment', $comment);
}
/**
* Get the comment URL of the cookie
*
* @return string|null
*/
public function getCommentUrl()
{
return $this->data['comment_url'];
}
/**
* Set the comment URL of the cookie
*
* @param string $commentUrl Cookie comment URL for more information
*
* @return Cookie
*/
public function setCommentUrl($commentUrl)
{
return $this->setData('comment_url', $commentUrl);
}
/**
* Get an array of acceptable ports this cookie can be used with
*
* @return array
*/
public function getPorts()
{
return $this->data['port'];
}
/**
* Set a list of acceptable ports this cookie can be used with
*
* @param array $ports Array of acceptable ports
*
* @return Cookie
*/
public function setPorts(array $ports)
{
return $this->setData('port', $ports);
}
/**
* Get whether or not this is an HTTP only cookie
*
* @return bool
*/
public function getHttpOnly()
{
return $this->data['http_only'];
}
/**
* Set whether or not this is an HTTP only cookie
*
* @param bool $httpOnly Set to true or false if this is HTTP only
*
* @return Cookie
*/
public function setHttpOnly($httpOnly)
{
return $this->setData('http_only', $httpOnly);
}
/**
* Get an array of extra cookie data
*
* @return array
*/
public function getAttributes()
{
return $this->data['data'];
}
/**
* Get a specific data point from the extra cookie data
*
* @param string $name Name of the data point to retrieve
*
* @return null|string
*/
public function getAttribute($name)
{
return array_key_exists($name, $this->data['data']) ? $this->data['data'][$name] : null;
}
/**
* Set a cookie data attribute
*
* @param string $name Name of the attribute to set
* @param string $value Value to set
*
* @return Cookie
*/
public function setAttribute($name, $value)
{
$this->data['data'][$name] = $value;
return $this;
}
/**
* Check if the cookie matches a path value
*
* @param string $path Path to check against
*
* @return bool
*/
public function matchesPath($path)
{
return !$this->getPath() || 0 === stripos($path, $this->getPath());
}
/**
* Check if the cookie matches a domain value
*
* @param string $domain Domain to check against
*
* @return bool
*/
public function matchesDomain($domain)
{
$cookieDomain = $this->getDomain();
// Domain not set or exact match.
if (!$cookieDomain || !strcasecmp($domain, $cookieDomain)) {
return true;
}
// . prefix match.
if (strpos($cookieDomain, '.') === 0) {
$realDomain = substr($cookieDomain, 1);
// Root domains don't match except for .local.
if (!substr_count($realDomain, '.') && strcasecmp($realDomain, 'local')) {
return false;
}
if (substr($domain, -strlen($realDomain)) === $realDomain) {
// Match exact or 1 deep subdomain.
return !strcasecmp($domain, $realDomain) ||
substr_count(substr($domain, 0, -strlen($realDomain)), '.') === 1;
}
}
return false;
}
/**
* Check if the cookie is compatible with a specific port
*
* @param int $port Port to check
*
* @return bool
*/
public function matchesPort($port)
{
return count($this->getPorts()) == 0 || in_array($port, $this->getPorts());
}
/**
* Check if the cookie is expired
*
* @return bool
*/
public function isExpired()
{
return $this->getExpires() && time() > $this->getExpires();
}
/**
* Check if the cookie is valid according to RFC 6265
*
* @return bool|string Returns true if valid or an error message if invalid
*/
public function validate()
{
// Names must not be empty, but can be 0
$name = $this->getName();
if (empty($name) && !is_numeric($name)) {
return 'The cookie name must not be empty';
}
// Check if any of the invalid characters are present in the cookie name
if (strpbrk($name, self::getInvalidCharacters()) !== false) {
return 'The cookie name must not contain invalid characters: ' . $name;
}
// Value must not be empty, but can be 0
$value = $this->getValue();
if (empty($value) && !is_numeric($value)) {
return 'The cookie value must not be empty';
}
// Domains must not be empty, but can be 0
// A "0" is not a valid internet domain, but may be used as server name in a private network
$domain = $this->getDomain();
if (empty($domain) && !is_numeric($domain)) {
return 'The cookie domain must not be empty';
}
return true;
}
/**
* Set a value and return the cookie object
*
* @param string $key Key to set
* @param string $value Value to set
*
* @return Cookie
*/
private function setData($key, $value)
{
$this->data[$key] = $value;
return $this;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cookie/CookiePlugin.php 0000644 233176441610067500000003611 12155472567 023463 0 ustar dowling ANT\Domain Users cookieJar = $cookieJar ?: new ArrayCookieJar();
}
public static function getSubscribedEvents()
{
return array(
'request.before_send' => array('onRequestBeforeSend', 125),
'request.sent' => array('onRequestSent', 125)
);
}
/**
* Get the cookie cookieJar
*
* @return CookieJarInterface
*/
public function getCookieJar()
{
return $this->cookieJar;
}
/**
* Add cookies before a request is sent
*
* @param Event $event
*/
public function onRequestBeforeSend(Event $event)
{
$request = $event['request'];
if (!$request->getParams()->get('cookies.disable')) {
$request->removeHeader('Cookie');
// Find cookies that match this request
foreach ($this->cookieJar->getMatchingCookies($request) as $cookie) {
$request->addCookie($cookie->getName(), $cookie->getValue());
}
}
}
/**
* Extract cookies from a sent request
*
* @param Event $event
*/
public function onRequestSent(Event $event)
{
$this->cookieJar->addCookiesFromResponse($event['response'], $event['request']);
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cookie/CookieJar/ArrayCookieJar.php 0000644 233176441610067500000015464 12155472567 025617 0 ustar dowling ANT\Domain Users strictMode = $strictMode;
}
/**
* Enable or disable strict mode on the cookie jar
*
* @param bool $strictMode Set to true to throw exceptions when invalid cookies are added. False to ignore them.
*
* @return self
*/
public function setStrictMode($strictMode)
{
$this->strictMode = $strictMode;
}
public function remove($domain = null, $path = null, $name = null)
{
$cookies = $this->all($domain, $path, $name, false, false);
$this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($cookies) {
return !in_array($cookie, $cookies, true);
});
return $this;
}
public function removeTemporary()
{
$this->cookies = array_filter($this->cookies, function (Cookie $cookie) {
return !$cookie->getDiscard() && $cookie->getExpires();
});
return $this;
}
public function removeExpired()
{
$currentTime = time();
$this->cookies = array_filter($this->cookies, function (Cookie $cookie) use ($currentTime) {
return !$cookie->getExpires() || $currentTime < $cookie->getExpires();
});
return $this;
}
public function all($domain = null, $path = null, $name = null, $skipDiscardable = false, $skipExpired = true)
{
return array_values(array_filter($this->cookies, function (Cookie $cookie) use (
$domain,
$path,
$name,
$skipDiscardable,
$skipExpired
) {
return false === (($name && $cookie->getName() != $name) ||
($skipExpired && $cookie->isExpired()) ||
($skipDiscardable && ($cookie->getDiscard() || !$cookie->getExpires())) ||
($path && !$cookie->matchesPath($path)) ||
($domain && !$cookie->matchesDomain($domain)));
}));
}
public function add(Cookie $cookie)
{
// Only allow cookies with set and valid domain, name, value
$result = $cookie->validate();
if ($result !== true) {
if ($this->strictMode) {
throw new InvalidCookieException($result);
} else {
return false;
}
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, domain, port and name are identical
if ($c->getPath() != $cookie->getPath() ||
$c->getDomain() != $cookie->getDomain() ||
$c->getPorts() != $cookie->getPorts() ||
$c->getName() != $cookie->getName()
) {
continue;
}
// The previously set cookie is a discard cookie and this one is not so allow the new cookie to be set
if (!$cookie->getDiscard() && $c->getDiscard()) {
unset($this->cookies[$i]);
continue;
}
// If the new cookie's expiration is further into the future, then replace the old cookie
if ($cookie->getExpires() > $c->getExpires()) {
unset($this->cookies[$i]);
continue;
}
// If the value has changed, we better change it
if ($cookie->getValue() !== $c->getValue()) {
unset($this->cookies[$i]);
continue;
}
// The cookie exists, so no need to continue
return false;
}
$this->cookies[] = $cookie;
return true;
}
/**
* Serializes the cookie cookieJar
*
* @return string
*/
public function serialize()
{
// Only serialize long term cookies and unexpired cookies
return json_encode(array_map(function (Cookie $cookie) {
return $cookie->toArray();
}, $this->all(null, null, null, true, true)));
}
/**
* Unserializes the cookie cookieJar
*/
public function unserialize($data)
{
$data = json_decode($data, true);
if (empty($data)) {
$this->cookies = array();
} else {
$this->cookies = array_map(function (array $cookie) {
return new Cookie($cookie);
}, $data);
}
}
/**
* Returns the total number of stored cookies
*
* @return int
*/
public function count()
{
return count($this->cookies);
}
/**
* Returns an iterator
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new \ArrayIterator($this->cookies);
}
public function addCookiesFromResponse(Response $response, RequestInterface $request = null)
{
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
$parser = ParserRegistry::getInstance()->getParser('cookie');
foreach ($cookieHeader as $cookie) {
if ($parsed = $request
? $parser->parseCookie($cookie, $request->getHost(), $request->getPath())
: $parser->parseCookie($cookie)
) {
// Break up cookie v2 into multiple cookies
foreach ($parsed['cookies'] as $key => $value) {
$row = $parsed;
$row['name'] = $key;
$row['value'] = $value;
unset($row['cookies']);
$this->add(new Cookie($row));
}
}
}
}
}
public function getMatchingCookies(RequestInterface $request)
{
// Find cookies that match this request
$cookies = $this->all($request->getHost(), $request->getPath());
// Remove ineligible cookies
foreach ($cookies as $index => $cookie) {
if (!$cookie->matchesPort($request->getPort()) || ($cookie->getSecure() && $request->getScheme() != 'https')) {
unset($cookies[$index]);
}
};
return $cookies;
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cookie/CookieJar/CookieJarInterface.php 0000644 233176441610067500000005552 12155472567 026436 0 ustar dowling ANT\Domain Users filename = $cookieFile;
$this->load();
}
/**
* Saves the file when shutting down
*/
public function __destruct()
{
$this->persist();
}
/**
* Save the contents of the data array to the file
*
* @throws RuntimeException if the file cannot be found or created
*/
protected function persist()
{
if (false === file_put_contents($this->filename, $this->serialize())) {
// @codeCoverageIgnoreStart
throw new RuntimeException('Unable to open file ' . $this->filename);
// @codeCoverageIgnoreEnd
}
}
/**
* Load the contents of the json formatted file into the data array and discard any unsaved state
*/
protected function load()
{
$json = file_get_contents($this->filename);
if (false === $json) {
// @codeCoverageIgnoreStart
throw new RuntimeException('Unable to open file ' . $this->filename);
// @codeCoverageIgnoreEnd
}
$this->unserialize($json);
$this->cookies = $this->cookies ?: array();
}
}
Guzzle-3.7.0/Guzzle/Plugin/Cookie/Exception/InvalidCookieException.php 0000644 233176441610067500000000252 12155472567 027426 0 ustar dowling ANT\Domain Users getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');
*/
class CurlAuthPlugin implements EventSubscriberInterface
{
private $username;
private $password;
private $scheme;
/**
* @param string $username HTTP basic auth username
* @param string $password Password
* @param int $scheme Curl auth scheme
*/
public function __construct($username, $password, $scheme=CURLAUTH_BASIC)
{
Version::warn(__CLASS__ . " is deprecated. Use \$client->getConfig()->setPath('request.options/auth', array('user', 'pass', 'Basic|Digest');");
$this->username = $username;
$this->password = $password;
$this->scheme = $scheme;
}
public static function getSubscribedEvents()
{
return array('client.create_request' => array('onRequestCreate', 255));
}
/**
* Add basic auth
*
* @param Event $event
*/
public function onRequestCreate(Event $event)
{
$event['request']->setAuth($this->username, $this->password, $this->scheme);
}
}
Guzzle-3.7.0/Guzzle/Plugin/ErrorResponse/ErrorResponseExceptionInterface.php 0000644 233176441610067500000001126 12155472567 031001 0 ustar dowling ANT\Domain Users array('onCommandBeforeSend', -1));
}
/**
* Adds a listener to requests before they sent from a command
*
* @param Event $event Event emitted
*/
public function onCommandBeforeSend(Event $event)
{
$command = $event['command'];
if ($operation = $command->getOperation()) {
if ($operation->getErrorResponses()) {
$request = $command->getRequest();
$request->getEventDispatcher()
->addListener('request.complete', $this->getErrorClosure($request, $command, $operation));
}
}
}
/**
* @param RequestInterface $request Request that received an error
* @param CommandInterface $command Command that created the request
* @param Operation $operation Operation that defines the request and errors
*
* @return \Closure Returns a closure
* @throws ErrorResponseException
*/
protected function getErrorClosure(RequestInterface $request, CommandInterface $command, Operation $operation)
{
return function (Event $event) use ($request, $command, $operation) {
$response = $event['response'];
foreach ($operation->getErrorResponses() as $error) {
if (!isset($error['class'])) {
continue;
}
if (isset($error['code']) && $response->getStatusCode() != $error['code']) {
continue;
}
if (isset($error['reason']) && $response->getReasonPhrase() != $error['reason']) {
continue;
}
$className = $error['class'];
$errorClassInterface = __NAMESPACE__ . '\\ErrorResponseExceptionInterface';
if (!class_exists($className)) {
throw new ErrorResponseException("{$className} does not exist");;
} elseif (!is_subclass_of($className, $errorClassInterface)) {
throw new ErrorResponseException("{$className} must implement {$errorClassInterface}");
}
throw $className::fromCommand($command, $response);
}
};
}
}
Guzzle-3.7.0/Guzzle/Plugin/ErrorResponse/Exception/ErrorResponseException.php 0000644 233176441610067500000000241 12155472567 031113 0 ustar dowling ANT\Domain Users array('onRequestSent', 9999));
}
/**
* 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['request']) . "\n\n< " . trim($response) . "\n";
}
return implode("\n", $lines);
}
/**
* Add a request to the history
*
* @param RequestInterface $request Request to add
* @param Response $response Response of the request
*
* @return HistoryPlugin
*/
public function add(RequestInterface $request, Response $response = null)
{
if (!$response && $request->getResponse()) {
$response = $request->getResponse();
}
$this->transactions[] = array('request' => $request, 'response' => $response);
if (count($this->transactions) > $this->getlimit()) {
array_shift($this->transactions);
}
return $this;
}
/**
* Set the max number of requests to store
*
* @param int $limit Limit
*
* @return HistoryPlugin
*/
public function setLimit($limit)
{
$this->limit = (int) $limit;
return $this;
}
/**
* Get the request limit
*
* @return int
*/
public function getLimit()
{
return $this->limit;
}
/**
* Get all of the raw transactions in the form of an array of associative arrays containing
* 'request' and 'response' keys.
*
* @return array
*/
public function getAll()
{
return $this->transactions;
}
/**
* Get the requests in the history
*
* @return \ArrayIterator
*/
public function getIterator()
{
// Return an iterator just like the old iteration of the HistoryPlugin for BC compatibility (use getAll())
return new \ArrayIterator(array_map(function ($entry) {
$entry['request']->getParams()->set('actual_response', $entry['response']);
return $entry['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
*
* @return RequestInterface
*/
public function getLastRequest()
{
$last = end($this->transactions);
return $last['request'];
}
/**
* Get the last response in the history
*
* @return Response|null
*/
public function getLastResponse()
{
$last = end($this->transactions);
return isset($last['response']) ? $last['response'] : null;
}
/**
* Clears the history
*
* @return HistoryPlugin
*/
public function clear()
{
$this->transactions = array();
return $this;
}
public function onRequestSent(Event $event)
{
$this->add($event['request'], $event['response']);
}
}
Guzzle-3.7.0/Guzzle/Plugin/Log/LogPlugin.php 0000644 233176441610067500000013435 12155472567 022310 0 ustar dowling ANT\Domain Users logAdapter = $logAdapter;
$this->formatter = $formatter instanceof MessageFormatter ? $formatter : new MessageFormatter($formatter);
$this->wireBodies = $wireBodies;
}
/**
* Get a log plugin that outputs full request, response, and curl error information to stderr
*
* @param bool $wireBodies Set to false to disable request/response body output when they use are not repeatable
* @param resource $stream Stream to write to when logging. Defaults to STDERR when it is available
*
* @return self
*/
public static function getDebugPlugin($wireBodies = true, $stream = null)
{
if ($stream === null) {
if (defined('STDERR')) {
$stream = STDERR;
} else {
$stream = fopen('php://output', 'w');
}
}
return new self(new ClosureLogAdapter(function ($m) use ($stream) {
fwrite($stream, $m . PHP_EOL);
}), "# Request:\n{request}\n\n# Response:\n{response}\n\n# Errors: {curl_code} {curl_error}", $wireBodies);
}
public static function getSubscribedEvents()
{
return array(
'curl.callback.write' => array('onCurlWrite', 255),
'curl.callback.read' => array('onCurlRead', 255),
'request.before_send' => array('onRequestBeforeSend', 255),
'request.sent' => array('onRequestSent', 255)
);
}
/**
* Event triggered when curl data is read from a request
*
* @param Event $event
*/
public function onCurlRead(Event $event)
{
// Stream the request body to the log if the body is not repeatable
if ($wire = $event['request']->getParams()->get('request_wire')) {
$wire->write($event['read']);
}
}
/**
* Event triggered when curl data is written to a response
*
* @param Event $event
*/
public function onCurlWrite(Event $event)
{
// Stream the response body to the log if the body is not repeatable
if ($wire = $event['request']->getParams()->get('response_wire')) {
$wire->write($event['write']);
}
}
/**
* Called before a request is sent
*
* @param Event $event
*/
public function onRequestBeforeSend(Event $event)
{
if ($this->wireBodies) {
$request = $event['request'];
// Ensure that curl IO events are emitted
$request->getCurlOptions()->set('emit_io', true);
// We need to make special handling for content wiring and non-repeatable streams.
if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
&& (!$request->getBody()->isSeekable() || !$request->getBody()->isReadable())
) {
// The body of the request cannot be recalled so logging the body will require us to buffer it
$request->getParams()->set('request_wire', EntityBody::factory());
}
if (!$request->getResponseBody()->isRepeatable()) {
// The body of the response cannot be recalled so logging the body will require us to buffer it
$request->getParams()->set('response_wire', EntityBody::factory());
}
}
}
/**
* Triggers the actual log write when a request completes
*
* @param Event $event
*/
public function onRequestSent(Event $event)
{
$request = $event['request'];
$response = $event['response'];
$handle = $event['handle'];
if ($wire = $request->getParams()->get('request_wire')) {
$request = clone $request;
$request->setBody($wire);
}
if ($wire = $request->getParams()->get('response_wire')) {
$response = clone $response;
$response->setBody($wire);
}
// Send the log message to the adapter, adding a category and host
$priority = $response && $response->isError() ? LOG_ERR : LOG_DEBUG;
$message = $this->formatter->format($request, $response, $handle);
$this->logAdapter->log($message, $priority, array(
'request' => $request,
'response' => $response,
'handle' => $handle
));
}
}
Guzzle-3.7.0/Guzzle/Plugin/Md5/CommandContentMd5Plugin.php 0000644 233176441610067500000004130 12155472567 024742 0 ustar dowling ANT\Domain Users contentMd5Param = $contentMd5Param;
$this->validateMd5Param = $validateMd5Param;
}
public static function getSubscribedEvents()
{
return array('command.before_send' => array('onCommandBeforeSend', -255));
}
public function onCommandBeforeSend(Event $event)
{
$command = $event['command'];
$request = $command->getRequest();
// Only add an MD5 is there is a MD5 option on the operation and it has a payload
if ($request instanceof EntityEnclosingRequestInterface && $request->getBody()
&& $command->getOperation()->hasParam($this->contentMd5Param)) {
// Check if an MD5 checksum value should be passed along to the request
if ($command[$this->contentMd5Param] === true) {
$request->setHeader('Content-MD5', $request->getBody()->getContentMd5(true, true));
}
}
// Check if MD5 validation should be used with the response
if ($command[$this->validateMd5Param] === true) {
$request->addSubscriber(new Md5ValidatorPlugin(true, false));
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Md5/Md5ValidatorPlugin.php 0000644 233176441610067500000006627 12155472567 023773 0 ustar dowling ANT\Domain Users contentLengthCutoff = $contentLengthCutoff;
$this->contentEncoded = $contentEncoded;
}
public static function getSubscribedEvents()
{
return array('request.complete' => array('onRequestComplete', 255));
}
/**
* {@inheritdoc}
* @throws UnexpectedValueException
*/
public function onRequestComplete(Event $event)
{
$response = $event['response'];
if (!$contentMd5 = $response->getContentMd5()) {
return;
}
$contentEncoding = $response->getContentEncoding();
if ($contentEncoding && !$this->contentEncoded) {
return false;
}
// Make sure that the size of the request is under the cutoff size
if ($this->contentLengthCutoff) {
$size = $response->getContentLength() ?: $response->getBody()->getSize();
if (!$size || $size > $this->contentLengthCutoff) {
return;
}
}
if (!$contentEncoding) {
$hash = $response->getBody()->getContentMd5();
} elseif ($contentEncoding == 'gzip') {
$response->getBody()->compress('zlib.deflate');
$hash = $response->getBody()->getContentMd5();
$response->getBody()->uncompress();
} elseif ($contentEncoding == 'compress') {
$response->getBody()->compress('bzip2.compress');
$hash = $response->getBody()->getContentMd5();
$response->getBody()->uncompress();
} else {
return;
}
if ($contentMd5 !== $hash) {
throw new UnexpectedValueException(
"The response entity body may have been modified over the wire. The Content-MD5 "
. "received ({$contentMd5}) did not match the calculated MD5 hash ({$hash})."
);
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Mock/MockPlugin.php 0000644 233176441610067500000015353 12155472567 022631 0 ustar dowling ANT\Domain Users readBodies = $readBodies;
$this->temporary = $temporary;
if ($items) {
foreach ($items as $item) {
if ($item instanceof \Exception) {
$this->addException($item);
} else {
$this->addResponse($item);
}
}
}
}
public static function getSubscribedEvents()
{
// Use a number lower than the CachePlugin
return array('request.before_send' => array('onRequestBeforeSend', -999));
}
public static function getAllEvents()
{
return array('mock.request');
}
/**
* Get a mock response from a file
*
* @param string $path File to retrieve a mock response from
*
* @return Response
* @throws InvalidArgumentException if the file is not found
*/
public static function getMockFile($path)
{
if (!file_exists($path)) {
throw new InvalidArgumentException('Unable to open mock file: ' . $path);
}
return Response::fromMessage(file_get_contents($path));
}
/**
* Set whether or not to consume the entity body of a request when a mock
* response is used
*
* @param bool $readBodies Set to true to read and consume entity bodies
*
* @return self
*/
public function readBodies($readBodies)
{
$this->readBodies = $readBodies;
return $this;
}
/**
* Returns the number of remaining mock responses
*
* @return int
*/
public function count()
{
return count($this->queue);
}
/**
* Add a response to the end of the queue
*
* @param string|Response $response Response object or path to response file
*
* @return MockPlugin
* @throws InvalidArgumentException if a string or Response is not passed
*/
public function addResponse($response)
{
if (!($response instanceof Response)) {
if (!is_string($response)) {
throw new InvalidArgumentException('Invalid response');
}
$response = self::getMockFile($response);
}
$this->queue[] = $response;
return $this;
}
/**
* Add an exception to the end of the queue
*
* @param CurlException $e Exception to throw when the request is executed
*
* @return MockPlugin
*/
public function addException(CurlException $e)
{
$this->queue[] = $e;
return $this;
}
/**
* Clear the queue
*
* @return MockPlugin
*/
public function clearQueue()
{
$this->queue = array();
return $this;
}
/**
* Returns an array of mock responses remaining in the queue
*
* @return array
*/
public function getQueue()
{
return $this->queue;
}
/**
* Check if this is a temporary plugin
*
* @return bool
*/
public function isTemporary()
{
return $this->temporary;
}
/**
* Get a response from the front of the list and add it to a request
*
* @param RequestInterface $request Request to mock
*
* @return self
* @throws CurlException When request.send is called and an exception is queued
*/
public function dequeue(RequestInterface $request)
{
$this->dispatch('mock.request', array('plugin' => $this, 'request' => $request));
$item = array_shift($this->queue);
if ($item instanceof Response) {
if ($this->readBodies && $request instanceof EntityEnclosingRequestInterface) {
$request->getEventDispatcher()->addListener('request.sent', $f = function (Event $event) use (&$f) {
while ($data = $event['request']->getBody()->read(8096));
// Remove the listener after one-time use
$event['request']->getEventDispatcher()->removeListener('request.sent', $f);
});
}
$request->setResponse($item);
} elseif ($item instanceof CurlException) {
// Emulates exceptions encountered while transferring requests
$item->setRequest($request);
$state = $request->setState(RequestInterface::STATE_ERROR, array('exception' => $item));
// Only throw if the exception wasn't handled
if ($state == RequestInterface::STATE_ERROR) {
throw $item;
}
}
return $this;
}
/**
* Clear the array of received requests
*/
public function flush()
{
$this->received = array();
}
/**
* Get an array of requests that were mocked by this plugin
*
* @return array
*/
public function getReceivedRequests()
{
return $this->received;
}
/**
* Called when a request is about to be sent
*
* @param Event $event
*/
public function onRequestBeforeSend(Event $event)
{
if ($this->queue) {
$request = $event['request'];
$this->received[] = $request;
// Detach the filter from the client so it's a one-time use
if ($this->temporary && count($this->queue) == 1 && $request->getClient()) {
$request->getClient()->getEventDispatcher()->removeSubscriber($this);
}
$this->dequeue($request);
}
}
}
Guzzle-3.7.0/Guzzle/Plugin/Oauth/OauthPlugin.php 0000644 233176441610067500000021325 12155472567 023203 0 ustar dowling ANT\Domain Users config = Collection::fromConfig($config, array(
'version' => '1.0',
'consumer_key' => 'anonymous',
'consumer_secret' => 'anonymous',
'signature_method' => 'HMAC-SHA1',
'signature_callback' => function($stringToSign, $key) {
return hash_hmac('sha1', $stringToSign, $key, true);
}
), array(
'signature_method', 'signature_callback', 'version',
'consumer_key', 'consumer_secret'
));
}
public static function getSubscribedEvents()
{
return array(
'request.before_send' => array('onRequestBeforeSend', -1000)
);
}
/**
* Request before-send event handler
*
* @param Event $event Event received
* @return array
*/
public function onRequestBeforeSend(Event $event)
{
$timestamp = $this->getTimestamp($event);
$request = $event['request'];
$nonce = $this->generateNonce($request);
$authorizationParams = array(
'oauth_callback' => $this->config['callback'],
'oauth_consumer_key' => $this->config['consumer_key'],
'oauth_nonce' => $nonce,
'oauth_signature' => $this->getSignature($request, $timestamp, $nonce),
'oauth_signature_method' => $this->config['signature_method'],
'oauth_timestamp' => $timestamp,
'oauth_token' => $this->config['token'],
'oauth_verifier' => $this->config['verifier'],
'oauth_version' => $this->config['version'],
);
$request->setHeader(
'Authorization',
$this->buildAuthorizationHeader($authorizationParams)
);
return $authorizationParams;
}
/**
* Builds the Authorization header for a request
*
* @param array $authorizationParams Associative array of authorization parameters
*
* @return string
*/
private function buildAuthorizationHeader($authorizationParams)
{
$authorizationString = 'OAuth ';
foreach ($authorizationParams as $key => $val) {
if ($val) {
$authorizationString .= $key . '="' . urlencode($val) . '", ';
}
}
return substr($authorizationString, 0, -2);
}
/**
* Calculate signature for request
*
* @param RequestInterface $request Request to generate a signature for
* @param integer $timestamp Timestamp to use for nonce
* @param string $nonce
*
* @return string
*/
public function getSignature(RequestInterface $request, $timestamp, $nonce)
{
$string = $this->getStringToSign($request, $timestamp, $nonce);
$key = urlencode($this->config['consumer_secret']) . '&' . urlencode($this->config['token_secret']);
return base64_encode(call_user_func($this->config['signature_callback'], $string, $key));
}
/**
* Calculate string to sign
*
* @param RequestInterface $request Request to generate a signature for
* @param int $timestamp Timestamp to use for nonce
* @param string $nonce
*
* @return string
*/
public function getStringToSign(RequestInterface $request, $timestamp, $nonce)
{
$params = $this->getParamsToSign($request, $timestamp, $nonce);
// Convert booleans to strings.
$params = $this->prepareParameters($params);
// Build signing string from combined params
$parameterString = new QueryString($params);
$url = Url::factory($request->getUrl())->setQuery('')->setFragment(null);
return strtoupper($request->getMethod()) . '&'
. rawurlencode($url) . '&'
. rawurlencode((string) $parameterString);
}
/**
* Parameters sorted and filtered in order to properly sign a request
*
* @param RequestInterface $request Request to generate a signature for
* @param integer $timestamp Timestamp to use for nonce
* @param string $nonce
*
* @return array
*/
public function getParamsToSign(RequestInterface $request, $timestamp, $nonce)
{
$params = new Collection(array(
'oauth_callback' => $this->config['callback'],
'oauth_consumer_key' => $this->config['consumer_key'],
'oauth_nonce' => $nonce,
'oauth_signature_method' => $this->config['signature_method'],
'oauth_timestamp' => $timestamp,
'oauth_token' => $this->config['token'],
'oauth_verifier' => $this->config['verifier'],
'oauth_version' => $this->config['version']
));
// Add query string parameters
$params->merge($request->getQuery());
// Add POST fields to signing string if required
if ($this->shouldPostFieldsBeSigned($request))
{
$params->merge($request->getPostFields());
}
// Sort params
$params = $params->toArray();
ksort($params);
return $params;
}
/**
* Decide whether the post fields should be added to the base string that Oauth signs.
* This implementation is correct. Non-conformant APIs may require that this method be
* overwritten e.g. the Flickr API incorrectly adds the post fields when the Content-Type
* is 'application/x-www-form-urlencoded'
*
* @param $request
* @return bool Whether the post fields should be signed or not
*/
public function shouldPostFieldsBeSigned($request)
{
if (!$this->config->get('disable_post_params') &&
$request instanceof EntityEnclosingRequestInterface &&
false !== strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded'))
{
return true;
}
return false;
}
/**
* Returns a Nonce Based on the unique id and URL. This will allow for multiple requests in parallel with the same
* exact timestamp to use separate nonce's.
*
* @param RequestInterface $request Request to generate a nonce for
*
* @return string
*/
public function generateNonce(RequestInterface $request)
{
return sha1(uniqid('', true) . $request->getUrl());
}
/**
* Gets timestamp from event or create new timestamp
*
* @param Event $event Event containing contextual information
*
* @return int
*/
public function getTimestamp(Event $event)
{
return $event['timestamp'] ?: time();
}
/**
* Convert booleans to strings, removed unset parameters, and sorts the array
*
* @param array $data Data array
*
* @return array
*/
protected function prepareParameters($data)
{
ksort($data);
foreach ($data as $key => &$value) {
switch (gettype($value)) {
case 'NULL':
unset($data[$key]);
break;
case 'array':
$data[$key] = self::prepareParameters($value);
break;
case 'boolean':
$data[$key] = $value ? 'true' : 'false';
break;
}
}
return $data;
}
}
Guzzle-3.7.0/Guzzle/Service/AbstractConfigLoader.php 0000644 233176441610067500000013561 12155472567 024051 0 ustar dowling ANT\Domain Users 'JSON_ERROR_NONE - No errors',
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'
);
public function load($config, array $options = array())
{
// Reset the array of loaded files because this is a new config
$this->loadedFiles = array();
if (is_string($config)) {
$config = $this->loadFile($config);
} elseif (!is_array($config)) {
throw new InvalidArgumentException('Unknown type passed to configuration loader: ' . gettype($config));
} else {
$this->mergeIncludes($config);
}
return $this->build($config, $options);
}
/**
* Add an include alias to the loader
*
* @param string $filename Filename to alias (e.g. _foo)
* @param string $alias Actual file to use (e.g. /path/to/foo.json)
*
* @return self
*/
public function addAlias($filename, $alias)
{
$this->aliases[$filename] = $alias;
return $this;
}
/**
* Remove an alias from the loader
*
* @param string $alias Alias to remove
*
* @return self
*/
public function removeAlias($alias)
{
unset($this->aliases[$alias]);
return $this;
}
/**
* Perform the parsing of a config file and create the end result
*
* @param array $config Configuration data
* @param array $options Options to use when building
*
* @return mixed
*/
protected abstract function build($config, array $options);
/**
* Load a configuration file (can load JSON or PHP files that return an array when included)
*
* @param string $filename File to load
*
* @return array
* @throws InvalidArgumentException
* @throws RuntimeException when the JSON cannot be parsed
*/
protected function loadFile($filename)
{
if (isset($this->aliases[$filename])) {
$filename = $this->aliases[$filename];
}
switch (pathinfo($filename, PATHINFO_EXTENSION)) {
case 'js':
case 'json':
$level = error_reporting(0);
$json = file_get_contents($filename);
error_reporting($level);
if ($json === false) {
$err = error_get_last();
throw new InvalidArgumentException("Unable to open {$filename}: " . $err['message']);
}
$config = json_decode($json, true);
// Throw an exception if there was an error loading the file
if ($error = json_last_error()) {
$message = isset(self::$jsonErrors[$error]) ? self::$jsonErrors[$error] : 'Unknown error';
throw new RuntimeException("Error loading JSON data from {$filename}: ({$error}) - {$message}");
}
break;
case 'php':
if (!is_readable($filename)) {
throw new InvalidArgumentException("Unable to open {$filename} for reading");
}
$config = require $filename;
if (!is_array($config)) {
throw new InvalidArgumentException('PHP files must return an array of configuration data');
}
break;
default:
throw new InvalidArgumentException('Unknown file extension: ' . $filename);
}
// Keep track of this file being loaded to prevent infinite recursion
$this->loadedFiles[$filename] = true;
// Merge include files into the configuration array
$this->mergeIncludes($config, dirname($filename));
return $config;
}
/**
* Merges in all include files
*
* @param array $config Config data that contains includes
* @param string $basePath Base path to use when a relative path is encountered
*
* @return array Returns the merged and included data
*/
protected function mergeIncludes(&$config, $basePath = null)
{
if (!empty($config['includes'])) {
foreach ($config['includes'] as &$path) {
// Account for relative paths
if ($path[0] != DIRECTORY_SEPARATOR && !isset($this->aliases[$path]) && $basePath) {
$path = "{$basePath}/{$path}";
}
// Don't load the same files more than once
if (!isset($this->loadedFiles[$path])) {
$this->loadedFiles[$path] = true;
$config = $this->mergeData($this->loadFile($path), $config);
}
}
}
}
/**
* Default implementation for merging two arrays of data (uses array_merge_recursive)
*
* @param array $a Original data
* @param array $b Data to merge into the original and overwrite existing values
*
* @return array
*/
protected function mergeData(array $a, array $b)
{
return array_merge_recursive($a, $b);
}
}
Guzzle-3.7.0/Guzzle/Service/CachingConfigLoader.php 0000644 233176441610067500000002224 12155472567 023634 0 ustar dowling ANT\Domain Users loader = $loader;
$this->cache = $cache;
}
public function load($config, array $options = array())
{
if (!is_string($config)) {
$key = false;
} else {
$key = 'loader_' . crc32($config);
if ($result = $this->cache->fetch($key)) {
return $result;
}
}
$result = $this->loader->load($config, $options);
if ($key) {
$this->cache->save($key, $result);
}
return $result;
}
}
Guzzle-3.7.0/Guzzle/Service/Client.php 0000644 233176441610067500000022041 12155472567 021240 0 ustar dowling ANT\Domain Users getCommand($method, isset($args[0]) ? $args[0] : array())->getResult();
}
public function getCommand($name, array $args = array())
{
// Add global client options to the command
if ($options = $this->getConfig(self::COMMAND_PARAMS)) {
$args += $options;
}
if (!($command = $this->getCommandFactory()->factory($name, $args))) {
throw new InvalidArgumentException("Command was not found matching {$name}");
}
$command->setClient($this);
$this->dispatch('client.command.create', array('client' => $this, 'command' => $command));
return $command;
}
/**
* Set the command factory used to create commands by name
*
* @param CommandFactoryInterface $factory Command factory
*
* @return self
*/
public function setCommandFactory(CommandFactoryInterface $factory)
{
$this->commandFactory = $factory;
return $this;
}
/**
* Set the resource iterator factory associated with the client
*
* @param ResourceIteratorFactoryInterface $factory Resource iterator factory
*
* @return self
*/
public function setResourceIteratorFactory(ResourceIteratorFactoryInterface $factory)
{
$this->resourceIteratorFactory = $factory;
return $this;
}
public function getIterator($command, array $commandOptions = null, array $iteratorOptions = array())
{
if (!($command instanceof CommandInterface)) {
$command = $this->getCommand($command, $commandOptions ?: array());
}
return $this->getResourceIteratorFactory()->build($command, $iteratorOptions);
}
public function execute($command)
{
if ($command instanceof CommandInterface) {
$this->send($this->prepareCommand($command));
$this->dispatch('command.after_send', array('command' => $command));
return $command->getResult();
} elseif (is_array($command) || $command instanceof \Traversable) {
return $this->executeMultiple($command);
} else {
throw new InvalidArgumentException('Command must be a command or array of commands');
}
}
public function setDescription(ServiceDescriptionInterface $service)
{
$this->serviceDescription = $service;
// If a baseUrl was set on the description, then update the client
if ($baseUrl = $service->getBaseUrl()) {
$this->setBaseUrl($baseUrl);
}
return $this;
}
public function getDescription()
{
return $this->serviceDescription;
}
/**
* Set the inflector used with the client
*
* @param InflectorInterface $inflector Inflection object
*
* @return self
*/
public function setInflector(InflectorInterface $inflector)
{
$this->inflector = $inflector;
return $this;
}
/**
* Get the inflector used with the client
*
* @return self
*/
public function getInflector()
{
if (!$this->inflector) {
$this->inflector = Inflector::getDefault();
}
return $this->inflector;
}
/**
* Prepare a command for sending and get the RequestInterface object created by the command
*
* @param CommandInterface $command Command to prepare
*
* @return RequestInterface
*/
protected function prepareCommand(CommandInterface $command)
{
// Set the client and prepare the command
$request = $command->setClient($this)->prepare();
// Set the state to new if the command was previously executed
$request->setState(RequestInterface::STATE_NEW);
$this->dispatch('command.before_send', array('command' => $command));
return $request;
}
/**
* Execute multiple commands in parallel
*
* @param array|Traversable $commands Array of CommandInterface objects to execute
*
* @return array Returns an array of the executed commands
* @throws Exception\CommandTransferException
*/
protected function executeMultiple($commands)
{
$requests = array();
$commandRequests = new \SplObjectStorage();
foreach ($commands as $command) {
$request = $this->prepareCommand($command);
$commandRequests[$request] = $command;
$requests[] = $request;
}
try {
$this->send($requests);
foreach ($commands as $command) {
$this->dispatch('command.after_send', array('command' => $command));
}
return $commands;
} catch (MultiTransferException $failureException) {
// Throw a CommandTransferException using the successful and failed commands
$e = CommandTransferException::fromMultiTransferException($failureException);
// Remove failed requests from the successful requests array and add to the failures array
foreach ($failureException->getFailedRequests() as $request) {
if (isset($commandRequests[$request])) {
$e->addFailedCommand($commandRequests[$request]);
unset($commandRequests[$request]);
}
}
// Always emit the command after_send events for successful commands
foreach ($commandRequests as $success) {
$e->addSuccessfulCommand($commandRequests[$success]);
$this->dispatch('command.after_send', array('command' => $commandRequests[$success]));
}
throw $e;
}
}
protected function getResourceIteratorFactory()
{
if (!$this->resourceIteratorFactory) {
// Build the default resource iterator factory if one is not set
$clientClass = get_class($this);
$prefix = substr($clientClass, 0, strrpos($clientClass, '\\'));
$this->resourceIteratorFactory = new ResourceIteratorClassFactory(array(
"{$prefix}\\Iterator",
"{$prefix}\\Model"
));
}
return $this->resourceIteratorFactory;
}
/**
* Get the command factory associated with the client
*
* @return CommandFactoryInterface
*/
protected function getCommandFactory()
{
if (!$this->commandFactory) {
$this->commandFactory = CompositeFactory::getDefaultChain($this);
}
return $this->commandFactory;
}
/**
* @deprecated
* @codeCoverageIgnore
*/
public function enableMagicMethods($isEnabled)
{
Version::warn(__METHOD__ . ' is deprecated');
}
}
Guzzle-3.7.0/Guzzle/Service/ClientInterface.php 0000644 233176441610067500000005223 12155472567 023064 0 ustar dowling ANT\Domain Users load($config, $globalParameters);
}
/**
* @param array $serviceBuilderConfig Service configuration settings:
* - name: Name of the service
* - class: Client class to instantiate using a factory method
* - params: array of key value pair configuration settings for the builder
*/
public function __construct(array $serviceBuilderConfig = array())
{
$this->builderConfig = $serviceBuilderConfig;
}
public static function getAllEvents()
{
return array('service_builder.create_client');
}
public function unserialize($serialized)
{
$this->builderConfig = json_decode($serialized, true);
}
public function serialize()
{
return json_encode($this->builderConfig);
}
/**
* Attach a plugin to every client created by the builder
*
* @param EventSubscriberInterface $plugin Plugin to attach to each client
*
* @return self
*/
public function addGlobalPlugin(EventSubscriberInterface $plugin)
{
$this->plugins[] = $plugin;
return $this;
}
/**
* Get data from the service builder without triggering the building of a service
*
* @param string $name Name of the service to retrieve
*
* @return array|null
*/
public function getData($name)
{
return isset($this->builderConfig[$name]) ? $this->builderConfig[$name] : null;
}
public function get($name, $throwAway = false)
{
if (!isset($this->builderConfig[$name])) {
// Check to see if arbitrary data is being referenced
if (isset($this->clients[$name])) {
return $this->clients[$name];
}
// Check aliases and return a match if found
foreach ($this->builderConfig as $actualName => $config) {
if (isset($config['alias']) && $config['alias'] == $name) {
return $this->get($actualName, $throwAway);
}
}
throw new ServiceNotFoundException('No service is registered as ' . $name);
}
if (!$throwAway && isset($this->clients[$name])) {
return $this->clients[$name];
}
$builder =& $this->builderConfig[$name];
// Convert references to the actual client
foreach ($builder['params'] as &$v) {
if (is_string($v) && substr($v, 0, 1) == '{' && substr($v, -1) == '}') {
$v = $this->get(trim($v, '{} '));
}
}
// Get the configured parameters and merge in any parameters provided for throw-away clients
$config = $builder['params'];
if (is_array($throwAway)) {
$config = $throwAway + $config;
}
$client = $builder['class']::factory($config);
if (!$throwAway) {
$this->clients[$name] = $client;
}
if ($client instanceof ClientInterface) {
foreach ($this->plugins as $plugin) {
$client->addSubscriber($plugin);
}
// Dispatch an event letting listeners know a client was created
$this->dispatch('service_builder.create_client', array('client' => $client));
}
return $client;
}
public function set($key, $service)
{
if (is_array($service) && isset($service['class']) && isset($service['params'])) {
$this->builderConfig[$key] = $service;
} else {
$this->clients[$key] = $service;
}
return $this;
}
public function offsetSet($offset, $value)
{
$this->set($offset, $value);
}
public function offsetUnset($offset)
{
unset($this->builderConfig[$offset]);
unset($this->clients[$offset]);
}
public function offsetExists($offset)
{
return isset($this->builderConfig[$offset]) || isset($this->clients[$offset]);
}
public function offsetGet($offset)
{
return $this->get($offset);
}
}
Guzzle-3.7.0/Guzzle/Service/Builder/ServiceBuilderInterface.php 0000644 233176441610067500000003706 12155472567 026147 0 ustar dowling ANT\Domain Users &$service) {
$service['params'] = isset($service['params']) ? $service['params'] : array();
// Check if this client builder extends another client
if (!empty($service['extends'])) {
// Make sure that the service it's extending has been defined
if (!isset($services[$service['extends']])) {
throw new ServiceNotFoundException(
"{$name} is trying to extend a non-existent service: {$service['extends']}"
);
}
$extended = &$services[$service['extends']];
// Use the correct class attribute
if (empty($service['class'])) {
$service['class'] = isset($extended['class']) ? $extended['class'] : '';
}
if ($extendsParams = isset($extended['params']) ? $extended['params'] : false) {
$service['params'] = $service['params'] + $extendsParams;
}
}
// Overwrite default values with global parameter values
if (!empty($options)) {
$service['params'] = $options + $service['params'];
}
$service['class'] = isset($service['class']) ? $service['class'] : '';
}
return new $class($services);
}
protected function mergeData(array $a, array $b)
{
$result = $b + $a;
// Merge services using a recursive union of arrays
if (isset($a['services']) && $b['services']) {
// Get a union of the services of the two arrays
$result['services'] = $b['services'] + $a['services'];
// Merge each service in using a union of the two arrays
foreach ($result['services'] as $name => &$service) {
// By default, services completely override a previously defined service unless it extends itself
if (isset($a['services'][$name]['extends'])
&& isset($b['services'][$name]['extends'])
&& $b['services'][$name]['extends'] == $name
) {
$service += $a['services'][$name];
// Use the `extends` attribute of the parent
$service['extends'] = $a['services'][$name]['extends'];
// Merge parameters using a union if both have parameters
if (isset($a['services'][$name]['params'])) {
$service['params'] += $a['services'][$name]['params'];
}
}
}
}
return $result;
}
}
Guzzle-3.7.0/Guzzle/Service/Command/AbstractCommand.php 0000644 233176441610067500000027473 12155472567 024460 0 ustar dowling ANT\Domain Users operation = $operation ?: $this->createOperation();
foreach ($this->operation->getParams() as $name => $arg) {
$currentValue = $this[$name];
$configValue = $arg->getValue($currentValue);
// If default or static values are set, then this should always be updated on the config object
if ($currentValue !== $configValue) {
$this[$name] = $configValue;
}
}
$headers = $this[self::HEADERS_OPTION];
if (!$headers instanceof Collection) {
$this[self::HEADERS_OPTION] = new Collection((array) $headers);
}
// You can set a command.on_complete option in your parameters to set an onComplete callback
if ($onComplete = $this['command.on_complete']) {
unset($this['command.on_complete']);
$this->setOnComplete($onComplete);
}
// Set the hidden additional parameters
if (!$this[self::HIDDEN_PARAMS]) {
$this[self::HIDDEN_PARAMS] = array(
self::HEADERS_OPTION,
self::RESPONSE_PROCESSING,
self::HIDDEN_PARAMS,
self::REQUEST_OPTIONS
);
}
$this->init();
}
/**
* Custom clone behavior
*/
public function __clone()
{
$this->request = null;
$this->result = null;
}
/**
* Execute the command in the same manner as calling a function
*
* @return mixed Returns the result of {@see AbstractCommand::execute}
*/
public function __invoke()
{
return $this->execute();
}
public function getName()
{
return $this->operation->getName();
}
/**
* Get the API command information about the command
*
* @return OperationInterface
*/
public function getOperation()
{
return $this->operation;
}
public function setOnComplete($callable)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException('The onComplete function must be callable');
}
$this->onComplete = $callable;
return $this;
}
public function execute()
{
if (!$this->client) {
throw new CommandException('A client must be associated with the command before it can be executed.');
}
return $this->client->execute($this);
}
public function getClient()
{
return $this->client;
}
public function setClient(ClientInterface $client)
{
$this->client = $client;
return $this;
}
public function getRequest()
{
if (!$this->request) {
throw new CommandException('The command must be prepared before retrieving the request');
}
return $this->request;
}
public function getResponse()
{
if (!$this->isExecuted()) {
$this->execute();
}
return $this->request->getResponse();
}
public function getResult()
{
if (!$this->isExecuted()) {
$this->execute();
}
if (null === $this->result) {
$this->process();
// Call the onComplete method if one is set
if ($this->onComplete) {
call_user_func($this->onComplete, $this);
}
}
return $this->result;
}
public function setResult($result)
{
$this->result = $result;
return $this;
}
public function isPrepared()
{
return $this->request !== null;
}
public function isExecuted()
{
return $this->request !== null && $this->request->getState() == 'complete';
}
public function prepare()
{
if (!$this->isPrepared()) {
if (!$this->client) {
throw new CommandException('A client must be associated with the command before it can be prepared.');
}
// If no response processing value was specified, then attempt to use the highest level of processing
if (!isset($this[self::RESPONSE_PROCESSING])) {
$this[self::RESPONSE_PROCESSING] = self::TYPE_MODEL;
}
// Notify subscribers of the client that the command is being prepared
$this->client->dispatch('command.before_prepare', array('command' => $this));
// Fail on missing required arguments, and change parameters via filters
$this->validate();
// Delegate to the subclass that implements the build method
$this->build();
// Add custom request headers set on the command
if ($headers = $this[self::HEADERS_OPTION]) {
foreach ($headers as $key => $value) {
$this->request->setHeader($key, $value);
}
}
// Add any curl options to the request
if ($options = $this[Client::CURL_OPTIONS]) {
$this->request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($options));
}
// Set a custom response body
if ($responseBody = $this[self::RESPONSE_BODY]) {
$this->request->setResponseBody($responseBody);
}
$this->client->dispatch('command.after_prepare', array('command' => $this));
}
return $this->request;
}
/**
* Set the validator used to validate and prepare command parameters and nested JSON schemas. If no validator is
* set, then the command will validate using the default {@see SchemaValidator}.
*
* @param ValidatorInterface $validator Validator used to prepare and validate properties against a JSON schema
*
* @return self
*/
public function setValidator(ValidatorInterface $validator)
{
$this->validator = $validator;
return $this;
}
public function getRequestHeaders()
{
return $this[self::HEADERS_OPTION];
}
/**
* Initialize the command (hook that can be implemented in subclasses)
*/
protected function init() {}
/**
* Create the request object that will carry out the command
*/
abstract protected function build();
/**
* Hook used to create an operation for concrete commands that are not associated with a service description
*
* @return OperationInterface
*/
protected function createOperation()
{
return new Operation(array('name' => get_class($this)));
}
/**
* Create the result of the command after the request has been completed.
* Override this method in subclasses to customize this behavior
*/
protected function process()
{
$this->result = $this[self::RESPONSE_PROCESSING] != self::TYPE_RAW
? DefaultResponseParser::getInstance()->parse($this)
: $this->request->getResponse();
}
/**
* Validate and prepare the command based on the schema and rules defined by the command's Operation object
*
* @throws ValidationException when validation errors occur
*/
protected function validate()
{
// Do not perform request validation/transformation if it is disable
if ($this[self::DISABLE_VALIDATION]) {
return;
}
$errors = array();
$validator = $this->getValidator();
foreach ($this->operation->getParams() as $name => $schema) {
$value = $this[$name];
if (!$validator->validate($schema, $value)) {
$errors = array_merge($errors, $validator->getErrors());
} elseif ($value !== $this[$name]) {
// Update the config value if it changed and no validation errors were encountered
$this->data[$name] = $value;
}
}
// Validate additional parameters
$hidden = $this[self::HIDDEN_PARAMS];
if ($properties = $this->operation->getAdditionalParameters()) {
foreach ($this->toArray() as $name => $value) {
// It's only additional if it isn't defined in the schema
if (!$this->operation->hasParam($name) && !in_array($name, $hidden)) {
// Always set the name so that error messages are useful
$properties->setName($name);
if (!$validator->validate($properties, $value)) {
$errors = array_merge($errors, $validator->getErrors());
} elseif ($value !== $this[$name]) {
$this->data[$name] = $value;
}
}
}
}
if (!empty($errors)) {
$e = new ValidationException('Validation errors: ' . implode("\n", $errors));
$e->setErrors($errors);
throw $e;
}
}
/**
* Get the validator used to prepare and validate properties. If no validator has been set on the command, then
* the default {@see SchemaValidator} will be used.
*
* @return ValidatorInterface
*/
protected function getValidator()
{
if (!$this->validator) {
$this->validator = SchemaValidator::getInstance();
}
return $this->validator;
}
}
Guzzle-3.7.0/Guzzle/Service/Command/ClosureCommand.php 0000644 233176441610067500000002435 12155472567 024320 0 ustar dowling ANT\Domain Users request = $closure($this, $this->operation);
if (!$this->request || !$this->request instanceof RequestInterface) {
throw new UnexpectedValueException('Closure command did not return a RequestInterface object');
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/CommandInterface.php 0000644 233176441610067500000006705 12155472567 024610 0 ustar dowling ANT\Domain Users factory = $factory;
}
/**
* Add a location visitor to the serializer
*
* @param string $location Location to associate with the visitor
* @param RequestVisitorInterface $visitor Visitor to attach
*
* @return self
*/
public function addVisitor($location, RequestVisitorInterface $visitor)
{
$this->factory->addRequestVisitor($location, $visitor);
return $this;
}
public function prepare(CommandInterface $command)
{
$request = $this->createRequest($command);
// Keep an array of visitors found in the operation
$foundVisitors = array();
$operation = $command->getOperation();
// Add arguments to the request using the location attribute
foreach ($operation->getParams() as $name => $arg) {
/** @var $arg \Guzzle\Service\Description\Parameter */
$location = $arg->getLocation();
// Skip 'uri' locations because they've already been processed
if ($location && $location != 'uri') {
// Instantiate visitors as they are detected in the properties
if (!isset($foundVisitors[$location])) {
$foundVisitors[$location] = $this->factory->getRequestVisitor($location);
}
// Ensure that a value has been set for this parameter
$value = $command[$name];
if ($value !== null) {
// Apply the parameter value with the location visitor
$foundVisitors[$location]->visit($command, $request, $arg, $value);
}
}
}
// Serialize additional parameters
if ($additional = $operation->getAdditionalParameters()) {
if ($visitor = $this->prepareAdditionalParameters($operation, $command, $request, $additional)) {
$foundVisitors[$additional->getLocation()] = $visitor;
}
}
// Call the after method on each visitor found in the operation
foreach ($foundVisitors as $visitor) {
$visitor->after($command, $request);
}
return $request;
}
/**
* Serialize additional parameters
*
* @param OperationInterface $operation Operation that owns the command
* @param CommandInterface $command Command to prepare
* @param RequestInterface $request Request to serialize
* @param Parameter $additional Additional parameters
*
* @return null|RequestVisitorInterface
*/
protected function prepareAdditionalParameters(
OperationInterface $operation,
CommandInterface $command,
RequestInterface $request,
Parameter $additional
) {
if (!($location = $additional->getLocation())) {
return;
}
$visitor = $this->factory->getRequestVisitor($location);
$hidden = $command[$command::HIDDEN_PARAMS];
foreach ($command->toArray() as $key => $value) {
// Ignore values that are null or built-in command options
if ($value !== null
&& !in_array($key, $hidden)
&& !$operation->hasParam($key)
) {
$additional->setName($key);
$visitor->visit($command, $request, $additional, $value);
}
}
return $visitor;
}
/**
* Create a request for the command and operation
*
* @param CommandInterface $command Command to create a request for
*
* @return RequestInterface
*/
protected function createRequest(CommandInterface $command)
{
$operation = $command->getOperation();
$client = $command->getClient();
$options = $command[AbstractCommand::REQUEST_OPTIONS] ?: array();
// If the command does not specify a template, then assume the base URL of the client
if (!($uri = $operation->getUri())) {
return $client->createRequest($operation->getHttpMethod(), $client->getBaseUrl(), null, null, $options);
}
// Get the path values and use the client config settings
$variables = array();
foreach ($operation->getParams() as $name => $arg) {
if ($arg->getLocation() == 'uri') {
if (isset($command[$name])) {
$variables[$name] = $arg->filter($command[$name]);
if (!is_array($variables[$name])) {
$variables[$name] = (string) $variables[$name];
}
}
}
}
return $client->createRequest($operation->getHttpMethod(), array($uri, $variables), null, null, $options);
}
}
Guzzle-3.7.0/Guzzle/Service/Command/DefaultResponseParser.php 0000644 233176441610067500000002721 12155472567 025663 0 ustar dowling ANT\Domain Users getRequest()->getResponse();
// Account for hard coded content-type values specified in service descriptions
if ($contentType = $command['command.expects']) {
$response->setHeader('Content-Type', $contentType);
} else {
$contentType = (string) $response->getHeader('Content-Type');
}
return $this->handleParsing($command, $response, $contentType);
}
protected function handleParsing(CommandInterface $command, Response $response, $contentType)
{
$result = $response;
if ($result->getBody()) {
if (stripos($contentType, 'json') !== false) {
$result = $result->json();
} if (stripos($contentType, 'xml') !== false) {
$result = $result->xml();
}
}
return $result;
}
}
Guzzle-3.7.0/Guzzle/Service/Command/OperationCommand.php 0000644 233176441610067500000004733 12155472567 024647 0 ustar dowling ANT\Domain Users responseParser = $parser;
return $this;
}
/**
* Set the request serializer used with the command
*
* @param RequestSerializerInterface $serializer Request serializer
*
* @return self
*/
public function setRequestSerializer(RequestSerializerInterface $serializer)
{
$this->requestSerializer = $serializer;
return $this;
}
/**
* Get the request serializer used with the command
*
* @return RequestSerializerInterface
*/
public function getRequestSerializer()
{
if (!$this->requestSerializer) {
// Use the default request serializer if none was found
$this->requestSerializer = DefaultRequestSerializer::getInstance();
}
return $this->requestSerializer;
}
/**
* Get the response parser used for the operation
*
* @return ResponseParserInterface
*/
public function getResponseParser()
{
if (!$this->responseParser) {
// Use the default response parser if none was found
$this->responseParser = OperationResponseParser::getInstance();
}
return $this->responseParser;
}
protected function build()
{
// Prepare and serialize the request
$this->request = $this->getRequestSerializer()->prepare($this);
}
protected function process()
{
// Do not process the response if 'command.response_processing' is set to 'raw'
$this->result = $this[self::RESPONSE_PROCESSING] == self::TYPE_RAW
? $this->request->getResponse()
: $this->getResponseParser()->parse($this);
}
}
Guzzle-3.7.0/Guzzle/Service/Command/OperationResponseParser.php 0000644 233176441610067500000014046 12155472567 026242 0 ustar dowling ANT\Domain Users factory = $factory;
}
/**
* Add a location visitor to the command
*
* @param string $location Location to associate with the visitor
* @param ResponseVisitorInterface $visitor Visitor to attach
*
* @return self
*/
public function addVisitor($location, ResponseVisitorInterface $visitor)
{
$this->factory->addResponseVisitor($location, $visitor);
return $this;
}
protected function handleParsing(CommandInterface $command, Response $response, $contentType)
{
$operation = $command->getOperation();
$type = $operation->getResponseType();
$model = null;
if ($type == OperationInterface::TYPE_MODEL) {
$model = $operation->getServiceDescription()->getModel($operation->getResponseClass());
} elseif ($type == OperationInterface::TYPE_CLASS) {
$responseClassInterface = __NAMESPACE__ . '\ResponseClassInterface';
$className = $operation->getResponseClass();
if (!class_exists($className)) {
throw new ResponseClassException("{$className} does not exist");
} elseif (!method_exists($className, 'fromCommand')) {
throw new ResponseClassException("{$className} must implement {$responseClassInterface}");
}
return $className::fromCommand($command);
}
if (!$model) {
// Return basic processing if the responseType is not model or the model cannot be found
return parent::handleParsing($command, $response, $contentType);
} elseif ($command[AbstractCommand::RESPONSE_PROCESSING] != AbstractCommand::TYPE_MODEL) {
// Returns a model with no visiting if the command response processing is not model
return new Model(parent::handleParsing($command, $response, $contentType), $model);
} else {
return new Model($this->visitResult($model, $command, $response), $model);
}
}
/**
* Perform transformations on the result array
*
* @param Parameter $model Model that defines the structure
* @param CommandInterface $command Command that performed the operation
* @param Response $response Response received
*
* @return array Returns the array of result data
*/
protected function visitResult(Parameter $model, CommandInterface $command, Response $response)
{
$foundVisitors = $result = array();
$props = $model->getProperties();
foreach ($props as $schema) {
if ($location = $schema->getLocation()) {
// Trigger the before method on the first found visitor of this type
if (!isset($foundVisitors[$location])) {
$foundVisitors[$location] = $this->factory->getResponseVisitor($location);
$foundVisitors[$location]->before($command, $result);
}
}
}
// Visit additional properties when it is an actual schema
if ($additional = $model->getAdditionalProperties()) {
if ($additional instanceof Parameter) {
// Only visit when a location is specified
if ($location = $additional->getLocation()) {
if (!isset($foundVisitors[$location])) {
$foundVisitors[$location] = $this->factory->getResponseVisitor($location);
$foundVisitors[$location]->before($command, $result);
}
// Only traverse if an array was parsed from the before() visitors
if (is_array($result)) {
// Find each additional property
foreach (array_keys($result) as $key) {
// Check if the model actually knows this property. If so, then it is not additional
if (!$model->getProperty($key)) {
// Set the name to the key so that we can parse it with each visitor
$additional->setName($key);
$foundVisitors[$location]->visit($command, $response, $additional, $result);
}
}
// Reset the additionalProperties name to null
$additional->setName(null);
}
}
}
}
// Apply the parameter value with the location visitor
foreach ($props as $schema) {
if ($location = $schema->getLocation()) {
$foundVisitors[$location]->visit($command, $response, $schema, $result);
}
}
// Call the after() method of each found visitor
foreach ($foundVisitors as $visitor) {
$visitor->after($command);
}
return $result;
}
}
Guzzle-3.7.0/Guzzle/Service/Command/RequestSerializerInterface.php 0000644 233176441610067500000000746 12155472567 026713 0 ustar dowling ANT\Domain Users client = $client;
$this->aliases = $aliases;
}
public function factory($name, array $args = array())
{
if (isset($this->aliases[$name])) {
try {
return $this->client->getCommand($this->aliases[$name], $args);
} catch (InvalidArgumentException $e) {
return null;
}
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/Factory/CompositeFactory.php 0000644 233176441610067500000010032 12155472567 026276 0 ustar dowling ANT\Domain Users getDescription()) {
$factories[] = new ServiceDescriptionFactory($description);
}
$factories[] = new ConcreteClassFactory($client);
return new self($factories);
}
/**
* @param array $factories Array of command factories
*/
public function __construct(array $factories = array())
{
$this->factories = $factories;
}
/**
* Add a command factory to the chain
*
* @param FactoryInterface $factory Factory to add
* @param string|FactoryInterface $before Insert the new command factory before a command factory class or object
* matching a class name.
* @return CompositeFactory
*/
public function add(FactoryInterface $factory, $before = null)
{
$pos = null;
if ($before) {
foreach ($this->factories as $i => $f) {
if ($before instanceof FactoryInterface) {
if ($f === $before) {
$pos = $i;
break;
}
} elseif (is_string($before)) {
if ($f instanceof $before) {
$pos = $i;
break;
}
}
}
}
if ($pos === null) {
$this->factories[] = $factory;
} else {
array_splice($this->factories, $i, 0, array($factory));
}
return $this;
}
/**
* Check if the chain contains a specific command factory
*
* @param FactoryInterface|string $factory Factory to check
*
* @return bool
*/
public function has($factory)
{
return (bool) $this->find($factory);
}
/**
* Remove a specific command factory from the chain
*
* @param string|FactoryInterface $factory Factory to remove by name or instance
*
* @return CompositeFactory
*/
public function remove($factory = null)
{
if (!($factory instanceof FactoryInterface)) {
$factory = $this->find($factory);
}
$this->factories = array_values(array_filter($this->factories, function($f) use ($factory) {
return $f !== $factory;
}));
return $this;
}
/**
* Get a command factory by class name
*
* @param string|FactoryInterface $factory Command factory class or instance
*
* @return null|FactoryInterface
*/
public function find($factory)
{
foreach ($this->factories as $f) {
if ($factory === $f || (is_string($factory) && $f instanceof $factory)) {
return $f;
}
}
}
/**
* Create a command using the associated command factories
*
* @param string $name Name of the command
* @param array $args Command arguments
*
* @return CommandInterface
*/
public function factory($name, array $args = array())
{
foreach ($this->factories as $factory) {
$command = $factory->factory($name, $args);
if ($command) {
return $command;
}
}
}
public function count()
{
return count($this->factories);
}
public function getIterator()
{
return new \ArrayIterator($this->factories);
}
}
Guzzle-3.7.0/Guzzle/Service/Command/Factory/ConcreteClassFactory.php 0000644 233176441610067500000003105 12155472567 027067 0 ustar dowling ANT\Domain Users client = $client;
$this->inflector = $inflector ?: Inflector::getDefault();
}
public function factory($name, array $args = array())
{
// Determine the class to instantiate based on the namespace of the current client and the default directory
$prefix = $this->client->getConfig('command.prefix');
if (!$prefix) {
// The prefix can be specified in a factory method and is cached
$prefix = implode('\\', array_slice(explode('\\', get_class($this->client)), 0, -1)) . '\\Command\\';
$this->client->getConfig()->set('command.prefix', $prefix);
}
$class = $prefix . str_replace(' ', '\\', ucwords(str_replace('.', ' ', $this->inflector->camel($name))));
// Create the concrete command if it exists
if (class_exists($class)) {
return new $class($args);
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/Factory/FactoryInterface.php 0000644 233176441610067500000000652 12155472567 026243 0 ustar dowling ANT\Domain Users map = $map;
}
public function factory($name, array $args = array())
{
if (isset($this->map[$name])) {
$class = $this->map[$name];
return new $class($args);
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/Factory/ServiceDescriptionFactory.php 0000644 233176441610067500000004155 12155472567 030151 0 ustar dowling ANT\Domain Users setServiceDescription($description);
$this->inflector = $inflector;
}
/**
* Change the service description used with the factory
*
* @param ServiceDescriptionInterface $description Service description to use
*
* @return FactoryInterface
*/
public function setServiceDescription(ServiceDescriptionInterface $description)
{
$this->description = $description;
return $this;
}
/**
* Returns the service description
*
* @return ServiceDescriptionInterface
*/
public function getServiceDescription()
{
return $this->description;
}
public function factory($name, array $args = array())
{
$command = $this->description->getOperation($name);
// If a command wasn't found, then try to uppercase the first letter and try again
if (!$command) {
$command = $this->description->getOperation(ucfirst($name));
// If an inflector was passed, then attempt to get the command using snake_case inflection
if (!$command && $this->inflector) {
$command = $this->description->getOperation($this->inflector->snake($name));
}
}
if ($command) {
$class = $command->getClass();
return new $class($args, $command, $this->description);
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/VisitorFlyweight.php 0000644 233176441610067500000011323 12155472567 030053 0 ustar dowling ANT\Domain Users 'Guzzle\Service\Command\LocationVisitor\Request\BodyVisitor',
'request.header' => 'Guzzle\Service\Command\LocationVisitor\Request\HeaderVisitor',
'request.json' => 'Guzzle\Service\Command\LocationVisitor\Request\JsonVisitor',
'request.postField' => 'Guzzle\Service\Command\LocationVisitor\Request\PostFieldVisitor',
'request.postFile' => 'Guzzle\Service\Command\LocationVisitor\Request\PostFileVisitor',
'request.query' => 'Guzzle\Service\Command\LocationVisitor\Request\QueryVisitor',
'request.response_body' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor',
'request.responseBody' => 'Guzzle\Service\Command\LocationVisitor\Request\ResponseBodyVisitor',
'request.xml' => 'Guzzle\Service\Command\LocationVisitor\Request\XmlVisitor',
'response.body' => 'Guzzle\Service\Command\LocationVisitor\Response\BodyVisitor',
'response.header' => 'Guzzle\Service\Command\LocationVisitor\Response\HeaderVisitor',
'response.json' => 'Guzzle\Service\Command\LocationVisitor\Response\JsonVisitor',
'response.reasonPhrase' => 'Guzzle\Service\Command\LocationVisitor\Response\ReasonPhraseVisitor',
'response.statusCode' => 'Guzzle\Service\Command\LocationVisitor\Response\StatusCodeVisitor',
'response.xml' => 'Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor'
);
/** @var array Array of mappings of location names to classes */
protected $mappings;
/** @var array Cache of instantiated visitors */
protected $cache = array();
/**
* @return self
* @codeCoverageIgnore
*/
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* @param array $mappings Array mapping request.name and response.name to location visitor classes. Leave null to
* use the default values.
*/
public function __construct(array $mappings = null)
{
$this->mappings = $mappings === null ? self::$defaultMappings : $mappings;
}
/**
* Get an instance of a request visitor by location name
*
* @param string $visitor Visitor name
*
* @return RequestVisitorInterface
*/
public function getRequestVisitor($visitor)
{
return $this->getKey('request.' . $visitor);
}
/**
* Get an instance of a response visitor by location name
*
* @param string $visitor Visitor name
*
* @return ResponseVisitorInterface
*/
public function getResponseVisitor($visitor)
{
return $this->getKey('response.' . $visitor);
}
/**
* Add a response visitor to the factory by name
*
* @param string $name Name of the visitor
* @param RequestVisitorInterface $visitor Visitor to add
*
* @return self
*/
public function addRequestVisitor($name, RequestVisitorInterface $visitor)
{
$this->cache['request.' . $name] = $visitor;
return $this;
}
/**
* Add a response visitor to the factory by name
*
* @param string $name Name of the visitor
* @param ResponseVisitorInterface $visitor Visitor to add
*
* @return self
*/
public function addResponseVisitor($name, ResponseVisitorInterface $visitor)
{
$this->cache['response.' . $name] = $visitor;
return $this;
}
/**
* Get a visitor by key value name
*
* @param string $key Key name to retrieve
*
* @return mixed
* @throws InvalidArgumentException
*/
private function getKey($key)
{
if (!isset($this->cache[$key])) {
if (!isset($this->mappings[$key])) {
list($type, $name) = explode('.', $key);
throw new InvalidArgumentException("No {$type} visitor has been mapped for {$name}");
}
$this->cache[$key] = new $this->mappings[$key];
}
return $this->cache[$key];
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/AbstractRequestVisitor.php 0000644 233176441610067500000004376 12155472567 032667 0 ustar dowling ANT\Domain Users resolveRecursively($value, $param)
: $param->filter($value);
}
/**
* Map nested parameters into the location_key based parameters
*
* @param array $value Value to map
* @param Parameter $param Parameter that holds information about the current key
*
* @return array Returns the mapped array
*/
protected function resolveRecursively(array $value, Parameter $param)
{
foreach ($value as $name => &$v) {
switch ($param->getType()) {
case 'object':
if ($subParam = $param->getProperty($name)) {
$key = $subParam->getWireName();
$value[$key] = $this->prepareValue($v, $subParam);
if ($name != $key) {
unset($value[$name]);
}
} elseif ($param->getAdditionalProperties() instanceof Parameter) {
$v = $this->prepareValue($v, $param->getAdditionalProperties());
}
break;
case 'array':
if ($items = $param->getItems()) {
$v = $this->prepareValue($v, $items);
}
break;
}
}
return $param->filter($value);
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/BodyVisitor.php 0000644 233176441610067500000004657 12155472567 030452 0 ustar dowling ANT\Domain Users filter($value);
$entityBody = EntityBody::factory($value);
$request->setBody($entityBody);
$this->addExpectHeader($request, $entityBody, $param->getData('expect_header'));
// Add the Content-Encoding header if one is set on the EntityBody
if ($encoding = $entityBody->getContentEncoding()) {
$request->setHeader('Content-Encoding', $encoding);
}
}
/**
* Add the appropriate expect header to a request
*
* @param EntityEnclosingRequestInterface $request Request to update
* @param EntityBodyInterface $body Entity body of the request
* @param string|int $expect Expect header setting
*/
protected function addExpectHeader(EntityEnclosingRequestInterface $request, EntityBodyInterface $body, $expect)
{
// Allow the `expect` data parameter to be set to remove the Expect header from the request
if ($expect === false) {
$request->removeHeader('Expect');
} elseif ($expect !== true) {
// Default to using a MB as the point in which to start using the expect header
$expect = $expect ?: 1048576;
// If the expect_header value is numeric then only add if the size is greater than the cutoff
if (is_numeric($expect) && $body->getSize()) {
if ($body->getSize() < $expect) {
$request->removeHeader('Expect');
} else {
$request->setHeader('Expect', '100-Continue');
}
}
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/HeaderVisitor.php 0000644 233176441610067500000002771 12155472567 030740 0 ustar dowling ANT\Domain Users filter($value);
if ($param->getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) {
$this->addPrefixedHeaders($request, $param, $value);
} else {
$request->setHeader($param->getWireName(), $value);
}
}
/**
* Add a prefixed array of headers to the request
*
* @param RequestInterface $request Request to update
* @param Parameter $param Parameter object
* @param array $value Header array to add
*
* @throws InvalidArgumentException
*/
protected function addPrefixedHeaders(RequestInterface $request, Parameter $param, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('An array of mapped headers expected, but received a single value');
}
$prefix = $param->getSentAs();
foreach ($value as $headerName => $headerValue) {
$request->setHeader($prefix . $headerName, $headerValue);
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/JsonVisitor.php 0000644 233176441610067500000003747 12155472567 030465 0 ustar dowling ANT\Domain Users data = new \SplObjectStorage();
}
/**
* Set the Content-Type header to add to the request if JSON is added to the body. This visitor does not add a
* Content-Type header unless you specify one here.
*
* @param string $header Header to set when JSON is added (e.g. application/json)
*
* @return self
*/
public function setContentTypeHeader($header = 'application/json')
{
$this->jsonContentType = $header;
return $this;
}
public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
{
if (isset($this->data[$command])) {
$json = $this->data[$command];
} else {
$json = array();
}
$json[$param->getWireName()] = $this->prepareValue($value, $param);
$this->data[$command] = $json;
}
public function after(CommandInterface $command, RequestInterface $request)
{
if (isset($this->data[$command])) {
$request->setBody(json_encode($this->data[$command]));
unset($this->data[$command]);
// Don't overwrite the Content-Type if one is set
if ($this->jsonContentType && !$request->hasHeader('Content-Type')) {
$request->setHeader('Content-Type', $this->jsonContentType);
}
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/PostFieldVisitor.php 0000644 233176441610067500000001015 12155472567 031427 0 ustar dowling ANT\Domain Users setPostField($param->getWireName(), $this->prepareValue($value, $param));
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/PostFileVisitor.php 0000644 233176441610067500000001276 12155472567 031274 0 ustar dowling ANT\Domain Users filter($value);
if ($value instanceof PostFileInterface) {
$request->addPostFile($value);
} else {
$request->addPostFile($param->getWireName(), $value);
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/QueryVisitor.php 0000644 233176441610067500000001030 12155472567 030640 0 ustar dowling ANT\Domain Users getQuery()->set($param->getWireName(), $this->prepareValue($value, $param));
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/RequestVisitorInterface.php 0000644 233176441610067500000002067 12155472567 033017 0 ustar dowling ANT\Domain Users setResponseBody($value);
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Request/XmlVisitor.php 0000644 233176441610067500000012267 12155472567 030311 0 ustar dowling ANT\Domain Users data = new \SplObjectStorage();
}
/**
* Change the content-type header that is added when XML is found
*
* @param string $header Header to set when XML is found
*
* @return self
*/
public function setContentTypeHeader($header)
{
$this->contentType = $header;
return $this;
}
public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
{
$xml = isset($this->data[$command])
? $this->data[$command]
: $this->createRootElement($param->getParent());
$this->addXml($xml, $param, $value);
$this->data[$command] = $xml;
}
public function after(CommandInterface $command, RequestInterface $request)
{
$xml = null;
// If data was found that needs to be serialized, then do so
if (isset($this->data[$command])) {
$xml = $this->data[$command]->asXML();
unset($this->data[$command]);
} else {
// Check if XML should always be sent for the command
$operation = $command->getOperation();
if ($operation->getData('xmlAllowEmpty')) {
$xml = $this->createRootElement($operation)->asXML();
}
}
if ($xml) {
$request->setBody($xml);
// Don't overwrite the Content-Type if one is set
if ($this->contentType && !$request->hasHeader('Content-Type')) {
$request->setHeader('Content-Type', $this->contentType);
}
}
}
/**
* Create the root XML element to use with a request
*
* @param Operation $operation Operation object
*
* @return \SimpleXMLElement
*/
protected function createRootElement(Operation $operation)
{
static $defaultRoot = array('name' => 'Request');
// If no root element was specified, then just wrap the XML in 'Request'
$root = $operation->getData('xmlRoot') ?: $defaultRoot;
// Allow the XML declaration to be customized with xmlEncoding
$declaration = 'getData('xmlEncoding')) {
$declaration .= ' encoding="' . $encoding . '"';
}
$declaration .= "?>";
// Create the wrapping element with no namespaces if no namespaces were present
if (empty($root['namespaces'])) {
return new \SimpleXMLElement("{$declaration}\n<{$root['name']}/>");
} else {
// Create the wrapping element with an array of one or more namespaces
$xml = "{$declaration}\n<{$root['name']} ";
foreach ((array) $root['namespaces'] as $prefix => $uri) {
$xml .= is_numeric($prefix) ? "xmlns=\"{$uri}\" " : "xmlns:{$prefix}=\"{$uri}\" ";
}
return new \SimpleXMLElement($xml . "/>");
}
}
/**
* Recursively build the XML body
*
* @param \SimpleXMLElement $xml XML to modify
* @param Parameter $param API Parameter
* @param mixed $value Value to add
*/
protected function addXml(\SimpleXMLElement $xml, Parameter $param, $value)
{
if ($value === null) {
return;
}
$value = $param->filter($value);
$type = $param->getType();
if ($type == 'object' || $type == 'array') {
$ele = $param->getData('xmlFlattened') ? $xml : $xml->addChild($param->getWireName());
if ($param->getType() == 'array') {
$this->addXmlArray($ele, $param, $value, $param->getData('xmlNamespace'));
} elseif ($param->getType() == 'object') {
$this->addXmlObject($ele, $param, $value);
}
} elseif ($param->getData('xmlAttribute')) {
$xml->addAttribute($param->getWireName(), $value, $param->getData('xmlNamespace'));
} else {
$xml->addChild($param->getWireName(), $value, $param->getData('xmlNamespace'));
}
}
/**
* Add an array to the XML
*/
protected function addXmlArray(\SimpleXMLElement $xml, Parameter $param, &$value)
{
if ($items = $param->getItems()) {
foreach ($value as $v) {
$this->addXml($xml, $items, $v);
}
}
}
/**
* Add an object to the XML
*/
protected function addXmlObject(\SimpleXMLElement $xml, Parameter $param, &$value)
{
foreach ($value as $name => $v) {
if ($property = $param->getProperty($name)) {
$this->addXml($xml, $property, $v);
}
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Response/AbstractResponseVisitor.php 0000644 233176441610067500000001146 12155472567 033173 0 ustar dowling ANT\Domain Users getName()] = $param->filter($response->getBody());
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Response/HeaderVisitor.php 0000644 233176441610067500000003426 12155472567 031104 0 ustar dowling ANT\Domain Users getType() == 'object' && $param->getAdditionalProperties() instanceof Parameter) {
$this->processPrefixedHeaders($response, $param, $value);
} else {
$value[$param->getName()] = $param->filter((string) $response->getHeader($param->getWireName()));
}
}
/**
* Process a prefixed header array
*
* @param Response $response Response that contains the headers
* @param Parameter $param Parameter object
* @param array $value Value response array to modify
*/
protected function processPrefixedHeaders(Response $response, Parameter $param, &$value)
{
// Grab prefixed headers that should be placed into an array with the prefix stripped
if ($prefix = $param->getSentAs()) {
$container = $param->getName();
$len = strlen($prefix);
// Find all matching headers and place them into the containing element
foreach ($response->getHeaders()->toArray() as $key => $header) {
if (stripos($key, $prefix) === 0) {
// Account for multi-value headers
$value[$container][substr($key, $len)] = count($header) == 1 ? end($header) : $header;
}
}
}
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Response/JsonVisitor.php 0000644 233176441610067500000005520 12155472567 030622 0 ustar dowling ANT\Domain Users getResponse()->json();
}
public function visit(
CommandInterface $command,
Response $response,
Parameter $param,
&$value,
$context = null
) {
$name = $param->getName();
$key = $param->getWireName();
if (isset($value[$key])) {
$this->recursiveProcess($param, $value[$key]);
if ($key != $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
}
/**
* Recursively process a parameter while applying filters
*
* @param Parameter $param API parameter being validated
* @param mixed $value Value to validate and process. The value may change during this process.
*/
protected function recursiveProcess(Parameter $param, &$value)
{
if ($value === null) {
return;
}
if (is_array($value)) {
$type = $param->getType();
if ($type == 'array') {
foreach ($value as &$item) {
$this->recursiveProcess($param->getItems(), $item);
}
} elseif ($type == 'object' && !isset($value[0])) {
// On the above line, we ensure that the array is associative and not numerically indexed
if ($properties = $param->getProperties()) {
foreach ($properties as $property) {
$name = $property->getName();
$key = $property->getWireName();
if (isset($value[$key])) {
$this->recursiveProcess($property, $value[$key]);
if ($key != $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
}
}
}
}
$value = $param->filter($value);
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Response/ReasonPhraseVisitor.php 0000644 233176441610067500000001110 12155472567 032272 0 ustar dowling ANT\Domain Users getName()] = $response->getReasonPhrase();
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Response/ResponseVisitorInterface.php 0000644 233176441610067500000003062 12155472567 033327 0 ustar dowling ANT\Domain Users getName()] = $response->getStatusCode();
}
}
Guzzle-3.7.0/Guzzle/Service/Command/LocationVisitor/Response/XmlVisitor.php 0000644 233176441610067500000012103 12155472567 030444 0 ustar dowling ANT\Domain Users getResponse()->xml()), true);
}
public function visit(
CommandInterface $command,
Response $response,
Parameter $param,
&$value,
$context = null
) {
$sentAs = $param->getWireName();
$name = $param->getName();
if (isset($value[$sentAs])) {
$this->recursiveProcess($param, $value[$sentAs]);
if ($name != $sentAs) {
$value[$name] = $value[$sentAs];
unset($value[$sentAs]);
}
}
}
/**
* Recursively process a parameter while applying filters
*
* @param Parameter $param API parameter being processed
* @param mixed $value Value to validate and process. The value may change during this process.
*/
protected function recursiveProcess(Parameter $param, &$value)
{
$type = $param->getType();
if (!is_array($value)) {
if ($type == 'array') {
// Cast to an array if the value was a string, but should be an array
$this->recursiveProcess($param->getItems(), $value);
$value = array($value);
}
} elseif ($type == 'object') {
$this->processObject($param, $value);
} elseif ($type == 'array') {
$this->processArray($param, $value);
}
if ($value !== null) {
$value = $param->filter($value);
}
}
/**
* Process an array
*
* @param Parameter $param API parameter being parsed
* @param mixed $value Value to process
*/
protected function processArray(Parameter $param, &$value)
{
// Convert the node if it was meant to be an array
if (!isset($value[0])) {
// Collections fo nodes are sometimes wrapped in an additional array. For example:
// 12 should become:
// array('Items' => array(array('a' => 1), array('a' => 2))
// Some nodes are not wrapped. For example: 12
// should become array('Foo' => array(array('a' => 1), array('a' => 2))
if ($param->getItems() && isset($value[$param->getItems()->getWireName()])) {
// Account for the case of a collection wrapping wrapped nodes: Items => Item[]
$value = $value[$param->getItems()->getWireName()];
// If the wrapped node only had one value, then make it an array of nodes
if (!isset($value[0]) || !is_array($value)) {
$value = array($value);
}
} elseif (!empty($value)) {
// Account for repeated nodes that must be an array: Foo => Baz, Foo => Baz, but only if the
// value is set and not empty
$value = array($value);
}
}
foreach ($value as &$item) {
$this->recursiveProcess($param->getItems(), $item);
}
}
/**
* Process an object
*
* @param Parameter $param API parameter being parsed
* @param mixed $value Value to process
*/
protected function processObject(Parameter $param, &$value)
{
// Ensure that the array is associative and not numerically indexed
if (!isset($value[0]) && ($properties = $param->getProperties())) {
foreach ($properties as $property) {
$name = $property->getName();
$sentAs = $property->getWireName();
if ($property->getData('xmlAttribute')) {
$this->processXmlAttribute($property, $value);
} elseif (isset($value[$sentAs])) {
$this->recursiveProcess($property, $value[$sentAs]);
if ($name != $sentAs) {
$value[$name] = $value[$sentAs];
unset($value[$sentAs]);
}
}
}
}
}
/**
* Process an XML attribute property
*
* @param Parameter $property Property to process
* @param array $value Value to process and update
*/
protected function processXmlAttribute(Parameter $property, array &$value)
{
$sentAs = $property->getWireName();
if (isset($value['@attributes'][$sentAs])) {
$value[$property->getName()] = $value['@attributes'][$sentAs];
unset($value['@attributes'][$sentAs]);
if (empty($value['@attributes'])) {
unset($value['@attributes']);
}
}
}
}
Guzzle-3.7.0/Guzzle/Service/Description/Operation.php 0000644 233176441610067500000037030 12155472567 024251 0 ustar dowling ANT\Domain Users true, 'httpMethod' => true, 'uri' => true, 'class' => true, 'responseClass' => true,
'responseType' => true, 'responseNotes' => true, 'notes' => true, 'summary' => true, 'documentationUrl' => true,
'deprecated' => true, 'data' => true, 'parameters' => true, 'additionalParameters' => true,
'errorResponses' => true
);
/** @var array Parameters */
protected $parameters = array();
/** @var Parameter Additional parameters schema */
protected $additionalParameters;
/** @var string Name of the command */
protected $name;
/** @var string HTTP method */
protected $httpMethod;
/** @var string This is a short summary of what the operation does */
protected $summary;
/** @var string A longer text field to explain the behavior of the operation. */
protected $notes;
/** @var string Reference URL providing more information about the operation */
protected $documentationUrl;
/** @var string HTTP URI of the command */
protected $uri;
/** @var string Class of the command object */
protected $class;
/** @var string This is what is returned from the method */
protected $responseClass;
/** @var string Type information about the response */
protected $responseType;
/** @var string Information about the response returned by the operation */
protected $responseNotes;
/** @var bool Whether or not the command is deprecated */
protected $deprecated;
/** @var array Array of errors that could occur when running the command */
protected $errorResponses;
/** @var ServiceDescriptionInterface */
protected $description;
/** @var array Extra operation information */
protected $data;
/**
* Builds an Operation object using an array of configuration data:
* - name: (string) Name of the command
* - httpMethod: (string) HTTP method of the operation
* - uri: (string) URI template that can create a relative or absolute URL
* - class: (string) Concrete class that implements this command
* - parameters: (array) Associative array of parameters for the command. {@see Parameter} for information.
* - summary: (string) This is a short summary of what the operation does
* - notes: (string) A longer text field to explain the behavior of the operation.
* - documentationUrl: (string) Reference URL providing more information about the operation
* - responseClass: (string) This is what is returned from the method. Can be a primitive, PSR-0 compliant
* class name, or model.
* - responseNotes: (string) Information about the response returned by the operation
* - responseType: (string) One of 'primitive', 'class', 'model', or 'documentation'. If not specified, this
* value will be automatically inferred based on whether or not there is a model matching the
* name, if a matching PSR-0 compliant class name is found, or set to 'primitive' by default.
* - deprecated: (bool) Set to true if this is a deprecated command
* - errorResponses: (array) Errors that could occur when executing the command. Array of hashes, each with a
* 'code' (the HTTP response code), 'phrase' (response reason phrase or description of the
* error), and 'class' (a custom exception class that would be thrown if the error is
* encountered).
* - data: (array) Any extra data that might be used to help build or serialize the operation
* - additionalParameters: (null|array) Parameter schema to use when an option is passed to the operation that is
* not in the schema
*
* @param array $config Array of configuration data
* @param ServiceDescriptionInterface $description Service description used to resolve models if $ref tags are found
*/
public function __construct(array $config = array(), ServiceDescriptionInterface $description = null)
{
$this->description = $description;
// Get the intersection of the available properties and properties set on the operation
foreach (array_intersect_key($config, self::$properties) as $key => $value) {
$this->{$key} = $value;
}
$this->class = $this->class ?: self::DEFAULT_COMMAND_CLASS;
$this->deprecated = (bool) $this->deprecated;
$this->errorResponses = $this->errorResponses ?: array();
$this->data = $this->data ?: array();
if (!$this->responseClass) {
$this->responseClass = 'array';
$this->responseType = 'primitive';
} elseif ($this->responseType) {
// Set the response type to perform validation
$this->setResponseType($this->responseType);
} else {
// A response class was set and no response type was set, so guess what the type is
$this->inferResponseType();
}
// Parameters need special handling when adding
if ($this->parameters) {
foreach ($this->parameters as $name => $param) {
if ($param instanceof Parameter) {
$param->setName($name)->setParent($this);
} elseif (is_array($param)) {
$param['name'] = $name;
$this->addParam(new Parameter($param, $this->description));
}
}
}
if ($this->additionalParameters) {
if ($this->additionalParameters instanceof Parameter) {
$this->additionalParameters->setParent($this);
} elseif (is_array($this->additionalParameters)) {
$this->setadditionalParameters(new Parameter($this->additionalParameters, $this->description));
}
}
}
public function toArray()
{
$result = array();
// Grab valid properties and filter out values that weren't set
foreach (array_keys(self::$properties) as $check) {
if ($value = $this->{$check}) {
$result[$check] = $value;
}
}
// Remove the name property
unset($result['name']);
// Parameters need to be converted to arrays
$result['parameters'] = array();
foreach ($this->parameters as $key => $param) {
$result['parameters'][$key] = $param->toArray();
}
// Additional parameters need to be cast to an array
if ($this->additionalParameters instanceof Parameter) {
$result['additionalParameters'] = $this->additionalParameters->toArray();
}
return $result;
}
public function getServiceDescription()
{
return $this->description;
}
public function setServiceDescription(ServiceDescriptionInterface $description)
{
$this->description = $description;
return $this;
}
public function getParams()
{
return $this->parameters;
}
public function getParamNames()
{
return array_keys($this->parameters);
}
public function hasParam($name)
{
return isset($this->parameters[$name]);
}
public function getParam($param)
{
return isset($this->parameters[$param]) ? $this->parameters[$param] : null;
}
/**
* Add a parameter to the command
*
* @param Parameter $param Parameter to add
*
* @return self
*/
public function addParam(Parameter $param)
{
$this->parameters[$param->getName()] = $param;
$param->setParent($this);
return $this;
}
/**
* Remove a parameter from the command
*
* @param string $name Name of the parameter to remove
*
* @return self
*/
public function removeParam($name)
{
unset($this->parameters[$name]);
return $this;
}
public function getHttpMethod()
{
return $this->httpMethod;
}
/**
* Set the HTTP method of the command
*
* @param string $httpMethod Method to set
*
* @return self
*/
public function setHttpMethod($httpMethod)
{
$this->httpMethod = $httpMethod;
return $this;
}
public function getClass()
{
return $this->class;
}
/**
* Set the concrete class of the command
*
* @param string $className Concrete class name
*
* @return self
*/
public function setClass($className)
{
$this->class = $className;
return $this;
}
public function getName()
{
return $this->name;
}
/**
* Set the name of the command
*
* @param string $name Name of the command
*
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getSummary()
{
return $this->summary;
}
/**
* Set a short summary of what the operation does
*
* @param string $summary Short summary of the operation
*
* @return self
*/
public function setSummary($summary)
{
$this->summary = $summary;
return $this;
}
public function getNotes()
{
return $this->notes;
}
/**
* Set a longer text field to explain the behavior of the operation.
*
* @param string $notes Notes on the operation
*
* @return self
*/
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
public function getDocumentationUrl()
{
return $this->documentationUrl;
}
/**
* Set the URL pointing to additional documentation on the command
*
* @param string $docUrl Documentation URL
*
* @return self
*/
public function setDocumentationUrl($docUrl)
{
$this->documentationUrl = $docUrl;
return $this;
}
public function getResponseClass()
{
return $this->responseClass;
}
/**
* Set what is returned from the method. Can be a primitive, class name, or model. For example: 'array',
* 'Guzzle\\Foo\\Baz', or 'MyModelName' (to reference a model by ID).
*
* @param string $responseClass Type of response
*
* @return self
*/
public function setResponseClass($responseClass)
{
$this->responseClass = $responseClass;
$this->inferResponseType();
return $this;
}
public function getResponseType()
{
return $this->responseType;
}
/**
* Set qualifying information about the responseClass. One of 'primitive', 'class', 'model', or 'documentation'
*
* @param string $responseType Response type information
*
* @return self
* @throws InvalidArgumentException
*/
public function setResponseType($responseType)
{
static $types = array(
self::TYPE_PRIMITIVE => true,
self::TYPE_CLASS => true,
self::TYPE_MODEL => true,
self::TYPE_DOCUMENTATION => true
);
if (!isset($types[$responseType])) {
throw new InvalidArgumentException('responseType must be one of ' . implode(', ', array_keys($types)));
}
$this->responseType = $responseType;
return $this;
}
public function getResponseNotes()
{
return $this->responseNotes;
}
/**
* Set notes about the response of the operation
*
* @param string $notes Response notes
*
* @return self
*/
public function setResponseNotes($notes)
{
$this->responseNotes = $notes;
return $this;
}
public function getDeprecated()
{
return $this->deprecated;
}
/**
* Set whether or not the command is deprecated
*
* @param bool $isDeprecated Set to true to mark as deprecated
*
* @return self
*/
public function setDeprecated($isDeprecated)
{
$this->deprecated = $isDeprecated;
return $this;
}
public function getUri()
{
return $this->uri;
}
/**
* Set the URI template of the command
*
* @param string $uri URI template to set
*
* @return self
*/
public function setUri($uri)
{
$this->uri = $uri;
return $this;
}
public function getErrorResponses()
{
return $this->errorResponses;
}
/**
* Add an error to the command
*
* @param string $code HTTP response code
* @param string $reason HTTP response reason phrase or information about the error
* @param string $class Exception class associated with the error
*
* @return self
*/
public function addErrorResponse($code, $reason, $class)
{
$this->errorResponses[] = array('code' => $code, 'reason' => $reason, 'class' => $class);
return $this;
}
/**
* Set all of the error responses of the operation
*
* @param array $errorResponses Hash of error name to a hash containing a code, reason, class
*
* @return self
*/
public function setErrorResponses(array $errorResponses)
{
$this->errorResponses = $errorResponses;
return $this;
}
public function getData($name)
{
return isset($this->data[$name]) ? $this->data[$name] : null;
}
/**
* Set a particular data point on the operation
*
* @param string $name Name of the data value
* @param mixed $value Value to set
*
* @return self
*/
public function setData($name, $value)
{
$this->data[$name] = $value;
return $this;
}
/**
* Get the additionalParameters of the operation
*
* @return Paramter|null
*/
public function getAdditionalParameters()
{
return $this->additionalParameters;
}
/**
* Set the additionalParameters of the operation
*
* @param Parameter|null $parameter Parameter to set
*
* @return self
*/
public function setAdditionalParameters($parameter)
{
if ($this->additionalParameters = $parameter) {
$this->additionalParameters->setParent($this);
}
return $this;
}
/**
* Infer the response type from the responseClass value
*/
protected function inferResponseType()
{
if (!$this->responseClass || $this->responseClass == 'array' || $this->responseClass == 'string'
|| $this->responseClass == 'boolean' || $this->responseClass == 'integer'
) {
$this->responseType = self::TYPE_PRIMITIVE;
} elseif ($this->description && $this->description->hasModel($this->responseClass)) {
$this->responseType = self::TYPE_MODEL;
} elseif (strpos($this->responseClass, '\\') !== false) {
$this->responseType = self::TYPE_CLASS;
} else {
$this->responseType = self::TYPE_PRIMITIVE;
}
}
}
Guzzle-3.7.0/Guzzle/Service/Description/OperationInterface.php 0000644 233176441610067500000007211 12155472567 026070 0 ustar dowling ANT\Domain Users getModel($data['$ref'])) {
// The name of the original parameter should override the ref name if one is available
$name = empty($data['name']) ? null : $data['name'];
$data = $model->toArray();
if ($name) {
$data['name'] = $name;
}
}
} elseif (isset($data['extends'])) {
// If this parameter extends from another parameter then start with the actual data
// union in the parent's data (e.g. actual supersedes parent)
if ($extends = $description->getModel($data['extends'])) {
$data += $extends->toArray();
}
}
}
// Pull configuration data into the parameter
foreach ($data as $key => $value) {
$this->{$key} = $value;
}
$this->serviceDescription = $description;
$this->required = (bool) $this->required;
$this->data = (array) $this->data;
if ($this->filters) {
$this->setFilters((array) $this->filters);
}
if ($this->type == 'object' && $this->additionalProperties === null) {
$this->additionalProperties = true;
}
}
/**
* Convert the object to an array
*
* @return array
*/
public function toArray()
{
$result = array();
$checks = array('required', 'description', 'static', 'type', 'format', 'instanceOf', 'location', 'sentAs',
'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'data', 'enum',
'filters');
// Anything that is in the `Items` attribute of an array *must* include it's name if available
if ($this->parent instanceof self && $this->parent->getType() == 'array' && isset($this->name)) {
$result['name'] = $this->name;
}
foreach ($checks as $c) {
if ($value = $this->{$c}) {
$result[$c] = $value;
}
}
if ($this->default !== null) {
$result['default'] = $this->default;
}
if ($this->items !== null) {
$result['items'] = $this->getItems()->toArray();
}
if ($this->additionalProperties !== null) {
$result['additionalProperties'] = $this->getAdditionalProperties();
if ($result['additionalProperties'] instanceof self) {
$result['additionalProperties'] = $result['additionalProperties']->toArray();
}
}
if ($this->type == 'object' && $this->properties) {
$result['properties'] = array();
foreach ($this->getProperties() as $name => $property) {
$result['properties'][$name] = $property->toArray();
}
}
return $result;
}
/**
* Get the default or static value of the command based on a value
*
* @param string $value Value that is currently set
*
* @return mixed Returns the value, a static value if one is present, or a default value
*/
public function getValue($value)
{
return $this->static || ($this->default !== null && !$value && ($this->type != 'boolean' || $value !== false))
? $this->default
: $value;
}
/**
* Run a value through the filters OR format attribute associated with the parameter
*
* @param mixed $value Value to filter
*
* @return mixed Returns the filtered value
*/
public function filter($value)
{
// Formats are applied exclusively and supersed filters
if ($this->format) {
return SchemaFormatter::format($this->format, $value);
}
// Convert Boolean values
if ($this->type == 'boolean' && !is_bool($value)) {
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
// Apply filters to the value
if ($this->filters) {
foreach ($this->filters as $filter) {
if (is_array($filter)) {
// Convert complex filters that hold value place holders
foreach ($filter['args'] as &$data) {
if ($data == '@value') {
$data = $value;
} elseif ($data == '@api') {
$data = $this;
}
}
$value = call_user_func_array($filter['method'], $filter['args']);
} else {
$value = call_user_func($filter, $value);
}
}
}
return $value;
}
/**
* Get the name of the parameter
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get the key of the parameter, where sentAs will supersede name if it is set
*
* @return string
*/
public function getWireName()
{
return $this->sentAs ?: $this->name;
}
/**
* Set the name of the parameter
*
* @param string $name Name to set
*
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get the type(s) of the parameter
*
* @return string|array
*/
public function getType()
{
return $this->type;
}
/**
* Set the type(s) of the parameter
*
* @param string|array $type Type of parameter or array of simple types used in a union
*
* @return self
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get if the parameter is required
*
* @return bool
*/
public function getRequired()
{
return $this->required;
}
/**
* Set if the parameter is required
*
* @param bool $isRequired Whether or not the parameter is required
*
* @return self
*/
public function setRequired($isRequired)
{
$this->required = (bool) $isRequired;
return $this;
}
/**
* Get the default value of the parameter
*
* @return string|null
*/
public function getDefault()
{
return $this->default;
}
/**
* Set the default value of the parameter
*
* @param string|null $default Default value to set
*
* @return self
*/
public function setDefault($default)
{
$this->default = $default;
return $this;
}
/**
* Get the description of the parameter
*
* @return string|null
*/
public function getDescription()
{
return $this->description;
}
/**
* Set the description of the parameter
*
* @param string $description Description
*
* @return self
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get the minimum acceptable value for an integer
*
* @return int|null
*/
public function getMinimum()
{
return $this->minimum;
}
/**
* Set the minimum acceptable value for an integer
*
* @param int|null $min Minimum
*
* @return self
*/
public function setMinimum($min)
{
$this->minimum = $min;
return $this;
}
/**
* Get the maximum acceptable value for an integer
*
* @return int|null
*/
public function getMaximum()
{
return $this->maximum;
}
/**
* Set the maximum acceptable value for an integer
*
* @param int $max Maximum
*
* @return self
*/
public function setMaximum($max)
{
$this->maximum = $max;
return $this;
}
/**
* Get the minimum allowed length of a string value
*
* @return int
*/
public function getMinLength()
{
return $this->minLength;
}
/**
* Set the minimum allowed length of a string value
*
* @param int|null $min Minimum
*
* @return self
*/
public function setMinLength($min)
{
$this->minLength = $min;
return $this;
}
/**
* Get the maximum allowed length of a string value
*
* @return int|null
*/
public function getMaxLength()
{
return $this->maxLength;
}
/**
* Set the maximum allowed length of a string value
*
* @param int $max Maximum length
*
* @return self
*/
public function setMaxLength($max)
{
$this->maxLength = $max;
return $this;
}
/**
* Get the maximum allowed number of items in an array value
*
* @return int|null
*/
public function getMaxItems()
{
return $this->maxItems;
}
/**
* Set the maximum allowed number of items in an array value
*
* @param int $max Maximum
*
* @return self
*/
public function setMaxItems($max)
{
$this->maxItems = $max;
return $this;
}
/**
* Get the minimum allowed number of items in an array value
*
* @return int
*/
public function getMinItems()
{
return $this->minItems;
}
/**
* Set the minimum allowed number of items in an array value
*
* @param int|null $min Minimum
*
* @return self
*/
public function setMinItems($min)
{
$this->minItems = $min;
return $this;
}
/**
* Get the location of the parameter
*
* @return string|null
*/
public function getLocation()
{
return $this->location;
}
/**
* Set the location of the parameter
*
* @param string|null $location Location of the parameter
*
* @return self
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get the sentAs attribute of the parameter that used with locations to sentAs an attribute when it is being
* applied to a location.
*
* @return string|null
*/
public function getSentAs()
{
return $this->sentAs;
}
/**
* Set the sentAs attribute
*
* @param string|null $name Name of the value as it is sent over the wire
*
* @return self
*/
public function setSentAs($name)
{
$this->sentAs = $name;
return $this;
}
/**
* Retrieve a known property from the parameter by name or a data property by name. When not specific name value
* is specified, all data properties will be returned.
*
* @param string|null $name Specify a particular property name to retrieve
*
* @return array|mixed|null
*/
public function getData($name = null)
{
if (!$name) {
return $this->data;
}
if (isset($this->data[$name])) {
return $this->data[$name];
} elseif (isset($this->{$name})) {
return $this->{$name};
}
return null;
}
/**
* Set the extra data properties of the parameter or set a specific extra property
*
* @param string|array|null $nameOrData The name of a specific extra to set or an array of extras to set
* @param mixed|null $data When setting a specific extra property, specify the data to set for it
*
* @return self
*/
public function setData($nameOrData, $data = null)
{
if (is_array($nameOrData)) {
$this->data = $nameOrData;
} else {
$this->data[$nameOrData] = $data;
}
return $this;
}
/**
* Get whether or not the default value can be changed
*
* @return mixed|null
*/
public function getStatic()
{
return $this->static;
}
/**
* Set to true if the default value cannot be changed
*
* @param bool $static True or false
*
* @return self
*/
public function setStatic($static)
{
$this->static = (bool) $static;
return $this;
}
/**
* Get an array of filters used by the parameter
*
* @return array
*/
public function getFilters()
{
return $this->filters ?: array();
}
/**
* Set the array of filters used by the parameter
*
* @param array $filters Array of functions to use as filters
*
* @return self
*/
public function setFilters(array $filters)
{
$this->filters = array();
foreach ($filters as $filter) {
$this->addFilter($filter);
}
return $this;
}
/**
* Add a filter to the parameter
*
* @param string|array $filter Method to filter the value through
*
* @return self
* @throws InvalidArgumentException
*/
public function addFilter($filter)
{
if (is_array($filter)) {
if (!isset($filter['method'])) {
throw new InvalidArgumentException('A [method] value must be specified for each complex filter');
}
}
if (!$this->filters) {
$this->filters = array($filter);
} else {
$this->filters[] = $filter;
}
return $this;
}
/**
* Get the parent object (an {@see OperationInterface} or {@see Parameter}
*
* @return OperationInterface|Parameter|null
*/
public function getParent()
{
return $this->parent;
}
/**
* Set the parent object of the parameter
*
* @param OperationInterface|Parameter|null $parent Parent container of the parameter
*
* @return self
*/
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
/**
* Get the properties of the parameter
*
* @return array
*/
public function getProperties()
{
if (!$this->propertiesCache) {
$this->propertiesCache = array();
foreach (array_keys($this->properties) as $name) {
$this->propertiesCache[$name] = $this->getProperty($name);
}
}
return $this->propertiesCache;
}
/**
* Get a specific property from the parameter
*
* @param string $name Name of the property to retrieve
*
* @return null|Parameter
*/
public function getProperty($name)
{
if (!isset($this->properties[$name])) {
return null;
}
if (!($this->properties[$name] instanceof self)) {
$this->properties[$name]['name'] = $name;
$this->properties[$name] = new static($this->properties[$name], $this->serviceDescription);
$this->properties[$name]->setParent($this);
}
return $this->properties[$name];
}
/**
* Remove a property from the parameter
*
* @param string $name Name of the property to remove
*
* @return self
*/
public function removeProperty($name)
{
unset($this->properties[$name]);
$this->propertiesCache = null;
return $this;
}
/**
* Add a property to the parameter
*
* @param Parameter $property Properties to set
*
* @return self
*/
public function addProperty(Parameter $property)
{
$this->properties[$property->getName()] = $property;
$property->setParent($this);
$this->propertiesCache = null;
return $this;
}
/**
* Get the additionalProperties value of the parameter
*
* @return bool|Parameter|null
*/
public function getAdditionalProperties()
{
if (is_array($this->additionalProperties)) {
$this->additionalProperties = new static($this->additionalProperties, $this->serviceDescription);
$this->additionalProperties->setParent($this);
}
return $this->additionalProperties;
}
/**
* Set the additionalProperties value of the parameter
*
* @param bool|Parameter|null $additional Boolean to allow any, an Parameter to specify a schema, or false to disallow
*
* @return self
*/
public function setAdditionalProperties($additional)
{
$this->additionalProperties = $additional;
return $this;
}
/**
* Set the items data of the parameter
*
* @param Parameter|null $items Items to set
*
* @return self
*/
public function setItems(Parameter $items = null)
{
if ($this->items = $items) {
$this->items->setParent($this);
}
return $this;
}
/**
* Get the item data of the parameter
*
* @return Parameter|null
*/
public function getItems()
{
if (is_array($this->items)) {
$this->items = new static($this->items, $this->serviceDescription);
$this->items->setParent($this);
}
return $this->items;
}
/**
* Get the class that the parameter must implement
*
* @return null|string
*/
public function getInstanceOf()
{
return $this->instanceOf;
}
/**
* Set the class that the parameter must be an instance of
*
* @param string|null $instanceOf Class or interface name
*
* @return self
*/
public function setInstanceOf($instanceOf)
{
$this->instanceOf = $instanceOf;
return $this;
}
/**
* Get the enum of strings that are valid for the parameter
*
* @return array|null
*/
public function getEnum()
{
return $this->enum;
}
/**
* Set the enum of strings that are valid for the parameter
*
* @param array|null $enum Array of strings or null
*
* @return self
*/
public function setEnum(array $enum = null)
{
$this->enum = $enum;
return $this;
}
/**
* Get the regex pattern that must match a value when the value is a string
*
* @return string
*/
public function getPattern()
{
return $this->pattern;
}
/**
* Set the regex pattern that must match a value when the value is a string
*
* @param string $pattern Regex pattern
*
* @return self
*/
public function setPattern($pattern)
{
$this->pattern = $pattern;
return $this;
}
/**
* Get the format attribute of the schema
*
* @return string
*/
public function getFormat()
{
return $this->format;
}
/**
* Set the format attribute of the schema
*
* @param string $format Format to set (e.g. date, date-time, timestamp, time, date-time-http)
*
* @return self
*/
public function setFormat($format)
{
$this->format = $format;
return $this;
}
}
Guzzle-3.7.0/Guzzle/Service/Description/SchemaFormatter.php 0000644 233176441610067500000007743 12155472567 025405 0 ustar dowling ANT\Domain Users setTimezone(self::getUtcTimeZone())->format($format);
}
throw new InvalidArgumentException('Date/Time values must be either a string, integer, or DateTime object');
}
}
Guzzle-3.7.0/Guzzle/Service/Description/SchemaValidator.php 0000644 233176441610067500000027107 12155472567 025363 0 ustar dowling ANT\Domain Users castIntegerToStringType = $castIntegerToStringType;
}
public function validate(Parameter $param, &$value)
{
$this->errors = array();
$this->recursiveProcess($param, $value);
if (empty($this->errors)) {
return true;
} else {
sort($this->errors);
return false;
}
}
/**
* Get the errors encountered while validating
*
* @return array
*/
public function getErrors()
{
return $this->errors ?: array();
}
/**
* Recursively validate a parameter
*
* @param Parameter $param API parameter being validated
* @param mixed $value Value to validate and validate. The value may change during this validate.
* @param string $path Current validation path (used for error reporting)
* @param int $depth Current depth in the validation validate
*
* @return bool Returns true if valid, or false if invalid
*/
protected function recursiveProcess(Parameter $param, &$value, $path = '', $depth = 0)
{
// Update the value by adding default or static values
$value = $param->getValue($value);
$required = $param->getRequired();
// if the value is null and the parameter is not required or is static, then skip any further recursion
if ((null === $value && !$required) || $param->getStatic()) {
return true;
}
$type = $param->getType();
// Attempt to limit the number of times is_array is called by tracking if the value is an array
$valueIsArray = is_array($value);
// If a name is set then update the path so that validation messages are more helpful
if ($name = $param->getName()) {
$path .= "[{$name}]";
}
if ($type == 'object') {
// Objects are either associative arrays, ToArrayInterface, or some other object
if ($param->getInstanceOf()) {
$instance = $param->getInstanceOf();
if (!($value instanceof $instance)) {
$this->errors[] = "{$path} must be an instance of {$instance}";
return false;
}
}
// Determine whether or not this "value" has properties and should be traversed
$traverse = $temporaryValue = false;
// Convert the value to an array
if (!$valueIsArray && $value instanceof ToArrayInterface) {
$value = $value->toArray();
}
if ($valueIsArray) {
// Ensure that the array is associative and not numerically indexed
if (isset($value[0])) {
$this->errors[] = "{$path} must be an array of properties. Got a numerically indexed array.";
return false;
}
$traverse = true;
} elseif ($value === null) {
// Attempt to let the contents be built up by default values if possible
$value = array();
$temporaryValue = $valueIsArray = $traverse = true;
}
if ($traverse) {
if ($properties = $param->getProperties()) {
// if properties were found, the validate each property of the value
foreach ($properties as $property) {
$name = $property->getName();
if (isset($value[$name])) {
$this->recursiveProcess($property, $value[$name], $path, $depth + 1);
} else {
$current = null;
$this->recursiveProcess($property, $current, $path, $depth + 1);
// Only set the value if it was populated with something
if ($current) {
$value[$name] = $current;
}
}
}
}
$additional = $param->getAdditionalProperties();
if ($additional !== true) {
// If additional properties were found, then validate each against the additionalProperties attr.
$keys = array_keys($value);
// Determine the keys that were specified that were not listed in the properties of the schema
$diff = array_diff($keys, array_keys($properties));
if (!empty($diff)) {
// Determine which keys are not in the properties
if ($additional instanceOf Parameter) {
foreach ($diff as $key) {
$this->recursiveProcess($additional, $value[$key], "{$path}[{$key}]", $depth);
}
} else {
// if additionalProperties is set to false and there are additionalProperties in the values, then fail
$keys = array_keys($value);
$this->errors[] = sprintf('%s[%s] is not an allowed property', $path, reset($keys));
}
}
}
// A temporary value will be used to traverse elements that have no corresponding input value.
// This allows nested required parameters with default values to bubble up into the input.
// Here we check if we used a temp value and nothing bubbled up, then we need to remote the value.
if ($temporaryValue && empty($value)) {
$value = null;
$valueIsArray = false;
}
}
} elseif ($type == 'array' && $valueIsArray && $param->getItems()) {
foreach ($value as $i => &$item) {
// Validate each item in an array against the items attribute of the schema
$this->recursiveProcess($param->getItems(), $item, $path . "[{$i}]", $depth + 1);
}
}
// If the value is required and the type is not null, then there is an error if the value is not set
if ($required && $value === null && $type != 'null') {
$message = "{$path} is " . ($param->getType() ? ('a required ' . implode(' or ', (array) $param->getType())) : 'required');
if ($param->getDescription()) {
$message .= ': ' . $param->getDescription();
}
$this->errors[] = $message;
return false;
}
// Validate that the type is correct. If the type is string but an integer was passed, the class can be
// instructed to cast the integer to a string to pass validation. This is the default behavior.
if ($type && (!$type = $this->determineType($type, $value))) {
if ($this->castIntegerToStringType && $param->getType() == 'string' && is_integer($value)) {
$value = (string) $value;
} else {
$this->errors[] = "{$path} must be of type " . implode(' or ', (array) $param->getType());
}
}
// Perform type specific validation for strings, arrays, and integers
if ($type == 'string') {
// Strings can have enums which are a list of predefined values
if (($enum = $param->getEnum()) && !in_array($value, $enum)) {
$this->errors[] = "{$path} must be one of " . implode(' or ', array_map(function ($s) {
return '"' . addslashes($s) . '"';
}, $enum));
}
// Strings can have a regex pattern that the value must match
if (($pattern = $param->getPattern()) && !preg_match($pattern, $value)) {
$this->errors[] = "{$path} must match the following regular expression: {$pattern}";
}
$strLen = null;
if ($min = $param->getMinLength()) {
$strLen = strlen($value);
if ($strLen < $min) {
$this->errors[] = "{$path} length must be greater than or equal to {$min}";
}
}
if ($max = $param->getMaxLength()) {
if (($strLen ?: strlen($value)) > $max) {
$this->errors[] = "{$path} length must be less than or equal to {$max}";
}
}
} elseif ($type == 'array') {
$size = null;
if ($min = $param->getMinItems()) {
$size = count($value);
if ($size < $min) {
$this->errors[] = "{$path} must contain {$min} or more elements";
}
}
if ($max = $param->getMaxItems()) {
if (($size ?: count($value)) > $max) {
$this->errors[] = "{$path} must contain {$max} or fewer elements";
}
}
} elseif ($type == 'integer' || $type == 'number' || $type == 'numeric') {
if (($min = $param->getMinimum()) && $value < $min) {
$this->errors[] = "{$path} must be greater than or equal to {$min}";
}
if (($max = $param->getMaximum()) && $value > $max) {
$this->errors[] = "{$path} must be less than or equal to {$max}";
}
}
return empty($this->errors);
}
/**
* From the allowable types, determine the type that the variable matches
*
* @param string $type Parameter type
* @param mixed $value Value to determine the type
*
* @return string|bool Returns the matching type on
*/
protected function determineType($type, $value)
{
foreach ((array) $type as $t) {
if ($t == 'string' && (is_string($value) || (is_object($value) && method_exists($value, '__toString')))) {
return 'string';
} elseif ($t == 'object' && (is_array($value) || is_object($value))) {
return 'object';
} elseif ($t == 'array' && is_array($value)) {
return 'array';
} elseif ($t == 'integer' && is_integer($value)) {
return 'integer';
} elseif ($t == 'boolean' && is_bool($value)) {
return 'boolean';
} elseif ($t == 'number' && is_numeric($value)) {
return 'number';
} elseif ($t == 'numeric' && is_numeric($value)) {
return 'numeric';
} elseif ($t == 'null' && !$value) {
return 'null';
} elseif ($t == 'any') {
return 'any';
}
}
return false;
}
}
Guzzle-3.7.0/Guzzle/Service/Description/ServiceDescription.php 0000644 233176441610067500000016214 12155472567 026116 0 ustar dowling ANT\Domain Users load($config, $options);
}
/**
* @param array $config Array of configuration data
*/
public function __construct(array $config = array())
{
$this->fromArray($config);
}
public function serialize()
{
return json_encode($this->toArray());
}
public function unserialize($json)
{
$this->operations = array();
$this->fromArray(json_decode($json, true));
}
public function toArray()
{
$result = array(
'name' => $this->name,
'apiVersion' => $this->apiVersion,
'baseUrl' => $this->baseUrl,
'description' => $this->description
) + $this->extraData;
$result['operations'] = array();
foreach ($this->getOperations() as $name => $operation) {
$result['operations'][$operation->getName() ?: $name] = $operation->toArray();
}
if (!empty($this->models)) {
$result['models'] = array();
foreach ($this->models as $id => $model) {
$result['models'][$id] = $model instanceof Parameter ? $model->toArray(): $model;
}
}
return array_filter($result);
}
public function getBaseUrl()
{
return $this->baseUrl;
}
/**
* Set the baseUrl of the description
*
* @param string $baseUrl Base URL of each operation
*
* @return self
*/
public function setBaseUrl($baseUrl)
{
$this->baseUrl = $baseUrl;
return $this;
}
public function getOperations()
{
foreach (array_keys($this->operations) as $name) {
$this->getOperation($name);
}
return $this->operations;
}
public function hasOperation($name)
{
return isset($this->operations[$name]);
}
public function getOperation($name)
{
// Lazily retrieve and build operations
if (!isset($this->operations[$name])) {
return null;
}
if (!($this->operations[$name] instanceof Operation)) {
$this->operations[$name] = new Operation($this->operations[$name], $this);
}
return $this->operations[$name];
}
/**
* Add a operation to the service description
*
* @param OperationInterface $operation Operation to add
*
* @return self
*/
public function addOperation(OperationInterface $operation)
{
$this->operations[$operation->getName()] = $operation->setServiceDescription($this);
return $this;
}
public function getModel($id)
{
if (!isset($this->models[$id])) {
return null;
}
if (!($this->models[$id] instanceof Parameter)) {
$this->models[$id] = new Parameter($this->models[$id] + array('name' => $id), $this);
}
return $this->models[$id];
}
public function getModels()
{
// Ensure all models are converted into parameter objects
foreach (array_keys($this->models) as $id) {
$this->getModel($id);
}
return $this->models;
}
public function hasModel($id)
{
return isset($this->models[$id]);
}
/**
* Add a model to the service description
*
* @param Parameter $model Model to add
*
* @return self
*/
public function addModel(Parameter $model)
{
$this->models[$model->getName()] = $model;
return $this;
}
public function getApiVersion()
{
return $this->apiVersion;
}
public function getName()
{
return $this->name;
}
public function getDescription()
{
return $this->description;
}
public function getData($key)
{
return isset($this->extraData[$key]) ? $this->extraData[$key] : null;
}
public function setData($key, $value)
{
$this->extraData[$key] = $value;
return $this;
}
/**
* Initialize the state from an array
*
* @param array $config Configuration data
* @throws InvalidArgumentException
*/
protected function fromArray(array $config)
{
// Keep a list of default keys used in service descriptions that is later used to determine extra data keys
static $defaultKeys = array('name', 'models', 'apiVersion', 'baseUrl', 'description');
// Pull in the default configuration values
foreach ($defaultKeys as $key) {
if (isset($config[$key])) {
$this->{$key} = $config[$key];
}
}
// Account for the Swagger name for Guzzle's baseUrl
if (isset($config['basePath'])) {
$this->baseUrl = $config['basePath'];
}
// Ensure that the models and operations properties are always arrays
$this->models = (array) $this->models;
$this->operations = (array) $this->operations;
// We want to add operations differently than adding the other properties
$defaultKeys[] = 'operations';
// Create operations for each operation
if (isset($config['operations'])) {
foreach ($config['operations'] as $name => $operation) {
if (!($operation instanceof Operation) && !is_array($operation)) {
throw new InvalidArgumentException('Invalid operation in service description: '
. gettype($operation));
}
$this->operations[$name] = $operation;
}
}
// Get all of the additional properties of the service description and store them in a data array
foreach (array_diff(array_keys($config), $defaultKeys) as $key) {
$this->extraData[$key] = $config[$key];
}
}
}
Guzzle-3.7.0/Guzzle/Service/Description/ServiceDescriptionInterface.php 0000644 233176441610067500000004261 12155472567 027736 0 ustar dowling ANT\Domain Users $op) {
$name = $op['name'] = isset($op['name']) ? $op['name'] : $name;
// Extend other operations
if (!empty($op['extends'])) {
$this->resolveExtension($name, $op, $operations);
}
$op['parameters'] = isset($op['parameters']) ? $op['parameters'] : array();
$operations[$name] = $op;
}
}
return new ServiceDescription(array(
'apiVersion' => isset($config['apiVersion']) ? $config['apiVersion'] : null,
'baseUrl' => isset($config['baseUrl']) ? $config['baseUrl'] : null,
'description' => isset($config['description']) ? $config['description'] : null,
'operations' => $operations,
'models' => isset($config['models']) ? $config['models'] : null
) + $config);
}
/**
* @param string $name Name of the operation
* @param array $op Operation value array
* @param array $operations Currently loaded operations
* @throws DescriptionBuilderException when extending a non-existent operation
*/
protected function resolveExtension($name, array &$op, array &$operations)
{
$resolved = array();
$original = empty($op['parameters']) ? false: $op['parameters'];
$hasClass = !empty($op['class']);
foreach ((array) $op['extends'] as $extendedCommand) {
if (empty($operations[$extendedCommand])) {
throw new DescriptionBuilderException("{$name} extends missing operation {$extendedCommand}");
}
$toArray = $operations[$extendedCommand];
$resolved = empty($resolved)
? $toArray['parameters']
: array_merge($resolved, $toArray['parameters']);
$op = $op + $toArray;
if (!$hasClass && isset($toArray['class'])) {
$op['class'] = $toArray['class'];
}
}
$op['parameters'] = $original ? array_merge($resolved, $original) : $resolved;
}
}
Guzzle-3.7.0/Guzzle/Service/Description/ValidatorInterface.php 0000644 233176441610067500000001721 12155472567 026055 0 ustar dowling ANT\Domain Users getMessage(), $e->getCode(), $e->getPrevious());
return $ce->setExceptions($e->getIterator()->getArrayCopy())
->setSuccessfulRequests($e->getSuccessfulRequests())
->setFailedRequests($e->getFailedRequests());
}
/**
* Get all of the commands in the transfer
*
* @return array
*/
public function getAllCommands()
{
return array_merge($this->successfulCommands, $this->failedCommands);
}
/**
* Add to the array of successful commands
*
* @param CommandInterface $command Successful command
*
* @return self
*/
public function addSuccessfulCommand(CommandInterface $command)
{
$this->successfulCommands[] = $command;
return $this;
}
/**
* Add to the array of failed commands
*
* @param CommandInterface $command Failed command
*
* @return self
*/
public function addFailedCommand(CommandInterface $command)
{
$this->failedCommands[] = $command;
return $this;
}
/**
* Get an array of successful commands
*
* @return array
*/
public function getSuccessfulCommands()
{
return $this->successfulCommands;
}
/**
* Get an array of failed commands
*
* @return array
*/
public function getFailedCommands()
{
return $this->failedCommands;
}
}
Guzzle-3.7.0/Guzzle/Service/Exception/DescriptionBuilderException.php 0000644 233176441610067500000000231 12155472567 027426 0 ustar dowling ANT\Domain Users invalidCommands = $commands;
parent::__construct(
'Encountered commands in a batch transfer that use inconsistent clients. The batching ' .
'strategy you use with a command transfer must divide command batches by client.'
);
}
/**
* Get the invalid commands
*
* @return array
*/
public function getCommands()
{
return $this->invalidCommands;
}
}
Guzzle-3.7.0/Guzzle/Service/Exception/ResponseClassException.php 0000644 233176441610067500000000225 12155472567 026423 0 ustar dowling ANT\Domain Users errors = $errors;
}
/**
* Get any validation errors
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
}
Guzzle-3.7.0/Guzzle/Service/Resource/AbstractResourceIteratorFactory.php 0000644 233176441610067500000002025 12155472567 030126 0 ustar dowling ANT\Domain Users canBuild($command)) {
throw new InvalidArgumentException('Iterator was not found for ' . $command->getName());
}
$className = $this->getClassName($command);
return new $className($command, $options);
}
public function canBuild(CommandInterface $command)
{
return (bool) $this->getClassName($command);
}
/**
* Get the name of the class to instantiate for the command
*
* @param CommandInterface $command Command that is associated with the iterator
*
* @return string
*/
abstract protected function getClassName(CommandInterface $command);
}
Guzzle-3.7.0/Guzzle/Service/Resource/CompositeResourceIteratorFactory.php 0000644 233176441610067500000003357 12155472567 030336 0 ustar dowling ANT\Domain Users factories = $factories;
}
public function build(CommandInterface $command, array $options = array())
{
if (!($factory = $this->getFactory($command))) {
throw new InvalidArgumentException('Iterator was not found for ' . $command->getName());
}
return $factory->build($command, $options);
}
public function canBuild(CommandInterface $command)
{
return $this->getFactory($command) !== false;
}
/**
* Add a factory to the composite factory
*
* @param ResourceIteratorFactoryInterface $factory Factory to add
*
* @return self
*/
public function addFactory(ResourceIteratorFactoryInterface $factory)
{
$this->factories[] = $factory;
return $this;
}
/**
* Get the factory that matches the command object
*
* @param CommandInterface $command Command retrieving the iterator for
*
* @return ResourceIteratorFactoryInterface|bool
*/
protected function getFactory(CommandInterface $command)
{
foreach ($this->factories as $factory) {
if ($factory->canBuild($command)) {
return $factory;
}
}
return false;
}
}
Guzzle-3.7.0/Guzzle/Service/Resource/MapResourceIteratorFactory.php 0000644 233176441610067500000001610 12155472567 027077 0 ustar dowling ANT\Domain Users map = $map;
}
public function getClassName(CommandInterface $command)
{
$className = $command->getName();
if (isset($this->map[$className])) {
return $this->map[$className];
} elseif (isset($this->map['*'])) {
// If a wildcard was added, then always use that
return $this->map['*'];
}
return null;
}
}
Guzzle-3.7.0/Guzzle/Service/Resource/Model.php 0000644 233176441610067500000003600 12155472567 022651 0 ustar dowling ANT\Domain Users data = $data;
$this->structure = $structure ?: new Parameter();
}
/**
* Get the structure of the model
*
* @return Parameter
*/
public function getStructure()
{
return $this->structure;
}
/**
* Provides debug information about the model object
*
* @return string
*/
public function __toString()
{
$output = 'Debug output of ' . ($this->structure->getName() ?: ' the model');
$output = str_repeat('=', strlen($output)) . "\n" . $output . "\n" . str_repeat('=', strlen($output)) . "\n\n";
$output .= "Model data\n-----------\n\n";
$output .= "This data can be retrieved from the model object using the get() method of the model "
. "(e.g. \$model->get(\$key)) or accessing the model like an associative array (e.g. \$model['key']).\n\n";
$lines = array_slice(explode("\n", trim(print_r($this->toArray(), true))), 2, -1);
$output .= implode("\n", $lines) . "\n\n";
$output .= "Model structure\n---------------\n\n";
$output .= "The following JSON document defines how the model was parsed from an HTTP response into the "
. "associative array strucure you see above.\n\n";
$output .= ' ' . json_encode($this->structure->toArray()) . "\n\n";
return $output;
}
}
Guzzle-3.7.0/Guzzle/Service/Resource/ResourceIterator.php 0000644 233176441610067500000016534 12155472567 025124 0 ustar dowling ANT\Domain Users originalCommand = $command;
// Parse options from the array of options
$this->data = $data;
$this->limit = array_key_exists('limit', $data) ? $data['limit'] : 0;
$this->pageSize = array_key_exists('page_size', $data) ? $data['page_size'] : false;
}
/**
* Get all of the resources as an array (Warning: this could issue a large number of requests)
*
* @return array
*/
public function toArray()
{
return iterator_to_array($this, false);
}
public function setLimit($limit)
{
$this->limit = $limit;
$this->resetState();
return $this;
}
public function setPageSize($pageSize)
{
$this->pageSize = $pageSize;
$this->resetState();
return $this;
}
/**
* Get an option from the iterator
*
* @param string $key Key of the option to retrieve
*
* @return mixed|null Returns NULL if not set or the value if set
*/
public function get($key)
{
return array_key_exists($key, $this->data) ? $this->data[$key] : null;
}
/**
* Set an option on the iterator
*
* @param string $key Key of the option to set
* @param mixed $value Value to set for the option
*
* @return ResourceIterator
*/
public function set($key, $value)
{
$this->data[$key] = $value;
return $this;
}
public function current()
{
return $this->resources ? current($this->resources) : false;
}
public function key()
{
return max(0, $this->iteratedCount - 1);
}
public function count()
{
return $this->retrievedCount;
}
/**
* Get the total number of requests sent
*
* @return int
*/
public function getRequestCount()
{
return $this->requestCount;
}
/**
* Rewind the Iterator to the first element and send the original command
*/
public function rewind()
{
// Use the original command
$this->command = clone $this->originalCommand;
$this->resetState();
$this->next();
}
public function valid()
{
return !$this->invalid && (!$this->resources || $this->current() || $this->nextToken)
&& (!$this->limit || $this->iteratedCount < $this->limit + 1);
}
public function next()
{
$this->iteratedCount++;
// Check if a new set of resources needs to be retrieved
$sendRequest = false;
if (!$this->resources) {
$sendRequest = true;
} else {
// iterate over the internal array
$current = next($this->resources);
$sendRequest = $current === false && $this->nextToken && (!$this->limit || $this->iteratedCount < $this->limit + 1);
}
if ($sendRequest) {
$this->dispatch('resource_iterator.before_send', array(
'iterator' => $this,
'resources' => $this->resources
));
// Get a new command object from the original command
$this->command = clone $this->originalCommand;
// Send a request and retrieve the newly loaded resources
$this->resources = $this->sendRequest();
$this->requestCount++;
// If no resources were found, then the last request was not needed
// and iteration must stop
if (empty($this->resources)) {
$this->invalid = true;
} else {
// Add to the number of retrieved resources
$this->retrievedCount += count($this->resources);
// Ensure that we rewind to the beginning of the array
reset($this->resources);
}
$this->dispatch('resource_iterator.after_send', array(
'iterator' => $this,
'resources' => $this->resources
));
}
}
/**
* Retrieve the NextToken that can be used in other iterators.
*
* @return string Returns a NextToken
*/
public function getNextToken()
{
return $this->nextToken;
}
/**
* Returns the value that should be specified for the page size for a request that will maintain any hard limits,
* but still honor the specified pageSize if the number of items retrieved + pageSize < hard limit
*
* @return int Returns the page size of the next request.
*/
protected function calculatePageSize()
{
if ($this->limit && $this->iteratedCount + $this->pageSize > $this->limit) {
return 1 + ($this->limit - $this->iteratedCount);
}
return (int) $this->pageSize;
}
/**
* Reset the internal state of the iterator without triggering a rewind()
*/
protected function resetState()
{
$this->iteratedCount = 0;
$this->retrievedCount = 0;
$this->nextToken = false;
$this->resources = null;
$this->invalid = false;
}
/**
* Send a request to retrieve the next page of results. Hook for subclasses to implement.
*
* @return array Returns the newly loaded resources
*/
abstract protected function sendRequest();
}
Guzzle-3.7.0/Guzzle/Service/Resource/ResourceIteratorApplyBatched.php 0000644 233176441610067500000006523 12155472567 027402 0 ustar dowling ANT\Domain Users iterator = $iterator;
$this->callback = $callback;
Version::warn(__CLASS__ . ' is deprecated');
}
/**
* Apply the callback to the contents of the resource iterator
*
* @param int $perBatch The number of records to group per batch transfer
*
* @return int Returns the number of iterated resources
*/
public function apply($perBatch = 50)
{
$this->iterated = $this->batches = $batches = 0;
$that = $this;
$it = $this->iterator;
$callback = $this->callback;
$batch = BatchBuilder::factory()
->createBatchesWith(new BatchSizeDivisor($perBatch))
->transferWith(new BatchClosureTransfer(function (array $batch) use ($that, $callback, &$batches, $it) {
$batches++;
$that->dispatch('iterator_batch.before_batch', array('iterator' => $it, 'batch' => $batch));
call_user_func_array($callback, array($it, $batch));
$that->dispatch('iterator_batch.after_batch', array('iterator' => $it, 'batch' => $batch));
}))
->autoFlushAt($perBatch)
->build();
$this->dispatch('iterator_batch.created_batch', array('batch' => $batch));
foreach ($this->iterator as $resource) {
$this->iterated++;
$batch->add($resource);
}
$batch->flush();
$this->batches = $batches;
return $this->iterated;
}
/**
* Get the total number of batches sent
*
* @return int
*/
public function getBatchCount()
{
return $this->batches;
}
/**
* Get the total number of iterated resources
*
* @return int
*/
public function getIteratedCount()
{
return $this->iterated;
}
}
Guzzle-3.7.0/Guzzle/Service/Resource/ResourceIteratorClassFactory.php 0000644 233176441610067500000003710 12155472567 027432 0 ustar dowling ANT\Domain Users AbcFoo).
*/
class ResourceIteratorClassFactory extends AbstractResourceIteratorFactory
{
/** @var array List of namespaces used to look for classes */
protected $namespaces;
/** @var InflectorInterface Inflector used to determine class names */
protected $inflector;
/**
* @param string|array $namespaces List of namespaces for iterator objects
* @param InflectorInterface $inflector Inflector used to resolve class names
*/
public function __construct($namespaces = array(), InflectorInterface $inflector = null)
{
$this->namespaces = (array) $namespaces;
$this->inflector = $inflector ?: Inflector::getDefault();
}
/**
* Registers a namespace to check for Iterators
*
* @param string $namespace Namespace which contains Iterator classes
*
* @return self
*/
public function registerNamespace($namespace)
{
array_unshift($this->namespaces, $namespace);
return $this;
}
protected function getClassName(CommandInterface $command)
{
$iteratorName = $this->inflector->camel($command->getName()) . 'Iterator';
// Determine the name of the class to load
foreach ($this->namespaces as $namespace) {
$potentialClassName = $namespace . '\\' . $iteratorName;
if (class_exists($potentialClassName)) {
return $potentialClassName;
}
}
return false;
}
}
Guzzle-3.7.0/Guzzle/Service/Resource/ResourceIteratorFactoryInterface.php 0000644 233176441610067500000001425 12155472567 030266 0 ustar dowling ANT\Domain Users contextOptions = stream_context_get_options($context);
$this->context = $context;
} elseif (is_array($context) || !$context) {
$this->contextOptions = $context;
$this->createContext($params);
} elseif ($context) {
throw new InvalidArgumentException('$context must be an array or resource');
}
$this->setUrl($request);
$this->addDefaultContextOptions($request);
$this->addSslOptions($request);
$this->addBodyOptions($request);
$this->addProxyOptions($request);
// Dispatch the before send event
$request->dispatch('request.before_send', array(
'request' => $request,
'context' => $this->context,
'context_options' => $this->contextOptions
));
// Create the file handle but silence errors
return $this->createStream($params)
->setCustomData('request', $request)
->setCustomData('response_headers', $this->getLastResponseHeaders());
}
/**
* Set an option on the context and the internal options array
*
* @param string $wrapper Stream wrapper name of http
* @param string $name Context name
* @param mixed $value Context value
* @param bool $overwrite Set to true to overwrite an existing value
*/
protected function setContextValue($wrapper, $name, $value, $overwrite = false)
{
if (!isset($this->contextOptions[$wrapper])) {
$this->contextOptions[$wrapper] = array($name => $value);
} elseif (!$overwrite && isset($this->contextOptions[$wrapper][$name])) {
return;
}
$this->contextOptions[$wrapper][$name] = $value;
stream_context_set_option($this->context, $wrapper, $name, $value);
}
/**
* Create a stream context
*
* @param array $params Parameter array
*/
protected function createContext(array $params)
{
$options = $this->contextOptions;
$this->context = $this->createResource(function () use ($params, $options) {
return stream_context_create($options, $params);
});
}
/**
* Get the last response headers received by the HTTP request
*
* @return array
*/
public function getLastResponseHeaders()
{
return $this->lastResponseHeaders;
}
/**
* Adds the default context options to the stream context options
*
* @param RequestInterface $request Request
*/
protected function addDefaultContextOptions(RequestInterface $request)
{
$this->setContextValue('http', 'method', $request->getMethod());
$this->setContextValue('http', 'header', $request->getHeaderLines());
// Force 1.0 for now until PHP fully support chunked transfer-encoding decoding
$this->setContextValue('http', 'protocol_version', '1.0');
$this->setContextValue('http', 'ignore_errors', true);
}
/**
* Set the URL to use with the factory
*
* @param RequestInterface $request Request that owns the URL
*/
protected function setUrl(RequestInterface $request)
{
$this->url = $request->getUrl(true);
// Check for basic Auth username
if ($request->getUsername()) {
$this->url->setUsername($request->getUsername());
}
// Check for basic Auth password
if ($request->getPassword()) {
$this->url->setPassword($request->getPassword());
}
}
/**
* Add SSL options to the stream context
*
* @param RequestInterface $request Request
*/
protected function addSslOptions(RequestInterface $request)
{
if ($verify = $request->getCurlOptions()->get(CURLOPT_SSL_VERIFYPEER)) {
$this->setContextValue('ssl', 'verify_peer', true, true);
if ($cafile = $request->getCurlOptions()->get(CURLOPT_CAINFO)) {
$this->setContextValue('ssl', 'cafile', $cafile, true);
}
} else {
$this->setContextValue('ssl', 'verify_peer', false, true);
}
}
/**
* Add body (content) specific options to the context options
*
* @param RequestInterface $request
*/
protected function addBodyOptions(RequestInterface $request)
{
// Add the content for the request if needed
if (!($request instanceof EntityEnclosingRequestInterface)) {
return;
}
if (count($request->getPostFields())) {
$this->setContextValue('http', 'content', (string) $request->getPostFields(), true);
} elseif ($request->getBody()) {
$this->setContextValue('http', 'content', (string) $request->getBody(), true);
}
// Always ensure a content-length header is sent
if (isset($this->contextOptions['http']['content'])) {
$headers = isset($this->contextOptions['http']['header']) ? $this->contextOptions['http']['header'] : array();
$headers[] = 'Content-Length: ' . strlen($this->contextOptions['http']['content']);
$this->setContextValue('http', 'header', $headers, true);
}
}
/**
* Add proxy parameters to the context if needed
*
* @param RequestInterface $request Request
*/
protected function addProxyOptions(RequestInterface $request)
{
if ($proxy = $request->getCurlOptions()->get(CURLOPT_PROXY)) {
$this->setContextValue('http', 'proxy', $proxy);
}
}
/**
* Create the stream for the request with the context options
*
* @param array $params Parameters of the stream
*
* @return StreamInterface
*/
protected function createStream(array $params)
{
$http_response_header = null;
$url = $this->url;
$context = $this->context;
$fp = $this->createResource(function () use ($context, $url, &$http_response_header) {
return fopen((string) $url, 'r', false, $context);
});
// Determine the class to instantiate
$className = isset($params['stream_class']) ? $params['stream_class'] : __NAMESPACE__ . '\\Stream';
/** @var $stream StreamInterface */
$stream = new $className($fp);
// Track the response headers of the request
if (isset($http_response_header)) {
$this->lastResponseHeaders = $http_response_header;
$this->processResponseHeaders($stream);
}
return $stream;
}
/**
* Process response headers
*
* @param StreamInterface $stream
*/
protected function processResponseHeaders(StreamInterface $stream)
{
// Set the size on the stream if it was returned in the response
foreach ($this->lastResponseHeaders as $header) {
if (($pos = stripos($header, 'Content-Length:')) === 0) {
$stream->setSize(trim(substr($header, 15)));
}
}
}
/**
* Create a resource and check to ensure it was created successfully
*
* @param callable $callback Closure to invoke that must return a valid resource
*
* @return resource
* @throws RuntimeException on error
*/
protected function createResource($callback)
{
// Turn off error reporting while we try to initiate the request
$level = error_reporting(0);
$resource = call_user_func($callback);
error_reporting($level);
// If the resource could not be created, then grab the last error and throw an exception
if (false === $resource) {
$message = 'Error creating resource. ';
foreach (error_get_last() as $key => $value) {
$message .= "[{$key}] {$value} ";
}
throw new RuntimeException(trim($message));
}
return $resource;
}
}
Guzzle-3.7.0/Guzzle/Stream/Stream.php 0000644 233176441610067500000016656 12155472567 021127 0 ustar dowling ANT\Domain Users array(
'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' => array(
'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
)
);
/**
* @param resource $stream Stream resource to wrap
* @param int $size Size of the stream in bytes. Only pass if the size cannot be obtained from the stream.
*
* @throws InvalidArgumentException if the stream is not a stream resource
*/
public function __construct($stream, $size = null)
{
$this->setStream($stream, $size);
}
/**
* Closes the stream when the helper is destructed
*/
public function __destruct()
{
$this->close();
}
public function __toString()
{
if (!$this->isReadable() || (!$this->isSeekable() && $this->isConsumed())) {
return '';
}
$originalPos = $this->ftell();
$body = stream_get_contents($this->stream, -1, 0);
$this->seek($originalPos);
return $body;
}
public function close()
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
$this->cache[self::IS_READABLE] = false;
$this->cache[self::IS_WRITABLE] = false;
}
/**
* 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 bool|string Returns false on failure or a hash string on success
*/
public static function getHash(StreamInterface $stream, $algo, $rawOutput = false)
{
$pos = $stream->ftell();
if (!$stream->seek(0)) {
return false;
}
$ctx = hash_init($algo);
while ($data = $stream->read(8192)) {
hash_update($ctx, $data);
}
$out = hash_final($ctx, (bool) $rawOutput);
$stream->seek($pos);
return $out;
}
public function getMetaData($key = null)
{
$meta = stream_get_meta_data($this->stream);
return !$key ? $meta : (array_key_exists($key, $meta) ? $meta[$key] : null);
}
public function getStream()
{
return $this->stream;
}
public function setStream($stream, $size = null)
{
if (!is_resource($stream)) {
throw new InvalidArgumentException('Stream must be a resource');
}
$this->size = $size;
$this->stream = $stream;
$this->rebuildCache();
return $this;
}
public function detachStream()
{
$this->stream = null;
return $this;
}
public function getWrapper()
{
return $this->cache[self::WRAPPER_TYPE];
}
public function getWrapperData()
{
return $this->getMetaData('wrapper_data') ?: array();
}
public function getStreamType()
{
return $this->cache[self::STREAM_TYPE];
}
public function getUri()
{
return $this->cache['uri'];
}
public function getSize()
{
if ($this->size !== null) {
return $this->size;
}
// If the stream is a file based stream and local, then use fstat
clearstatcache(true, $this->cache['uri']);
$stats = fstat($this->stream);
if (isset($stats['size'])) {
$this->size = $stats['size'];
return $this->size;
} elseif ($this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE]) {
// Only get the size based on the content if the the stream is readable and seekable
$pos = $this->ftell();
$this->size = strlen((string) $this);
$this->seek($pos);
return $this->size;
}
return false;
}
public function isReadable()
{
return $this->cache[self::IS_READABLE];
}
public function isRepeatable()
{
return $this->cache[self::IS_READABLE] && $this->cache[self::SEEKABLE];
}
public function isWritable()
{
return $this->cache[self::IS_WRITABLE];
}
public function isConsumed()
{
return feof($this->stream);
}
public function feof()
{
return $this->isConsumed();
}
public function isLocal()
{
return $this->cache[self::IS_LOCAL];
}
public function isSeekable()
{
return $this->cache[self::SEEKABLE];
}
public function setSize($size)
{
$this->size = $size;
return $this;
}
public function seek($offset, $whence = SEEK_SET)
{
return $this->cache[self::SEEKABLE] ? fseek($this->stream, $offset, $whence) === 0 : false;
}
public function read($length)
{
return $this->cache[self::IS_READABLE] ? fread($this->stream, $length) : false;
}
public function write($string)
{
if (!$this->cache[self::IS_WRITABLE]) {
return 0;
}
$bytes = fwrite($this->stream, $string);
// We can't know the size after writing anything
$this->size = null;
return $bytes;
}
public function ftell()
{
return ftell($this->stream);
}
public function rewind()
{
return $this->seek(0);
}
public function readLine($maxLength = null)
{
if (!$this->cache[self::IS_READABLE]) {
return false;
} else {
return $maxLength ? fgets($this->getStream(), $maxLength) : fgets($this->getStream());
}
}
public function setCustomData($key, $value)
{
$this->customData[$key] = $value;
return $this;
}
public function getCustomData($key)
{
return isset($this->customData[$key]) ? $this->customData[$key] : null;
}
/**
* Reprocess stream metadata
*/
protected function rebuildCache()
{
$this->cache = stream_get_meta_data($this->stream);
$this->cache[self::IS_LOCAL] = stream_is_local($this->stream);
$this->cache[self::IS_READABLE] = isset(self::$readWriteHash['read'][$this->cache['mode']]);
$this->cache[self::IS_WRITABLE] = isset(self::$readWriteHash['write'][$this->cache['mode']]);
}
}
Guzzle-3.7.0/Guzzle/Stream/StreamInterface.php 0000644 233176441610067500000011070 12155472567 022731 0 ustar dowling ANT\Domain Users