/**
  * @covers Guzzle\Guzzle::getCurlInfo
  * @covers Guzzle\Guzzle::reset
  */
 public function testDeterminesIfCurlCanFollowLocation()
 {
     Guzzle::reset();
     if (!ini_get('open_basedir')) {
         $this->assertTrue(Guzzle::getCurlInfo('follow_location'));
     } else {
         $this->assertFalse(Guzzle::getCurlInfo('follow_location'));
     }
 }
 /**
  * @covers Guzzle\Service\Command\DynamicCommand
  */
 public function testUsesDifferentLocations()
 {
     $client = new Client('http://www.tazmania.com/');
     $command = $this->factory->factory('body', array('b' => 'my-data', 'q' => 'abc', 'h' => 'haha'));
     $request = $command->setClient($client)->prepare();
     $this->assertEquals("PUT /?test=abc&i=test HTTP/1.1\r\n" . "Host: www.tazmania.com\r\n" . "User-Agent: " . Guzzle::getDefaultUserAgent() . "\r\n" . "Expect: 100-Continue\r\n" . "Content-Length: 29\r\n" . "X-Custom: haha\r\n" . "\r\n" . "begin_body::my-data::end_body", (string) $request);
     unset($command);
     unset($request);
     $command = $this->factory->factory('body', array('b' => 'my-data', 'q' => 'abc', 'h' => 'haha', 'i' => 'does not change the value because it\'s static'));
     $request = $command->setClient($client)->prepare();
     $this->assertEquals("PUT /?test=abc&i=test HTTP/1.1\r\n" . "Host: www.tazmania.com\r\n" . "User-Agent: " . Guzzle::getDefaultUserAgent() . "\r\n" . "Expect: 100-Continue\r\n" . "Content-Length: 29\r\n" . "X-Custom: haha\r\n" . "\r\n" . "begin_body::my-data::end_body", (string) $request);
 }
Ejemplo n.º 3
0
 /**
  * @covers Guzzle\Aws\S3\Command\Object\PutObject
  * @covers Guzzle\Aws\S3\Command\Object\AbstractRequestObject
  * @covers Guzzle\Aws\S3\Command\Object\AbstractRequestObjectPut
  */
 public function testPutObject()
 {
     $command = new PutObject();
     $command->setBucket('test')->setKey('key');
     $command->setBody('data');
     $command->getRequestHeaders()->set('x-amz-test', '123');
     $command->setAcl(S3Client::ACL_PUBLIC_READ);
     $command->setStorageClass('STANDARD');
     $client = $this->getServiceBuilder()->get('test.s3');
     $this->setMockResponse($client, 'PutObjectResponse');
     $client->execute($command);
     $request = (string) $command->getRequest();
     $this->assertEquals('http://test.s3.amazonaws.com/key', $command->getRequest()->getUrl());
     $this->assertEquals('PUT', $command->getRequest()->getMethod());
     $this->assertFalse($this->compareHttpHeaders(array('Host' => 'test.s3.amazonaws.com', 'Date' => '*', 'Content-Length' => '4', 'Content-MD5' => '8d777f385d3dfec8815d20f7496026dc', 'Authorization' => '*', 'x-amz-test' => '123', 'x-amz-acl' => 'public-read', 'x-amz-storage-class' => 'STANDARD', 'User-Agent' => Guzzle::getDefaultUserAgent(), 'Expect' => '100-Continue'), $command->getRequestHeaders()->getAll()));
     $this->assertEquals('data', (string) $command->getRequest()->getBody());
 }
Ejemplo n.º 4
0
 /**
  * @covers Guzzle\Aws\S3\Command\Object\HeadObject
  * @covers Guzzle\Aws\S3\Command\Object\AbstractRequestObject
  */
 public function testHeadObject()
 {
     $command = new \Guzzle\Aws\S3\Command\Object\HeadObject();
     $command->setBucket('test')->setKey('key');
     $command->setRange('bytes=500-999');
     $command->setIfMatch('abcd');
     $command->setIfNoneMatch('efghi');
     $command->setIfModifiedSince('Sat, 29 Oct 1994 19:43:31 GMT');
     $command->setIfUnmodifiedSince('Sat, 29 Oct 1994 19:43:31 GMT');
     $command->getRequestHeaders()->set('x-amz-test', '123');
     $command->setVersionId('123');
     $client = $this->getServiceBuilder()->get('test.s3');
     $this->setMockResponse($client, 'HeadObjectResponse');
     $client->execute($command);
     $this->assertEquals('http://test.s3.amazonaws.com/key?versionId=123', $command->getRequest()->getUrl());
     $this->assertEquals('HEAD', $command->getRequest()->getMethod());
     $this->assertFalse($this->compareHttpHeaders(array('Host' => 'test.s3.amazonaws.com', 'User-Agent' => Guzzle::getDefaultUserAgent(), 'Date' => '*', 'Authorization' => '*', 'Range' => 'bytes=500-999', 'If-Match' => 'abcd', 'If-None-Match' => 'efghi', 'If-Unmodified-Since' => 'Sat, 29 Oct 1994 19:43:31 GMT', 'If-Modified-Since' => 'Sat, 29 Oct 1994 19:43:31 GMT', 'x-amz-test' => '123'), $command->getRequest()->getHeaders()->getAll()));
 }
 /**
  * @covers Guzzle\Aws\S3\Command\Bucket\DeleteBucketPolicy
  */
 public function testDeleteBucketPolicy()
 {
     $command = new DeleteBucketPolicy();
     $this->assertSame($command, $command->setBucket('test'));
     $client = $this->getServiceBuilder()->get('test.s3');
     $this->setMockResponse($client, 'DeleteBucketPolicyResponse');
     $client->execute($command);
     // Ensure that the DELETE request was sent to the policy sub resource
     $this->assertEquals('http://test.s3.amazonaws.com/?policy', $command->getRequest()->getUrl());
     $this->assertEquals('DELETE', $command->getRequest()->getMethod());
     // Check the raw HTTP request message
     $request = explode("\r\n", (string) $command->getRequest());
     $this->assertEquals('DELETE /?policy HTTP/1.1', $request[0]);
     $this->assertEquals('User-Agent: ' . Guzzle::getDefaultUserAgent(), $request[1]);
     $this->assertEquals('Host: test.s3.amazonaws.com', $request[2]);
     $this->assertContains("Date: ", $request[3]);
     $this->assertContains("Authorization: ", $request[4]);
 }
 /**
  * @covers Guzzle\Aws\S3\Command\Object\InitiateMultipartUpload
  * @covers Guzzle\Aws\S3\Command\Object\AbstractRequestObject
  * @covers Guzzle\Aws\S3\Command\Object\AbstractRequestObjectPut
  */
 public function testInitiate()
 {
     $command = new InitiateMultipartUpload();
     $command->setBucket('example-bucket')->setKey('example-object');
     $command->getRequestHeaders()->set('x-amz-test', '123');
     $command->setAcl(S3Client::ACL_PUBLIC_READ);
     $command->setStorageClass('STANDARD');
     $client = $this->getServiceBuilder()->get('test.s3');
     $this->setMockResponse($client, 'InitiateMultipartUploadResponse');
     $client->execute($command);
     $request = (string) $command->getRequest();
     $this->assertEquals('http://example-bucket.s3.amazonaws.com/example-object?uploads', $command->getRequest()->getUrl());
     $this->assertEquals('POST', $command->getRequest()->getMethod());
     $this->assertFalse($this->compareHttpHeaders(array('Host' => 'example-bucket.s3.amazonaws.com', 'Date' => '*', 'Authorization' => '*', 'x-amz-test' => '123', 'x-amz-acl' => 'public-read', 'x-amz-storage-class' => 'STANDARD', 'User-Agent' => Guzzle::getDefaultUserAgent()), $command->getRequestHeaders()->getAll()));
     $this->assertInstanceOf('SimpleXMLElement', $command->getResult());
     $this->assertEquals('example-bucket', (string) $command->getResult()->Bucket);
     $this->assertEquals('example-object', (string) $command->getResult()->Key);
     $this->assertEquals('VXBsb2FkIElEIGZvciA2aWWpbmcncyBteS1tb3ZpZS5tMnRzIHVwbG9hZA', (string) $command->getResult()->UploadId);
 }
Ejemplo n.º 7
0
 /**
  * @covers Guzzle\Aws\S3\Command\Object\CopyObject
  */
 public function testCopyObject()
 {
     $command = new \Guzzle\Aws\S3\Command\Object\CopyObject();
     $command->setBucket('test')->setKey('key');
     $this->assertSame($command, $command->setCopySource('source_bucket', 'source_key'));
     $this->assertSame($command, $command->setAcl(\Guzzle\Aws\S3\S3Client::ACL_PUBLIC_READ));
     $this->assertSame($command, $command->setStorageClass('STANDARD'));
     $this->assertSame($command, $command->setMetadataDirective('COPY'));
     $this->assertSame($command, $command->setCopySourceIfMatch('match_etag'));
     $this->assertSame($command, $command->setCopySourceIfNoneMatch('none_match_etag'));
     $this->assertSame($command, $command->setCopySourceIfModifiedSince('now'));
     $this->assertSame($command, $command->setCopySourceIfUnmodifiedSince('now'));
     $client = $this->getServiceBuilder()->get('test.s3');
     $this->setMockResponse($client, 'CopyObjectResponse');
     $client->execute($command);
     $request = (string) $command->getRequest();
     $this->assertEquals('http://test.s3.amazonaws.com/key', $command->getRequest()->getUrl());
     $this->assertEquals('PUT', $command->getRequest()->getMethod());
     $this->assertFalse($this->compareHttpHeaders(array('Host' => 'test.s3.amazonaws.com', 'Date' => '*', 'Content-Length' => '4', 'Content-MD5' => '8d777f385d3dfec8815d20f7496026dc', 'Authorization' => '*', 'x-amz-test' => '123', 'x-amz-acl' => 'public-read', 'x-amz-storage-class' => 'STANDARD', 'x-amz-copy-source' => '/source_bucket/source_key', 'x-amz-metadata-directive' => 'COPY', 'x-amz-copy-source-if-match' => 'match_etag', 'x-amz-copy-source-if-none-match' => 'none_match_etag', 'x-amz-copy-source-if-modified-since' => Guzzle::getHttpDate('now'), 'x-amz-copy-source-if-unmodified-since' => Guzzle::getHttpDate('now'), 'User-Agent' => Guzzle::getDefaultUserAgent()), $command->getRequestHeaders()->getAll()));
 }
Ejemplo n.º 8
0
 /**
  * prepares a request for execution
  **/
 protected function build()
 {
     $method = $this->get('method');
     // ensure the appropriate method is being used
     if (null === constant('\\Guzzle\\Http\\Message\\RequestInterface::' . strtoupper($method))) {
         throw new \InvalidArgumentException('You must use a valid REST method.');
     }
     //end if
     $url = $this->get('service');
     // convert passed arguments into a collection
     if ($args = $this->get('args')) {
         $args = new \Guzzle\Common\Collection((array) $args);
         $url = \Guzzle\Guzzle::inject($url, $args);
     }
     //end if
     // set up the request object
     $this->request = $this->client->{$method}($url);
     // assign query data if passed
     if ($query = $this->get('query')) {
         $this->request->getQuery()->merge($query);
     }
     //end if
 }
 /**
  * Return the object only if it has not been modified since the specified
  * time, otherwise return a 412 (precondition failed).
  *
  * @param string $since
  * 
  * @return GetObject
  */
 public function setIfUnmodifiedSince($since)
 {
     return $this->set('if_unmodified_since', Guzzle::getHttpDate($since));
 }
Ejemplo n.º 10
0
 /**
  * Set the name of your application and application version that will be
  * appended to the User-Agent header of all reqeusts.
  *
  * @param string $userAgent User agent string
  * @param bool $includeDefault (optional) Set to TRUE to append the default
  *    Guzzle user agent
  *
  * @return Client
  */
 public function setUserAgent($userAgent, $includeDefault = false)
 {
     if ($includeDefault) {
         $userAgent .= ' ' . Guzzle::getDefaultUserAgent();
     }
     $this->defaultHeaders->set('User-Agent', $userAgent);
     return $this;
 }
 /**
  * Data provider to test cache revalidation
  *
  * @return array
  */
 public function cacheRevalidationDataProvider()
 {
     return array(array(true, "Pragma: no-cache\r\n\r\n", "HTTP/1.1 200 OK\r\nDate: " . Guzzle::getHttpDate('-100 hours') . "\r\nContent-Length: 4\r\n\r\nData", "HTTP/1.1 304 NOT MODIFIED\r\nCache-Control: max-age=2000000\r\nContent-Length: 0\r\n\r\n"), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: must-revalidate, no-cache\r\nDate: " . Guzzle::getHttpDate('-10 hours') . "\r\nContent-Length: 4\r\n\r\nData", "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nDatas", "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nDate: " . Guzzle::getHttpDate('now') . "\r\n\r\nDatas"), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . Guzzle::getHttpDate('-3 hours') . "\r\nContent-Length: 4\r\n\r\nData", null, null, 'never'), array(true, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . Guzzle::getHttpDate('-3 hours') . "\r\nContent-Length: 4\r\n\r\nData", null, null, 'skip'), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nDate: " . Guzzle::getHttpDate('-3 hours') . "\r\n\r\nData", "HTTP/1.1 500 INTERNAL SERVER ERROR\r\nContent-Length: 0\r\n\r\n"), array(false, "\r\n\r\n", "HTTP/1.1 200 OK\r\nCache-Control: no-cache\r\nETag: \"123\"\r\nDate: " . Guzzle::getHttpDate('-10 hours') . "\r\n\r\nData", "HTTP/1.1 304 NOT MODIFIED\r\nETag: \"123456\"\r\n\r\n"));
 }
 /**
  * Save data to the cache adapter
  *
  * @param string $key The cache key
  * @param Response $response The response to cache
  * @param int $lifetime (optional) Amount of seconds to cache
  *
  * @return int Returns the lifetime of the cached data
  */
 protected function saveCache($key, Response $response, $lifetime = null)
 {
     $lifetime = $lifetime ?: $this->defaultLifetime;
     // If the data is cacheable, then save it to the cache adapter
     if ($lifetime) {
         // Remove excluded headers from the response  (see RFC 2616:13.5.1)
         foreach ($this->excludeResponseHeaders as $header) {
             $response->removeHeader($header);
         }
         // Add a Date header to the response if none is set (for validation)
         if (!$response->getDate()) {
             $response->setHeader('Date', Guzzle::getHttpDate('now'));
         }
         $data = array('c' => $response->getStatusCode(), 'h' => $response->getHeaders(), 'b' => $response->getBody(true));
         if ($this->serialize) {
             $data = serialize($data);
         }
         $this->getCacheAdapter()->save($key, $data, $lifetime);
     }
     return $lifetime;
 }
 /**
  * Data provider for factory tests
  *
  * @return array
  */
 public function dataProvider()
 {
     $testFile = __DIR__ . '/../../../../../phpunit.xml';
     $postBody = new QueryString(array('file' => '@' . $testFile));
     $qs = new QueryString(array('x' => 'y', 'z' => 'a'));
     $userAgent = Guzzle::getDefaultUserAgent();
     $auth = base64_encode('michael:123');
     $testFileSize = filesize($testFile);
     return array(array('GET', 'http://www.google.com/', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_ENCODING => '', CURLOPT_HTTPHEADER => array('Host: www.google.com', 'User-Agent: ' . $userAgent))), array('TRACE', 'http://www.google.com/', null, null, array(CURLOPT_CUSTOMREQUEST => 'TRACE')), array('GET', 'http://127.0.0.1:8080', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_ENCODING => '', CURLOPT_PORT => 8080, CURLOPT_HTTPHEADER => array('Host: 127.0.0.1:8080', 'User-Agent: ' . $userAgent))), array('HEAD', 'http://www.google.com/', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_ENCODING => '', CURLOPT_HTTPHEADER => array('Host: www.google.com', 'User-Agent: ' . $userAgent), CURLOPT_NOBODY => 1)), array('GET', 'https://*****:*****@localhost/index.html?q=2', null, null, array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_ENCODING => '', CURLOPT_HTTPHEADER => array('Host: localhost', 'Authorization: Basic ' . $auth, 'User-Agent: ' . $userAgent), CURLOPT_PORT => 443)), array('GET', 'http://*****:*****@' . $testFile), CURLOPT_HTTPHEADER => array('Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Expect: 100-Continue', 'Content-Type: multipart/form-data')), array('_Accept' => '*', '_Accept-Encoding' => '*', 'Host' => '*', 'User-Agent' => '*', 'Content-Length' => '*', 'Expect' => '100-Continue', 'Content-Type' => 'multipart/form-data; boundary=*', '!Transfer-Encoding' => null)), array('POST', 'http://localhost:8124/post.php', array('Content-Type' => 'application/json'), '{"hi":"there"}', array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_ENCODING => '', CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array('Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Expect: 100-Continue', 'Content-Type: application/json', 'Content-Length: 14')), array('_Accept-Encoding' => '*', '_Accept' => '*', 'Host' => '*', 'User-Agent' => '*', 'Content-Type' => 'application/json', 'Expect' => '100-Continue', 'Content-Length' => '14', '!Transfer-Encoding' => null)), array('POST', 'http://localhost:8124/post.php', array('Content-Type' => 'application/json', 'Transfer-Encoding' => 'chunked'), '{"hi":"there"}', array(CURLOPT_RETURNTRANSFER => 0, CURLOPT_HEADER => 0, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_USERAGENT => $userAgent, CURLOPT_WRITEFUNCTION => 'callback', CURLOPT_HEADERFUNCTION => 'callback', CURLOPT_ENCODING => '', CURLOPT_POST => 1, CURLOPT_HTTPHEADER => array('Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Expect: 100-Continue', 'Content-Type: application/json', 'Transfer-Encoding: chunked')), array('_Accept-Encoding' => '*', '_Accept' => '*', 'Host' => '*', 'User-Agent' => '*', 'Content-Type' => 'application/json', 'Expect' => '100-Continue', 'Transfer-Encoding' => 'chunked', '!Content-Length' => '')), array('POST', 'http://localhost:8124/foo.php', null, null, array(CURLOPT_HTTPHEADER => array('Expect:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Content-Length: 0')), array('_Accept' => '*', '_Accept-Encoding' => '*', 'Host' => '*', 'User-Agent' => '*', 'Content-Length' => '0', '!Expect' => null, 'Content-Type' => 'application/x-www-form-urlencoded', '!Transfer-Encoding' => null)), array('PUT', 'http://localhost:8124/empty-put.php', null, null, array(CURLOPT_HTTPHEADER => array('Expect:', 'Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Content-Length: 0')), array('_Accept' => '*', '_Accept-Encoding' => '*', 'Host' => '*', 'User-Agent' => '*', 'Content-Length' => '0', '!Expect' => null, '!Content-Type' => null, '!Transfer-Encoding' => null)), array('PATCH', 'http://localhost:8124/patch.php', null, 'body', array(CURLOPT_INFILESIZE => 4, CURLOPT_HTTPHEADER => array('Host: localhost:8124', 'User-Agent: ' . $userAgent, 'Expect: 100-Continue'))));
 }
Ejemplo n.º 14
0
 /**
  * {@inheritdoc}
  */
 public function createRequest($method = RequestInterface::GET, $uri = null, $inject = null)
 {
     $request = parent::createRequest($method, $uri, $inject);
     $request->setHeader('Date', Guzzle::getHttpDate('now'))->setHeader('Host', $request->getHost());
     return $request;
 }
 /**
  * @covers Guzzle\Http\Plugin\CookiePlugin::onRequestBeforeSend
  */
 public function testCookiesAreNotAddedWhenParamIsSet()
 {
     $this->storage->clear();
     $this->storage->save(array('domain' => 'example.com', 'path' => '/', 'cookie' => array('test', 'hi'), 'expires' => Guzzle::getHttpDate('+1 day')));
     $client = new Client('http://example.com');
     $client->getEventDispatcher()->addSubscriber($this->plugin);
     $request = $client->get();
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertEquals('hi', $request->getCookie()->get('test'));
     $request = $client->get();
     $request->getParams()->set('cookies.disable', true);
     $request->setResponse(new Response(200), true);
     $request->send();
     $this->assertNull($request->getCookie()->get('test'));
 }
 /**
  * @covers Guzzle\Http\Message\Response::getMaxAge
  */
 public function testDeterminesResponseMaxAge()
 {
     $this->assertEquals(null, $this->getResponse(200)->getMaxAge());
     // Uses the response's s-maxage
     $this->assertEquals(140, $this->getResponse(200, array('Cache-Control' => 's-maxage=140'))->getMaxAge());
     // Uses the response's max-age
     $this->assertEquals(120, $this->getResponse(200, array('Cache-Control' => 'max-age=120'))->getMaxAge());
     // Uses the response's max-age
     $this->assertEquals(120, $this->getResponse(200, array('Cache-Control' => 'max-age=120', 'Expires' => Guzzle::getHttpDate('+1 day')))->getMaxAge());
     // Uses the Expires date
     $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array('Expires' => Guzzle::getHttpDate('+1 day')))->getMaxAge());
     // Uses the Expires date
     $this->assertGreaterThanOrEqual(82400, $this->getResponse(200, array('Expires' => Guzzle::getHttpDate('+1 day')))->getMaxAge());
 }
 /**
  * Factory method to create a new curl handle based on an HTTP request
  *
  * There are some helpful options you can set to enable specific behavior:
  *    - disabled_wire: This is a performance improvement that will disable
  *         some debugging functionality with cURL.  The functionality
  *         it disabled allows you to see the exact HTTP request sent over
  *         the wire.
  *    - progress: Set to true to enable progress function callbacks. Most
  *         People don't need this, so it has been disabled by default.
  *
  * @param RequestInterface $request Request
  *
  * @return CurlHandle
  */
 public static function factory(RequestInterface $request)
 {
     $handle = curl_init();
     $mediator = new RequestMediator($request);
     $requestCurlOptions = $request->getCurlOptions();
     // Array of default cURL options.
     $curlOptions = array(CURLOPT_URL => $request->getUrl(), CURLOPT_CUSTOMREQUEST => $request->getMethod(), CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_RETURNTRANSFER => false, CURLOPT_HEADER => false, CURLOPT_USERAGENT => (string) $request->getHeader('User-Agent'), CURLOPT_ENCODING => '', CURLOPT_PORT => $request->getPort(), CURLOPT_HTTP_VERSION => $request->getProtocolVersion() === '1.0' ? CURL_HTTP_VERSION_1_0 : CURL_HTTP_VERSION_1_1, CURLOPT_HTTPHEADER => array(), CURLOPT_HEADERFUNCTION => array($mediator, 'receiveResponseHeader'));
     // Enable the progress function if the 'progress' param was set
     if ($requestCurlOptions->get('progress')) {
         $curlOptions[CURLOPT_PROGRESSFUNCTION] = array($mediator, 'progress');
         $curlOptions[CURLOPT_NOPROGRESS] = false;
     }
     // Enable curl debug information if the 'debug' param was set
     if (!$requestCurlOptions->get('disable_wire')) {
         $curlOptions[CURLOPT_STDERR] = fopen('php://temp', 'r+');
         $curlOptions[CURLOPT_VERBOSE] = true;
     }
     // HEAD requests need no response body, everything else might
     if ($request->getMethod() != 'HEAD') {
         $curlOptions[CURLOPT_WRITEFUNCTION] = array($mediator, 'writeResponseBody');
     }
     // Account for PHP installations with safe_mode or open_basedir enabled
     // @codeCoverageIgnoreStart
     if (Guzzle::getCurlInfo('follow_location')) {
         $curlOptions[CURLOPT_FOLLOWLOCATION] = true;
         $curlOptions[CURLOPT_MAXREDIRS] = 5;
     }
     // @codeCoverageIgnoreEnd
     $headers = $request->getHeaders()->getAll();
     // Specify settings according to the HTTP method
     switch ($request->getMethod()) {
         case 'GET':
             $curlOptions[CURLOPT_HTTPGET] = true;
             break;
         case 'HEAD':
             $curlOptions[CURLOPT_NOBODY] = true;
             unset($curlOptions[CURLOPT_WRITEFUNCTION]);
             break;
         case 'POST':
             $curlOptions[CURLOPT_POST] = true;
             break;
         case 'PUT':
         case 'PATCH':
             $curlOptions[CURLOPT_UPLOAD] = true;
             if ($request->hasHeader('Content-Length')) {
                 unset($headers['Content-Length']);
                 $curlOptions[CURLOPT_INFILESIZE] = (int) (string) $request->getHeader('Content-Length');
             }
             break;
     }
     if ($request instanceof EntityEnclosingRequestInterface) {
         // If no body is being sent, always send Content-Length of 0
         if (!$request->getBody() && !count($request->getPostFields())) {
             $headers['Content-Length'] = 0;
             unset($headers['Transfer-Encoding']);
             // Need to remove CURLOPT_UPLOAD to prevent chunked encoding
             unset($curlOptions[CURLOPT_UPLOAD]);
             unset($curlOptions[CURLOPT_POST]);
             // Not reading from a callback when using empty body
             unset($curlOptions[CURLOPT_READFUNCTION]);
         } else {
             // Add a callback for curl to read data to send with the request
             $curlOptions[CURLOPT_READFUNCTION] = array($mediator, 'readRequestBody');
         }
         // If the Expect header is not present, prevent curl from adding it
         if (!$request->hasHeader('Expect')) {
             $curlOptions[CURLOPT_HTTPHEADER][] = 'Expect:';
         }
     }
     // Set custom cURL options
     foreach ($requestCurlOptions as $key => $value) {
         if (is_numeric($key)) {
             $curlOptions[$key] = $value;
         }
     }
     // Check if any headers or cURL options are blacklisted
     $client = $request->getClient();
     if ($client) {
         $blacklist = $client->getConfig('curl.blacklist');
         if ($blacklist) {
             foreach ($blacklist as $value) {
                 if (strpos($value, 'header.') === 0) {
                     $blacklistHeader = substr($value, 7);
                     // Remove headers that may have previously been set
                     // but are supposed to be blacklisted
                     unset($headers[$blacklistHeader]);
                     $headers[$blacklistHeader] = '';
                 } else {
                     unset($curlOptions[$value]);
                 }
             }
         }
     }
     // Add any custom headers to the request. Emtpy headers will cause curl to
     // not send the header at all.
     foreach ($headers as $key => $value) {
         foreach ((array) $value as $val) {
             $curlOptions[CURLOPT_HTTPHEADER][] = trim("{$key}: {$val}");
         }
     }
     // Apply the options to the cURL handle.
     curl_setopt_array($handle, $curlOptions);
     $request->getParams()->set('curl.last_options', $curlOptions);
     return new static($handle, $curlOptions);
 }
 /**
  * @covers Guzzle\Http\Client::setUserAgent
  * @covers Guzzle\Http\Client::createRequest
  * @covers Guzzle\Http\Client::prepareRequest
  */
 public function testSetsUserAgent()
 {
     $client = new Client('http://www.test.com/', array('api' => 'v1'));
     $this->assertSame($client, $client->setUserAgent('Test/1.0Ab', true));
     $this->assertEquals('Test/1.0Ab ' . Guzzle::getDefaultUserAgent(), $client->get()->getHeader('User-Agent'));
     $client->setUserAgent('Test/1.0Ab');
     $this->assertEquals('Test/1.0Ab', $client->get()->getHeader('User-Agent'));
 }
Ejemplo n.º 19
0
 /**
  * Copies the object if it has been modified since the specified time;
  * otherwise, the request returns a 412 HTTP status code error (failed
  * condition).
  *
  * @param string $date The HTTP date to use
  *
  * @return CopyObject
  */
 public function setCopySourceIfModifiedSince($date)
 {
     return $this->set('copy_source_if_modified_since', Guzzle::getHttpDate($date));
 }
 /**
  * Add values to the cookiejar
  */
 protected function addCookies()
 {
     $this->jar->save(array('cookie' => array('foo', 'bar'), 'domain' => 'example.com', 'path' => '/', 'max_age' => '86400', 'port' => array(80, 8080), 'version' => '1', 'secure' => true))->save(array('cookie' => array('test', '123'), 'domain' => 'www.foobar.com', 'path' => '/path/', 'discard' => true))->save(array('domain' => '.y.example.com', 'path' => '/acme/', 'cookie' => array('muppet', 'cookie_monster'), 'comment' => 'Comment goes here...', 'expires' => Guzzle::getHttpDate('+1 day')))->save(array('domain' => '.example.com', 'path' => '/test/acme/', 'cookie' => array('googoo', 'gaga'), 'max_age' => 1500, 'version' => 2));
 }
 public function testLogsWhenExceptionsAreThrown()
 {
     $client = new Client($this->getServer()->getUrl());
     $plugin = new LogPlugin($this->logAdapter, LogPlugin::LOG_VERBOSE);
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request = $client->get();
     $this->getServer()->enqueue("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
     ob_start();
     try {
         $request->send();
         $this->fail('Exception for 404 was not thrown');
     } catch (\Exception $e) {
     }
     $message = ob_get_clean();
     $this->assertContains('127.0.0.1 - "GET / HTTP/1.1" - 404 0 - ', $message);
     $this->assertContains("GET / HTTP/1.1\r\n", $message);
     $this->assertContains("User-Agent: " . Guzzle::getDefaultUserAgent(), $message);
     $this->assertContains("\n< HTTP/1.1 404 Not Found\r\n< Content-Length: 0", $message);
 }
 /**
  * This test launches a dummy Guzzle\Http\Server\Server object that listens
  * for incoming requests.  The server allows us to test how cURL sends
  * requests and receives responses.  We can validate the request structure
  * and whether or not the response was interpreted correctly.
  *
  * @covers Guzzle\Http\Message\Request
  */
 public function testRequestCanBeSentUsingCurl()
 {
     $this->getServer()->flush();
     $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata", "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nExpires: Thu, 01 Dec 1994 16:00:00 GMT\r\nConnection: close\r\n\r\ndata", "HTTP/1.1 404 Not Found\r\nContent-Encoding: application/xml\r\nContent-Length: 48\r\n\r\n<error><mesage>File not found</message></error>"));
     $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl());
     $request->setClient($this->client);
     $response = $request->send();
     $this->assertEquals('data', $response->getBody(true));
     $this->assertEquals(200, (int) $response->getStatusCode());
     $this->assertEquals('OK', $response->getReasonPhrase());
     $this->assertEquals(4, $response->getContentLength());
     $this->assertEquals('Thu, 01 Dec 1994 16:00:00 GMT', $response->getExpires());
     // Test that the same handle can be sent twice without setting state to new
     $response2 = $request->send();
     $this->assertNotSame($response, $response2);
     try {
         $request = RequestFactory::getInstance()->create('GET', $this->getServer()->getUrl() . 'index.html');
         $request->setClient($this->client);
         $response = $request->send();
         $this->fail('Request did not receive a 404 response');
     } catch (BadResponseException $e) {
     }
     $requests = $this->getServer()->getReceivedRequests(true);
     $messages = $this->getServer()->getReceivedRequests(false);
     $port = $this->getServer()->getPort();
     $userAgent = Guzzle::getDefaultUserAgent();
     $this->assertEquals('127.0.0.1:' . $port, $requests[0]->getHeader('Host'));
     $this->assertEquals('127.0.0.1:' . $port, $requests[1]->getHeader('Host'));
     $this->assertEquals('127.0.0.1:' . $port, $requests[2]->getHeader('Host'));
     $this->assertEquals('/', $requests[0]->getPath());
     $this->assertEquals('/', $requests[1]->getPath());
     $this->assertEquals('/index.html', $requests[2]->getPath());
     $parts = explode("\r\n", $messages[0]);
     $this->assertEquals('GET / HTTP/1.1', $parts[0]);
     $parts = explode("\r\n", $messages[1]);
     $this->assertEquals('GET / HTTP/1.1', $parts[0]);
     $parts = explode("\r\n", $messages[2]);
     $this->assertEquals('GET /index.html HTTP/1.1', $parts[0]);
 }
 /**
  * Validates that all required args are included in a config object,
  * and if not, throws an InvalidArgumentException with a helpful error message.  Adds
  * default args to the passed config object if the parameter was not
  * set in the config object.
  *
  * @param array $params Params to validate
  * @param Collection $config Configuration settings
  * @param bool $strict (optional) Set to FALSE to allow missing required fields
  * @param bool $validate (optional) Set to TRUE or FALSE to validate data.
  *     Set to false when you only need to add default values and statics.
  *
  * @return array|bool Returns an array of errors or TRUE on success
  *
  * @throws InvalidArgumentException if any args are missing and $strict is TRUE
  */
 public function validateConfig(array $params, Collection $config, $strict = true, $validate = true)
 {
     $errors = array();
     foreach ($params as $name => $arg) {
         // Set the default or static value if it is not set
         $configValue = $arg->getValue($config->get($name));
         // Inject configuration information into the config value
         if (is_string($configValue)) {
             $configValue = Guzzle::inject($configValue, $config);
         }
         // Ensure that required arguments are set
         if ($validate && $arg->getRequired() && ($configValue === null || $configValue === '')) {
             $errors[] = 'Requires that the ' . $name . ' argument be supplied.' . ($arg->getDoc() ? '  (' . $arg->getDoc() . ').' : '');
             continue;
         }
         // Ensure that the correct data type is being used
         if ($validate && $this->typeValidation && $configValue !== null && ($argType = $arg->getType())) {
             $validation = $this->validateConstraint($argType, $configValue);
             if ($validation !== true) {
                 $errors[] = $validation;
                 continue;
             }
         }
         // Run the value through attached filters
         $configValue = $arg->filter($configValue);
         $config->set($name, $configValue);
         // Check the length values if validating data
         if ($validate) {
             $argMinLength = $arg->getMinLength();
             if ($argMinLength && strlen($configValue) < $argMinLength) {
                 $errors[] = 'Requires that the ' . $name . ' argument be >= ' . $arg->getMinLength() . ' characters.';
             }
             $argMaxLength = $arg->getMaxLength();
             if ($argMaxLength && strlen($configValue) > $argMaxLength) {
                 $errors[] = 'Requires that the ' . $name . ' argument be <= ' . $arg->getMaxLength() . ' characters.';
             }
         }
         $config->set($name, $configValue);
     }
     if (empty($errors)) {
         return true;
     } else {
         if ($strict) {
             throw new ValidationException('Validation errors: ' . implode("\n", $errors));
         }
     }
     return $errors;
 }
 /**
  * Create a new request
  *
  * @param string $method HTTP method
  * @param string|Url $url HTTP URL to connect to.  The URI scheme, host
  *      header, and URI are parsed from the full URL.  If query string
  *      parameters are present they will be parsed as well.
  * @param array|Collection $headers (optional) HTTP headers
  */
 public function __construct($method, $url, $headers = array())
 {
     $this->method = strtoupper($method);
     $this->curlOptions = new Collection();
     $this->params = new Collection();
     $this->setUrl($url);
     if ($headers) {
         // Special handling for multi-value headers
         foreach ($headers as $key => $value) {
             $lkey = strtolower($key);
             // Deal with collisions with Host and Authorization
             if ($lkey == 'host' || $lkey == 'authorization') {
                 $this->setHeader($key, $value);
             } else {
                 foreach ((array) $value as $v) {
                     $this->addHeader($key, $v);
                 }
             }
         }
     }
     if (!$this->hasHeader('User-Agent', true)) {
         $this->setHeader('User-Agent', Guzzle::getDefaultUserAgent());
     }
     $this->cookie = Cookie::factory($this->getHeader('Cookie'));
     $this->setState(self::STATE_NEW);
 }
 /**
  * @covers Guzzle\Http\CookieJar\ArrayCookieJar
  */
 public function testClearsExpiredCookies()
 {
     self::addCookies($this->jar);
     $this->assertEquals(0, $this->jar->deleteExpired());
     // Add an expired cookie
     $this->jar->save(array('cookie' => array('data', 'abc'), 'expires' => Guzzle::getHttpDate('-1 day'), 'domain' => '.example.com'));
     // Filters out expired cookies
     $this->hasCookies($this->jar->getCookies(), array('foo', 'baz', 'test', 'muppet', 'googoo'));
     $this->assertEquals(1, $this->jar->deleteExpired());
     $this->assertEquals(0, $this->jar->deleteExpired());
 }
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::__toString
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::addPostFields
  */
 public function testAddsPostFieldsAndSetsContentLength()
 {
     $request = RequestFactory::getInstance()->create('POST', 'http://www.guzzle-project.com/', null, array('data' => '123'));
     $this->assertEquals("POST / HTTP/1.1\r\n" . "Host: www.guzzle-project.com\r\n" . "User-Agent: " . Guzzle::getDefaultUserAgent() . "\r\n" . "Content-Type: application/x-www-form-urlencoded\r\n\r\n" . "data=123", (string) $request);
 }