1
0
mirror of https://github.com/guzzle/guzzle.git synced 2025-02-12 11:30:49 +01:00

Moving the option application to RequestFactoryInterface. Adding options parameters to client HTTP methods and createRequest.

This commit is contained in:
Michael Dowling 2013-06-02 15:54:43 -07:00
parent c921334368
commit 158f956a52
9 changed files with 343 additions and 516 deletions

View File

@ -53,8 +53,7 @@
"psr-0": {
"Guzzle\\Tests": "tests/",
"Guzzle": "src/"
},
"files": ["src/Guzzle/Guzzle.php"]
}
},
"require-dev": {

View File

@ -1,190 +0,0 @@
<?php
use Guzzle\Http\Client;
use Guzzle\Http\RedirectPlugin;
use Guzzle\Stream\StreamRequestFactoryInterface;
use Guzzle\Stream\PhpStreamRequestFactory;
/**
* Simplified interface to Guzzle that does not require a class to be instantiated
*/
final class Guzzle
{
/**
* @var Client Guzzle client
*/
private static $client;
/**
* @param string $method HTTP request method (GET, POST, HEAD, DELETE, PUT, etc)
* @param string $url URL of the request
* @param array $options Options to use with the request. Available options are:
* "headers": Associative array of headers
* "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.
* "allow_redirects": Set to false to disable redirects
* "auth": Basic auth array where index 0 is the username and index 1 is the password
* "query": Associative array of query string values to add to the request
* "cookies": Associative array of cookies
* "curl": Associative array of CURL options to add to the request
* "events": Associative array mapping event names to callables
* "stream": Set to true to retrieve a Guzzle\Stream\Stream object instead of a response
* "plugins": Array of plugins to add to the request
*
* @return \Guzzle\Http\Message\Response|\Guzzle\Stream\Stream
*/
public static function request($method, $url, $options = array())
{
if (!self::$client) {
self::$client = new Client();
}
// Extract parameters from the config array
$headers = $body = $curl = $auth = $events = $plugins = $allow_redirects = $cookies = $query = $stream = null;
extract($options, EXTR_IF_EXISTS);
$request = self::$client->createRequest($method, $url, $headers, $body);
if ($allow_redirects === false) {
$request->getParams()->set(RedirectPlugin::DISABLE, true);
}
if (is_array($cookies)) {
foreach ($cookies as $name => $value) {
$request->addCookie($name, $value);
}
}
if (is_array($query)) {
$request->getQuery()->overwriteWith($query);
}
if (is_array($curl)) {
$request->getCurlOptions()->overwriteWith($curl);
}
if (is_array($auth)) {
$request->setAuth($auth[0], isset($auth[1]) ? $auth[1] : null);
}
if (is_array($events)) {
foreach ($events as $name => $method) {
$request->getEventDispatcher()->addListener($name, $method);
}
}
if (is_array($plugins)) {
foreach ($plugins as $plugin) {
$request->addSubscriber($plugin);
}
}
if (!$stream) {
return $request->send();
} elseif ($stream instanceof StreamRequestFactoryInterface) {
return $stream->fromRequest($request);
} else {
$streamFactory = new PhpStreamRequestFactory();
return $streamFactory->fromRequest($request);
}
}
/**
* 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);
}
}

View File

@ -57,6 +57,8 @@ class Client extends AbstractHasDispatcher implements ClientInterface
/**
* @param string $baseUrl Base URL of the web service
* @param array|Collection $config Configuration settings
*
* @throws RuntimeException if cURL is not installed
*/
public function __construct($baseUrl = '', $config = null)
{
@ -69,8 +71,8 @@ class Client extends AbstractHasDispatcher implements ClientInterface
$this->defaultHeaders = new Collection();
$this->setRequestFactory(RequestFactory::getInstance());
// Redirect by default, but allow for redirects to be globally disabled on a client
if (!$this->config->get(self::DISABLE_REDIRECTS)) {
// Redirect by default, but allow for redire4cts to be globally disabled on a client
if (!$this->config[self::DISABLE_REDIRECTS]) {
$this->addSubscriber(new RedirectPlugin());
}
@ -96,12 +98,12 @@ class Client extends AbstractHasDispatcher implements ClientInterface
final public function getConfig($key = false)
{
return $key ? $this->config->get($key) : $this->config;
return $key ? $this->config[$key] : $this->config;
}
final public function setSslVerification($certificateAuthority = true, $verifyPeer = true, $verifyHost = 2)
{
$opts = $this->config->get(self::CURL_OPTIONS) ?: array();
$opts = $this->config[self::CURL_OPTIONS] ?: array();
if ($certificateAuthority === true) {
// use bundled CA bundle, set secure defaults
@ -193,44 +195,43 @@ class Client extends AbstractHasDispatcher implements ClientInterface
return $this->uriTemplate;
}
public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null)
public function createRequest($method = 'GET', $uri = null, $headers = null, $body = null, array $options = array())
{
if (!is_array($uri)) {
$templateVars = null;
} else {
if (count($uri) != 2 || !isset($uri[1]) || !is_array($uri[1])) {
throw new InvalidArgumentException(
'You must provide a URI template followed by an array of template variables '
. 'when using an array for a URI template'
);
}
list($uri, $templateVars) = $uri;
}
if (!$uri) {
$url = $this->getBaseUrl();
} elseif (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 (!is_array($uri)) {
$templateVars = null;
} else {
if (count($uri) != 2 || !isset($uri[1]) || !is_array($uri[1])) {
throw new InvalidArgumentException(
'You must provide a URI template followed by an array of template variables '
. 'when using an array for a URI template'
);
}
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 into existing headers
// If a collision occurs, the header is completely replaced
if (count($this->defaultHeaders)) {
if (is_array($headers)) {
$headers = array_merge($this->defaultHeaders->getAll(), $headers);
$headers = array_merge($this->defaultHeaders->toArray(), $headers);
} elseif ($headers instanceof Collection) {
$headers = array_merge($this->defaultHeaders->getAll(), $headers->getAll());
$headers = array_merge($this->defaultHeaders->toArray(), $headers->toArray());
} else {
$headers = $this->defaultHeaders;
}
}
return $this->prepareRequest(
$this->requestFactory->create($method, (string) $url, $headers, $body)
);
return $this->prepareRequest($this->requestFactory->create($method, (string) $url, $headers, $body), $options);
}
public function getBaseUrl($expand = true)
@ -267,39 +268,39 @@ class Client extends AbstractHasDispatcher implements ClientInterface
. ' PHP/' . PHP_VERSION;
}
public function get($uri = null, $headers = null, $body = null)
public function get($uri = null, $headers = null, $saveTo = null, array $options = array())
{
return $this->createRequest('GET', $uri, $headers, $body);
return $this->createRequest('GET', $uri, $headers, $saveTo, $options);
}
public function head($uri = null, $headers = null)
public function head($uri = null, $headers = null, array $options = array())
{
return $this->createRequest('HEAD', $uri, $headers);
return $this->createRequest('HEAD', $uri, $headers, $options);
}
public function delete($uri = null, $headers = null, $body = null)
public function delete($uri = null, $headers = null, $body = null, array $options = array())
{
return $this->createRequest('DELETE', $uri, $headers, $body);
return $this->createRequest('DELETE', $uri, $headers, $body, $options);
}
public function put($uri = null, $headers = null, $body = null)
public function put($uri = null, $headers = null, $body = null, array $options = array())
{
return $this->createRequest('PUT', $uri, $headers, $body);
return $this->createRequest('PUT', $uri, $headers, $body, $options);
}
public function patch($uri = null, $headers = null, $body = null)
public function patch($uri = null, $headers = null, $body = null, array $options = array())
{
return $this->createRequest('PATCH', $uri, $headers, $body);
return $this->createRequest('PATCH', $uri, $headers, $body, $options);
}
public function post($uri = null, $headers = null, $postBody = null)
public function post($uri = null, $headers = null, $postBody = null, array $options = array())
{
return $this->createRequest('POST', $uri, $headers, $postBody);
return $this->createRequest('POST', $uri, $headers, $postBody, $options);
}
public function options($uri = null)
public function options($uri = null, array $options = array())
{
return $this->createRequest('OPTIONS', $uri);
return $this->createRequest('OPTIONS', $uri, $options);
}
public function send($requests)
@ -386,21 +387,22 @@ class Client extends AbstractHasDispatcher implements ClientInterface
* 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)
protected function prepareRequest(RequestInterface $request, array $options = array())
{
$request->setClient($this);
// Add any curl options to the request
if ($options = $this->config->get(self::CURL_OPTIONS)) {
$request->getCurlOptions()->merge(CurlHandle::parseCurlConfig($options));
if ($curl = $this->config[self::CURL_OPTIONS]) {
$request->getCurlOptions()->overwriteWith(CurlHandle::parseCurlConfig($curl));
}
// Add request parameters to the request
if ($options = $this->config->get(self::REQUEST_PARAMS)) {
$request->getParams()->merge($options);
if ($params = $this->config[self::REQUEST_PARAMS]) {
$request->getParams()->overwriteWith($params);
}
// Attach client observers to the request
@ -411,13 +413,11 @@ class Client extends AbstractHasDispatcher implements ClientInterface
$request->setHeader('User-Agent', $this->userAgent);
}
$this->dispatch(
'client.create_request',
array(
'client' => $this,
'request' => $request
)
);
if ($options) {
$this->requestFactory->applyOptions($request, $options);
}
$this->dispatch('client.create_request', array('client' => $this, 'request' => $request));
return $request;
}
@ -428,7 +428,7 @@ class Client extends AbstractHasDispatcher implements ClientInterface
protected function initSsl()
{
// Allow ssl.certificate_authority config setting to control the certificate authority used by curl
$authority = $this->config->get(self::SSL_CERT_AUTHORITY);
$authority = $this->config[self::SSL_CERT_AUTHORITY];
// Set the SSL certificate
if ($authority !== 'system') {

View File

@ -100,12 +100,19 @@ interface ClientInterface extends HasDispatcherInterface
* @param string|array $uri Resource URI.
* @param array|Collection $headers HTTP headers
* @param string|resource|array|EntityBodyInterface $body Entity body of request (POST/PUT) or response (GET)
* @param array $options Array of options to apply to the request
*
* @return RequestInterface
* @throws InvalidArgumentException if a URI array is passed that does not contain exactly two elements: the URI
* followed by template variables
*/
public function createRequest($method = RequestInterface::GET, $uri = null, $headers = null, $body = null);
public function createRequest(
$method = RequestInterface::GET,
$uri = null,
$headers = null,
$body = null,
array $options = array()
);
/**
* Get the client's base URL as either an expanded or raw URI template
@ -140,35 +147,38 @@ interface ClientInterface extends HasDispatcherInterface
*
* @param string|array $uri Resource URI
* @param array|Collection $headers HTTP headers
* @param string|resource|array|EntityBodyInterface $body Where to store the response entity body
* @param string|resource|array|EntityBodyInterface $saveTo Where to store the response entity body
* @param array $options Options to apply to the request
*
* @return RequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function get($uri = null, $headers = null, $body = null);
public function get($uri = null, $headers = null, $saveTo = null, array $options = array());
/**
* Create a HEAD request for the client
*
* @param string|array $uri Resource URI
* @param array|Collection $headers HTTP headers
* @param array $options Options to apply to the request
*
* @return RequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function head($uri = null, $headers = null);
public function head($uri = null, $headers = null, array $options = array());
/**
* Create a DELETE request for the client
*
* @param string|array $uri Resource URI
* @param array|Collection $headers HTTP headers
* @param string|array $uri Resource URI
* @param array|Collection $headers HTTP headers
* @param string|resource|EntityBodyInterface $body Body to send in the request
* @param array $options Options to apply to the request
*
* @return EntityEnclosingRequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function delete($uri = null, $headers = null, $body = null);
public function delete($uri = null, $headers = null, $body = null, array $options = array());
/**
* Create a PUT request for the client
@ -176,11 +186,12 @@ interface ClientInterface extends HasDispatcherInterface
* @param string|array $uri Resource URI
* @param array|Collection $headers HTTP headers
* @param string|resource|EntityBodyInterface $body Body to send in the request
* @param array $options Options to apply to the request
*
* @return EntityEnclosingRequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function put($uri = null, $headers = null, $body = null);
public function put($uri = null, $headers = null, $body = null, array $options = array());
/**
* Create a PATCH request for the client
@ -188,11 +199,12 @@ interface ClientInterface extends HasDispatcherInterface
* @param string|array $uri Resource URI
* @param array|Collection $headers HTTP headers
* @param string|resource|EntityBodyInterface $body Body to send in the request
* @param array $options Options to apply to the request
*
* @return EntityEnclosingRequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function patch($uri = null, $headers = null, $body = null);
public function patch($uri = null, $headers = null, $body = null, array $options = array());
/**
* Create a POST request for the client
@ -203,20 +215,23 @@ interface ClientInterface extends HasDispatcherInterface
* associative array of POST fields to send in the body of the
* request. Prefix a value in the array with the @ symbol to
* reference a file.
* @param array $options Options to apply to the request
*
* @return EntityEnclosingRequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function post($uri = null, $headers = null, $postBody = null);
public function post($uri = null, $headers = null, $postBody = null, array $options = array());
/**
* Create an OPTIONS request for the client
*
* @param string|array $uri Resource URI
* @param string|array $uri Resource URI
* @param array $options Options to apply to the request
*
* @return RequestInterface
* @see Guzzle\Http\ClientInterface::createRequest()
*/
public function options($uri = null);
public function options($uri = null, array $options = array());
/**
* Sends a single request or an array of requests in parallel

View File

@ -3,8 +3,11 @@
namespace Guzzle\Http\Message;
use Guzzle\Common\Collection;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Url;
use Guzzle\Parser\ParserRegistry;
use Guzzle\Plugin\Log\LogPlugin;
use Guzzle\Http\RedirectPlugin;
/**
* Default HTTP request factory used to create the default {@see Request} and {@see EntityEnclosingRequest} objects.
@ -70,7 +73,7 @@ class RequestFactory implements RequestFactoryInterface
->setProtocolVersion($protocolVersion);
}
public function create($method, $url, $headers = null, $body = null)
public function create($method, $url, $headers = null, $body = null, array $options = array())
{
$method = strtoupper($method);
@ -84,33 +87,35 @@ class RequestFactory implements RequestFactoryInterface
$request->setResponseBody($body);
}
}
return $request;
}
// 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]);
} 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');
}
}
// 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;
}
@ -145,4 +150,135 @@ class RequestFactory implements RequestFactoryInterface
return $cloned;
}
public function applyOptions(RequestInterface $request, array $options = array())
{
$methods = get_class_methods(__CLASS__);
// Iterate over each key value pair and attempt to apply a config using function visitors
foreach ($options as $key => $value) {
$method = "visit_{$key}";
if (in_array($method, $methods)) {
$this->{$method}($request, $value);
}
}
}
protected function visit_headers(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('headers value must be an array');
}
$request->addHeaders($value);
}
protected function visit_body(RequestInterface $request, $value)
{
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)
{
if ($value === false) {
$request->getParams()->set(RedirectPlugin::DISABLE, true);
}
}
protected function visit_auth(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('auth value must be an array');
}
$request->setAuth($value[0], isset($value[1]) ? $value[1] : null);
}
protected function visit_query(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('query value must be an array');
}
$request->getQuery()->overwriteWith($value);
}
protected function visit_cookies(RequestInterface $request, $value)
{
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_curl(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('curl value must be an array');
}
$request->getCurlOptions()->replace($value);
}
protected function visit_timeout(RequestInterface $request, $value)
{
$request->getCurlOptions()->set(CURLOPT_TIMEOUT_MS, $value * 1000);
}
protected function visit_debug(RequestInterface $request, $value)
{
if (class_exists('Guzzle\Plugin\Log\LogPlugin')) {
$request->addSubscriber(LogPlugin::getDebugPlugin());
} else {
$request->getCurlOptions()->set(CURLOPT_VERBOSE, true);
}
}
protected function visit_events(RequestInterface $request, $value)
{
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[1], $method[0]);
} else {
$request->getEventDispatcher()->addListener($name, $method);
}
}
}
protected function visit_plugins(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('plugins value must be an array');
}
foreach ($value as $plugin) {
$request->addSubscriber($plugin);
}
}
protected function visit_verify(RequestInterface $request, $value)
{
$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;
}
}
}

View File

@ -56,8 +56,31 @@ interface RequestFactoryInterface
* @param string|Url $url HTTP URL to connect to
* @param array|Collection $headers HTTP headers
* @param string|resource|array|EntityBodyInterface $body Body to send in the request
* @param array $options Array of options to apply to the request
*
* @return RequestInterface
*/
public function create($method, $url, $headers = null, $body = null);
public function create($method, $url, $headers = null, $body = null, array $options = array());
/**
* Apply an associative array of options to the request
*
* @param RequestInterface $request Request to update
* @param array $options Options to use with the request. Available options are:
* "headers": Associative array of headers
* "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.
* "allow_redirects": Set to false to disable redirects
* "auth": Basic auth array where index 0 is the username and index 1 is the password
* "query": Associative array of query string values to add to the request
* "cookies": Associative array of cookies
* "timeout": Float describing the timeout of the request in seconds
* "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.
* "curl": Associative array of CURL options to add to the request
* "events": Associative array mapping event names to a closure or array of (priority, closure)
* "plugins": Array of plugins to add to the request
* "debug": Set to true to display all data sent over the wire
*/
public function applyOptions(RequestInterface $request, array $options = array());
}

View File

@ -2,11 +2,8 @@
namespace Guzzle\Http;
use Guzzle\Common\Exception\InvalidArgumentException;
use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Stream\StreamRequestFactoryInterface;
use Guzzle\Stream\PhpStreamRequestFactory;
@ -15,9 +12,7 @@ use Guzzle\Stream\PhpStreamRequestFactory;
*/
final class StaticClient
{
/**
* @var Client Guzzle client
*/
/** @var Client Guzzle client */
private static $client;
/**
@ -37,20 +32,7 @@ final class StaticClient
/**
* @param string $method HTTP request method (GET, POST, HEAD, DELETE, PUT, etc)
* @param string $url URL of the request
* @param array $options Options to use with the request. Available options are:
* "headers": Associative array of headers
* "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.
* "allow_redirects": Set to false to disable redirects
* "auth": Basic auth array where index 0 is the username and index 1 is the password
* "query": Associative array of query string values to add to the request
* "cookies": Associative array of cookies
* "curl": Associative array of CURL options to add to the request
* "events": Associative array mapping event names to callables
* "stream": Set to true to retrieve a Guzzle\Stream\Stream object instead of a response
* "plugins": Array of plugins to add to the request
*
* @param array $options Options to use with the request. See: Guzzle\Http\Message\RequestFactory::applyOptions()
* @return \Guzzle\Http\Message\Response|\Guzzle\Stream\Stream
*/
public static function request($method, $url, $options = array())
@ -59,23 +41,18 @@ final class StaticClient
self::$client = new Client();
}
$request = self::$client->createRequest($method, $url);
$returnValue = null;
$request = self::$client->createRequest($method, $url, null, null, $options);
// Iterate over each key value pair and attempt to apply a config using function visitors
foreach ($options as $key => $value) {
$method = __CLASS__ . '::visit_' . $key;
if (function_exists($method)) {
$result = call_user_func($method, $request, $value);
if ($result !== null) {
$returnValue = $result;
}
} else {
die('aaa' . $method);
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 $returnValue ?: $request->send();
return $request->send();
}
/**
@ -175,99 +152,4 @@ final class StaticClient
{
return self::request('OPTIONS', $url, $options);
}
private static function visit_headers(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('headers value must be an array');
}
$request->addHeaders($value);
}
private static function visit_body(RequestInterface $request, $value)
{
if ($request instanceof EntityEnclosingRequestInterface) {
$request->setBody($value);
} else {
throw new InvalidArgumentException('Attempting to set a body on a non-entity-enclosing request');
}
}
private static function visit_allow_redirects(RequestInterface $request, $value)
{
if ($value === false) {
$request->getParams()->set(RedirectPlugin::DISABLE, true);
}
}
private static function visit_auth(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('auth value must be an array');
}
$request->setAuth($value[0], isset($value[1]) ? $value[1] : null);
}
private static function visit_query(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('query value must be an array');
}
$request->getQuery()->overwriteWith($value);
}
private static function visit_cookies(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('cookies value must be an array');
}
foreach ($value as $name => $v) {
$request->addCookie($name, $v);
}
}
private static function visit_curl(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('curl value must be an array');
}
$request->getCurlOptions()->overwriteWith($value);
}
private static function visit_events(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('events value must be an array');
}
foreach ($value as $name => $method) {
$request->getEventDispatcher()->addListener($name, $method);
}
}
private static function visit_stream(RequestInterface $request, $value)
{
if ($value instanceof StreamRequestFactoryInterface) {
return $value->fromRequest($request);
} elseif ($value == true) {
$streamFactory = new PhpStreamRequestFactory();
return $streamFactory->fromRequest($request);
}
}
private static function visit_plugins(RequestInterface $request, $value)
{
if (!is_array($value)) {
throw new InvalidArgumentException('plugins value must be an array');
}
foreach ($value as $plugin) {
$request->addSubscriber($plugin);
}
}
}

View File

@ -1,107 +0,0 @@
<?php
namespace Guzzle\Tests;
use \Guzzle;
use Guzzle\Plugin\History\HistoryPlugin;
/**
* @group server
* @covers \Guzzle
*/
class GuzzleTest extends \Guzzle\Tests\GuzzleTestCase
{
public function setUp()
{
$this->getServer()->flush();
$this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"));
}
public function httpMethodProvider()
{
return array_map(function ($method) { return array($method); }, array(
'get', 'head', 'put', 'post', 'delete', 'options', 'patch'
));
}
/**
* @dataProvider httpMethodProvider
*/
public function testSendsHttpRequestsWithMethod($method)
{
Guzzle::$method($this->getServer()->getUrl());
$requests = $this->getServer()->getReceivedRequests(true);
$this->assertEquals(strtoupper($method), $requests[0]->getMethod());
}
public function testCanDisableRedirects()
{
$this->getServer()->enqueue(array(
"HTTP/1.1 307\r\nLocation: " . $this->getServer()->getUrl() . "\r\nContent-Length: 0\r\n\r\n"
));
$response = Guzzle::get($this->getServer()->getUrl(), array('allow_redirects' => false));
$this->assertEquals(307, $response->getStatusCode());
}
public function testCanAddCookies()
{
Guzzle::get($this->getServer()->getUrl(), array('cookies' => array('Foo' => 'Bar')));
$requests = $this->getServer()->getReceivedRequests(true);
$this->assertEquals('Bar', $requests[0]->getCookie('Foo'));
}
public function testCanAddQueryString()
{
Guzzle::get($this->getServer()->getUrl(), array('query' => array('Foo' => 'Bar')));
$requests = $this->getServer()->getReceivedRequests(true);
$this->assertEquals('Bar', $requests[0]->getQuery()->get('Foo'));
}
public function testCanAddCurl()
{
Guzzle::get($this->getServer()->getUrl(), array('curl' => array(CURLOPT_ENCODING => '*')));
$requests = $this->getServer()->getReceivedRequests(true);
$this->assertEquals('*/*', (string) $requests[0]->getHeader('Accept'));
}
public function testCanAddAuth()
{
Guzzle::get($this->getServer()->getUrl(), array('auth' => array('michael', 'test')));
$requests = $this->getServer()->getReceivedRequests(true);
$this->assertEquals('Basic bWljaGFlbDp0ZXN0', (string) $requests[0]->getHeader('Authorization'));
}
public function testCanAddEvents()
{
$foo = null;
Guzzle::get($this->getServer()->getUrl(), array(
'events' => array(
'request.complete' => function () use (&$foo) { $foo = true; }
)
));
$this->assertTrue($foo);
}
public function testCanAddPlugins()
{
$history = new HistoryPlugin();
Guzzle::get($this->getServer()->getUrl(), array('plugins' => array($history)));
$this->assertEquals(1, count($history));
}
public function testCanCreateStreams()
{
$response = Guzzle::get($this->getServer()->getUrl(), array('stream' => true));
$this->assertInstanceOf('Guzzle\Stream\StreamInterface', $response);
}
public function testCanCreateStreamsWithCustomFactory()
{
$f = $this->getMockBuilder('Guzzle\Stream\StreamRequestFactoryInterface')
->setMethods(array('fromRequest'))
->getMock();
$f->expects($this->once())
->method('fromRequest');
Guzzle::get($this->getServer()->getUrl(), array('stream' => $f));
}
}

View File

@ -4,11 +4,13 @@ namespace Guzzle\Tests\Http\Message;
use Guzzle\Common\Collection;
use Guzzle\Http\Client;
use Guzzle\Http\Message\Response;
use Guzzle\Http\Url;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\QueryString;
use Guzzle\Parser\Message\MessageParser;
use Guzzle\Plugin\Mock\MockPlugin;
/**
* @group server
@ -322,4 +324,71 @@ class HttpRequestFactoryTest extends \Guzzle\Tests\GuzzleTestCase
$this->assertEquals('http://www.test.com', $cloned->getUrl());
$this->assertSame($request->getClient(), $cloned->getClient());
}
public function testCanDisableRedirects()
{
$this->getServer()->enqueue(array(
"HTTP/1.1 307\r\nLocation: " . $this->getServer()->getUrl() . "\r\nContent-Length: 0\r\n\r\n"
));
$client = new Client($this->getServer()->getUrl());
$response = $client->get('/', array(), null, array('allow_redirects' => false))->send();
$this->assertEquals(307, $response->getStatusCode());
}
public function testCanAddCookies()
{
$client = new Client($this->getServer()->getUrl());
$request = $client->get('/', array(), null, array('cookies' => array('Foo' => 'Bar')));
$this->assertEquals('Bar', $request->getCookie('Foo'));
}
public function testCanAddQueryString()
{
$request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array(
'query' => array('Foo' => 'Bar')
));
$this->assertEquals('Bar', $request->getQuery()->get('Foo'));
}
public function testCanAddCurl()
{
$request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array(
'curl' => array(CURLOPT_ENCODING => '*')
));
$this->assertEquals('*', $request->getCurlOptions()->get(CURLOPT_ENCODING));
}
public function testCanAddAuth()
{
$request = RequestFactory::getInstance()->create('GET', 'http://foo.com', array(), null, array(
'auth' => array('michael', 'test')
));
$this->assertEquals('michael', $request->getUsername());
$this->assertEquals('test', $request->getPassword());
}
public function testCanAddEvents()
{
$foo = null;
$client = new Client();
$client->addSubscriber(new MockPlugin(array(new Response(200))));
$request = $client->get($this->getServer()->getUrl(), array(), null, array(
'events' => array(
'request.before_send' => function () use (&$foo) { $foo = true; }
)
));
$request->send();
$this->assertTrue($foo);
}
public function testCanAddPlugins()
{
$mock = new MockPlugin(array(new Response(200)));
$client = new Client();
$client->addSubscriber($mock);
$request = $client->get($this->getServer()->getUrl(), array(), null, array(
'plugins' => array($mock)
));
$request->send();
}
}