Пример #1
0
 protected function createRedirectRequest(RequestInterface $request, $statusCode, $location, RequestInterface $original)
 {
     $redirectRequest = null;
     $strict = $original->getParams()->get(self::STRICT_REDIRECTS);
     if ($request instanceof EntityEnclosingRequestInterface && ($statusCode == 303 || !$strict && $statusCode <= 302)) {
         $redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET');
     } else {
         $redirectRequest = clone $request;
     }
     $redirectRequest->setIsRedirect(true);
     $redirectRequest->setResponseBody($request->getResponseBody());
     $location = Url::factory($location);
     if (!$location->isAbsolute()) {
         $originalUrl = $redirectRequest->getUrl(true);
         $originalUrl->getQuery()->clear();
         $location = $originalUrl->combine((string) $location, true);
     }
     $redirectRequest->setUrl($location);
     $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);
     });
     if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) {
         $body = $redirectRequest->getBody();
         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;
 }
Пример #2
0
 public function testSettingBody()
 {
     $request = \Guzzle\Http\Message\RequestFactory::getInstance()->create('PUT', 'http://www.test.com/');
     $request->setBody(EntityBody::factory('test'));
     $this->assertEquals(4, (string) $request->getHeader('Content-Length'));
     $this->assertFalse($request->hasHeader('Transfer-Encoding'));
 }
 private function uploadMedia($path, $type)
 {
     //build Mac
     $timeStamp = time();
     $lstParams = array($this->pageId, $timeStamp, $this->secretKey);
     $mac = ZaloSdkHelper::buildMacForAuthentication($lstParams);
     $request = RequestFactory::getInstance()->create('POST', CommonInfo::$DOMAIN . CommonInfo::$SER_UPLOAD)->setClient(new Client())->addPostFiles(array(CommonInfo::$URL_UPLOAD => $path))->addPostFields(array(CommonInfo::$URL_ACT => $type, CommonInfo::$URL_PAGEID => $this->pageId, CommonInfo::$URL_TIMESTAMP => $timeStamp, CommonInfo::$URL_MAC => $mac));
     $response = $request->send()->json();
     $error = $response["error"];
     if ($error < 0) {
         $zaloSdkExcep = new ZaloSdkException();
         $zaloSdkExcep->setZaloSdkExceptionErrorCode($error);
         if (!empty($response["message"])) {
             $zaloSdkExcep->setZaloSdkExceptionMessage($response["message"]);
         }
         throw $zaloSdkExcep;
     } else {
         if (!empty($response["result"])) {
             return $response["result"];
         } else {
             $zaloSdkExcep = new ZaloSdkException();
             $zaloSdkExcep->setZaloSdkExceptionErrorCode(-1);
             throw zaloSdkExcep;
         }
     }
 }
Пример #4
0
 /**
  * Client constructor
  *
  * @param string           $baseUrl Base URL of the web service
  * @param array|Collection $config  Configuration settings
  */
 public function __construct($baseUrl = '', $config = null)
 {
     $this->setConfig($config ?: new Collection());
     $this->setBaseUrl($baseUrl);
     $this->defaultHeaders = new Collection();
     $this->setRequestFactory(RequestFactory::getInstance());
 }
Пример #5
0
 /**
  * Constructor override
  */
 public function __construct(Collection $config)
 {
     $this->setConfig($config);
     $this->setBaseUrl($config->get(Options::BASE_URL));
     $this->defaultHeaders = new Collection();
     $this->setRequestFactory(RequestFactory::getInstance());
 }
Пример #6
0
 public function testProperlyValidatesWhenUsingContentEncoding()
 {
     $plugin = new Md5ValidatorPlugin(true);
     $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
     $request->getEventDispatcher()->addSubscriber($plugin);
     // Content-MD5 is the MD5 hash of the canonical content after all
     // content-encoding has been applied.  Because cURL will automatically
     // decompress entity bodies, we need to re-compress it to calculate.
     $body = EntityBody::factory('abc');
     $body->compress();
     $hash = $body->getContentMd5();
     $body->uncompress();
     $response = new Response(200, array('Content-MD5' => $hash, 'Content-Encoding' => 'gzip'), 'abc');
     $request->dispatch('request.complete', array('response' => $response));
     $this->assertEquals('abc', $response->getBody(true));
     // Try again with an unknown encoding
     $response = new Response(200, array('Content-MD5' => $hash, 'Content-Encoding' => 'foobar'), 'abc');
     $request->dispatch('request.complete', array('response' => $response));
     // Try again with compress
     $body->compress('bzip2.compress');
     $response = new Response(200, array('Content-MD5' => $body->getContentMd5(), 'Content-Encoding' => 'compress'), 'abc');
     $request->dispatch('request.complete', array('response' => $response));
     // Try again with encoding and disabled content-encoding checks
     $request->getEventDispatcher()->removeSubscriber($plugin);
     $plugin = new Md5ValidatorPlugin(false);
     $request->getEventDispatcher()->addSubscriber($plugin);
     $request->dispatch('request.complete', array('response' => $response));
 }
Пример #7
0
 /**
  * @dataProvider signatureDataProvider
  */
 public function testCreatesCanonicalizedString($input, $result, $expires = null)
 {
     $signature = new S3Signature();
     $request = \Guzzle\Http\Message\RequestFactory::getInstance()->create($input['verb'], 'http://' . $input['headers']['Host'] . $input['path'], $input['headers']);
     $request->setClient($this->getServiceBuilder()->get('s3'));
     $this->assertEquals($result, $signature->createCanonicalizedString($request), $expires);
 }
 /**
  * @covers Guzzle\Http\Plugin\HistoryPlugin::add
  */
 public function testIgnoresUnsentRequests()
 {
     $h = new HistoryPlugin();
     $request = RequestFactory::getInstance()->create('GET', 'http://localhost/');
     $h->add($request);
     $this->assertEquals(0, count($h));
 }
 /**
  * @dataProvider cacheRevalidationDataProvider
  */
 public function testRevalidatesResponsesAgainstOriginServer($can, $request, $response, $validate = null, $result = null)
 {
     // Send some responses to the test server for cache validation
     $server = $this->getServer();
     $server->flush();
     if ($validate) {
         $server->enqueue($validate);
     }
     $request = RequestFactory::getInstance()->fromMessage("GET / HTTP/1.1\r\nHost: 127.0.0.1:" . $server->getPort() . "\r\n" . $request);
     $response = Response::fromMessage($response);
     $request->setClient(new Client());
     $plugin = new CachePlugin(new DoctrineCacheAdapter(new ArrayCache()));
     $this->assertEquals($can, $plugin->canResponseSatisfyRequest($request, $response), '-> ' . $request . "\n" . $response);
     if ($result) {
         $result = Response::fromMessage($result);
         $result->removeHeader('Date');
         $request->getResponse()->removeHeader('Date');
         $request->getResponse()->removeHeader('Connection');
         // Get rid of dates
         $this->assertEquals((string) $result, (string) $request->getResponse());
     }
     if ($validate) {
         $this->assertEquals(1, count($server->getReceivedRequests()));
     }
 }
Пример #10
0
 /**
  * @dataProvider getErrorMapping
  * @param string $httpMethod
  * @param int    $statusCode
  * @param string $description
  */
 public function testErrorDescriptions($httpMethod, $statusCode, $description)
 {
     $request = RequestFactory::getInstance()->fromMessage("{$httpMethod} /container/ HTTP/1.1\r\n" . "Host: www.foo.bar\r\n");
     $response = new Response($statusCode);
     $prevException = BadResponseException::factory($request, $response);
     $httpException = HttpException::factory($prevException);
     $this->assertEquals($description, $httpException->getDescription());
 }
 /**
  * @expectedException PHPUnit_Framework_Error
  * @expectedExceptionMessage GET http://www.example.com/ - 503 Service Unavailable
  */
 public function testAddsDebugLoggerWhenSetToDebug()
 {
     list($config, $plugin, $resolver) = $this->getMocks();
     $config->set(Options::BACKOFF_LOGGER, 'debug');
     $client = $this->getMock('Aws\\Common\\Client\\DefaultClient', array(), array(), '', false);
     $resolver->resolve($config, $client);
     $listeners = $plugin->getEventDispatcher()->getListeners();
     $this->assertArrayHasKey('plugins.backoff.retry', $listeners);
     $plugin->dispatch('plugins.backoff.retry', array('request' => RequestFactory::getInstance()->create('GET', 'http://www.example.com'), 'response' => new Response(503), 'retries' => 3, 'delay' => 2));
 }
 /**
  * @return array
  */
 protected function getMocks()
 {
     $that = $this;
     $logger = new ClosureLogAdapter(function ($message) use($that) {
         $that->message .= $message . "\n";
     });
     $logPlugin = new BackoffLogger($logger);
     $response = new Response(503);
     $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com', array('Content-Length' => 3, 'Foo' => 'Bar'));
     return array($logPlugin, $request, $response);
 }
 /**
  * @param Response $response
  * @param string $path
  * @throws UnexpectedValueException
  * @return UnifiedRequest
  */
 private function parseRequestFromResponse(Response $response, $path)
 {
     try {
         $requestInfo = Util::deserialize($response->getBody());
     } catch (UnexpectedValueException $e) {
         throw new UnexpectedValueException(sprintf('Cannot deserialize response from "%s": "%s"', $path, $response->getBody()), null, $e);
     }
     $request = RequestFactory::getInstance()->fromMessage($requestInfo['request']);
     $params = $this->configureRequest($request, $requestInfo['server'], isset($requestInfo['enclosure']) ? $requestInfo['enclosure'] : []);
     return new UnifiedRequest($request, $params);
 }
Пример #14
0
 /**
  * @covers Guzzle\Http\Plugin\AsyncPlugin::onRequestTimeout
  */
 public function testMasksCurlExceptions()
 {
     $p = new AsyncPlugin();
     $request = RequestFactory::getInstance()->create('PUT', 'http://www.example.com');
     $e = new CurlException('Error');
     $event = new Event(array('request' => $request, 'exception' => $e));
     $p->onRequestTimeout($event);
     $this->assertEquals(RequestInterface::STATE_COMPLETE, $request->getState());
     $this->assertEquals(200, $request->getResponse()->getStatusCode());
     $this->assertTrue($request->getResponse()->hasHeader('X-Guzzle-Async'));
 }
 /**
  * @covers Guzzle\Service\Command\ClosureCommand::prepare
  * @covers Guzzle\Service\Command\ClosureCommand::build
  */
 public function testExecutesClosure()
 {
     $c = new ClosureCommand(array('closure' => function ($command, $api) {
         $command->set('testing', '123');
         $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
         return $request;
     }));
     $client = $this->getServiceBuilder()->get('mock');
     $c->setClient($client)->prepare();
     $this->assertEquals('123', $c->get('testing'));
     $this->assertEquals('http://www.test.com/', $c->getRequest()->getUrl());
 }
Пример #16
0
 public function testAddsHeader()
 {
     $plugin = new AuthenticationPlugin('foo');
     $dispatcher = new EventDispatcher();
     $dispatcher->addSubscriber($plugin);
     $request = RequestFactory::getInstance()->create('POST', 'http://www.example.com');
     $event = new Event(array('request' => $request));
     $dispatcher->dispatch('request.before_send', $event);
     $headers = $event['request']->getHeaders();
     $this->assertArrayHasKey('helthe-api-key', $headers);
     $this->assertEquals('foo', $headers['helthe-api-key']);
 }
 /**
  * @param Response $response
  * @param string $path
  * @throws UnexpectedValueException
  * @return UnifiedRequest
  */
 private function parseRequestFromResponse(Response $response, $path)
 {
     // @codingStandardsIgnoreStart
     $requestInfo = @unserialize($response->getBody());
     // @codingStandardsIgnoreEnd
     if ($requestInfo === false) {
         throw new UnexpectedValueException(sprintf('Cannot deserialize response from "%s": "%s"', $path, $response->getBody()));
     }
     $request = RequestFactory::getInstance()->fromMessage($requestInfo['request']);
     $params = $this->configureRequest($request, $requestInfo['server']);
     return new UnifiedRequest($request, $params);
 }
 public function testAppendsStringsToUserAgentHeader()
 {
     $this->assertInternalType('array', UserAgentListener::getSubscribedEvents());
     $listener = new UserAgentListener();
     $request = RequestFactory::getInstance()->create('GET', 'http://www.foo.com', array('User-Agent' => 'Aws/Foo Baz/Bar'));
     $command = $this->getMockBuilder('Aws\\Common\\Command\\JsonCommand')->setMethods(array('getRequest'))->getMock();
     $command->expects($this->any())->method('getRequest')->will($this->returnValue($request));
     $command->add(UserAgentListener::OPTION, 'Test/123')->add(UserAgentListener::OPTION, 'Other/456');
     $event = new Event(array('command' => $command));
     $listener->onBeforeSend($event);
     $this->assertEquals('Aws/Foo Baz/Bar Test/123 Other/456', (string) $request->getHeader('User-Agent'));
 }
Пример #19
0
 /**
  * Client constructor
  *
  * @param string           $baseUrl Base URL of the web service
  * @param array|Collection $config  Configuration settings
  */
 public function __construct($baseUrl = '', $config = null)
 {
     $this->setConfig($config ?: new Collection());
     $this->initSsl();
     $this->setBaseUrl($baseUrl);
     $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)) {
         $this->addSubscriber(new RedirectPlugin());
     }
     // Set the default User-Agent on the client
     $this->userAgent = $this->getDefaultUserAgent();
 }
Пример #20
0
 public function __construct($baseUrl = '', $config = null)
 {
     if (!extension_loaded('curl')) {
         throw new RuntimeException('The PHP cURL extension must be installed to use Guzzle.');
     }
     $this->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());
     }
 }
Пример #21
0
 /**
  * @param string           $baseUrl Base URL of the web service
  * @param array|Collection $config  Configuration settings
  */
 public function __construct($baseUrl = '', $config = null)
 {
     if (!extension_loaded('curl')) {
         throw new RuntimeException('The PHP cURL extension must be installed to use Guzzle.');
     }
     $this->setConfig($config ?: new Collection());
     $this->initSsl();
     $this->setBaseUrl($baseUrl);
     $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)) {
         $this->addSubscriber(new RedirectPlugin());
     }
     // Set the default User-Agent on the client
     $this->userAgent = $this->getDefaultUserAgent();
 }
Пример #22
0
 /**
  * @dataProvider testSuiteProvider
  * @covers Aws\Common\Signature\SignatureV3
  */
 public function testSignsRequestsProperly($request, $stringToSign, $header)
 {
     // Create a request based on the request
     $request = RequestFactory::getInstance()->fromMessage($request);
     // Sanitize the request
     $request->removeHeader('User-Agent')->removeHeader('Content-Length');
     // Sign the request using the test credentials
     $credentials = new Credentials(self::DEFAULT_KEY, self::DEFAULT_SECRET);
     // Get a mock signature object
     $signature = $this->getSignature();
     // Sign the request
     $signature->signRequest($request, $credentials);
     // Test that the string to sign is correct
     $this->assertEquals($stringToSign, $request->getParams()->get('aws.string_to_sign'));
     // Test that the signature is correct
     $this->assertEquals($header, (string) $request->getHeader('x-amzn-authorization'));
 }
 /**
  * @dataProvider testSuiteProvider
  * @covers Aws\Common\Signature\SignatureV3Https
  */
 public function testSignsRequestsProperly($request)
 {
     // Create a request based on the request
     $request = RequestFactory::getInstance()->fromMessage($request);
     // Sanitize the request
     $request->removeHeader('User-Agent')->removeHeader('Content-Length');
     // Sign the request using the test credentials
     $credentials = new Credentials(self::DEFAULT_KEY, self::DEFAULT_SECRET);
     // Get a mock signature object
     $signature = $this->getSignature();
     // Sign the request
     $signature->signRequest($request, $credentials);
     // Test that the string to sign is correct
     $stringToSign = self::DEFAULT_DATETIME;
     $this->assertEquals($stringToSign, $request->getParams()->get('aws.string_to_sign'));
     // Test that the signature is correct
     $expectedHeader = 'AWS3-HTTPS AWSAccessKeyId=AKIDEXAMPLE,Algorithm=HmacSHA256,Signature=2xkne78+c4e7JzUxDAADvn9vECImgCcEaBDkYw3Wk+w=';
     $this->assertEquals($expectedHeader, $request->getHeader('x-amzn-authorization', true));
 }
Пример #24
0
 /**
  * Client constructor
  *
  * @param string           $baseUrl Base URL of the web service
  * @param array|Collection $config  Configuration settings
  */
 public function __construct($baseUrl = '', $config = null)
 {
     $this->setConfig($config ?: new Collection());
     // Allow ssl.certificate_authority config setting to control the certificate authority used by curl
     $authority = $this->config->get(self::SSL_CERT_AUTHORITY);
     // Use the system's cacert if in a phar (curl can't read from a phar stream wrapper)
     if (strpos(__FILE__, 'phar://') === false && $authority === true) {
         $authority = 'system';
     }
     // Set the config setting to system to use the certificate authority bundle on your system
     if ($authority !== 'system') {
         $this->setSslVerification($authority !== null ? $authority : true);
     }
     $this->setBaseUrl($baseUrl);
     $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)) {
         $this->addSubscriber(new RedirectPlugin());
     }
 }
Пример #25
0
 /**
  * @dataProvider testSuiteProvider
  * @covers Aws\Common\Signature\SignatureV2
  */
 public function testSignsRequestsProperly($request, $stringToSign, $postFields, $mocksignature)
 {
     // Create a request based on the request
     $request = RequestFactory::getInstance()->fromMessage($request);
     if (!empty($postFields)) {
         $request->addPostFields($postFields);
     }
     // Sanitize the request
     $request->removeHeader('User-Agent')->removeHeader('Content-Length');
     // Sign the request using the test credentials
     $credentials = new Credentials(self::DEFAULT_KEY, self::DEFAULT_SECRET);
     // Get a mock signature object
     $signature = $this->getSignature();
     // Sign the request
     $signature->signRequest($request, $credentials);
     // Test that the string to sign is correct
     $this->assertEquals($stringToSign, $request->getParams()->get('aws.string_to_sign'));
     // Test that the signature is correct
     if (!empty($postFields)) {
         $this->assertEquals($mocksignature, $request->getPostField('Signature'));
     } else {
         $this->assertEquals($mocksignature, $request->getQuery()->get('Signature'));
     }
 }
Пример #26
0
 /**
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::setBody
  * @covers Guzzle\Http\Message\EntityEnclosingRequest::processPostFields
  */
 public function testCanSendMultipleRequestsUsingASingleRequestObject()
 {
     $this->getServer()->flush();
     $this->getServer()->enqueue(array("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", "HTTP/1.1 201 Created\r\nContent-Length: 0\r\n\r\n"));
     // Send the first request
     $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl())->setBody('test')->setClient(new Client());
     $request->send();
     $this->assertEquals(200, $request->getResponse()->getStatusCode());
     // Send the second request
     $request->setBody('abcdefg', 'application/json', false);
     $request->send();
     $this->assertEquals(201, $request->getResponse()->getStatusCode());
     // Ensure that the same request was sent twice with different bodies
     $requests = $this->getServer()->getReceivedRequests(true);
     $this->assertEquals(2, count($requests));
     $this->assertEquals(4, $requests[0]->getHeader('Content-Length', true));
     $this->assertEquals(7, $requests[1]->getHeader('Content-Length', true));
 }
Пример #27
0
 protected function getRequest()
 {
     return RequestFactory::getInstance()->create('POST', 'http://www.test.com/path?a=b&c=d', null, array('e' => 'f'));
 }
Пример #28
0
 public function testCanSetDefaultHeadersOptions()
 {
     $request = new Request('GET', 'http://www.foo.com', array('Foo' => 'Bar'));
     RequestFactory::getInstance()->applyOptions($request, array('headers' => array('Foo' => 'Baz', 'Bam' => 't123')), RequestFactory::OPTIONS_AS_DEFAULTS);
     $this->assertEquals('Bar', (string) $request->getHeader('Foo'));
     $this->assertEquals('t123', (string) $request->getHeader('Bam'));
 }
 public function testAddsCustomCurlOptions()
 {
     $request = RequestFactory::getInstance()->create('PUT', $this->getServer()->getUrl());
     $request->getCurlOptions()->set(CURLOPT_TIMEOUT, 200);
     $handle = CurlHandle::factory($request);
     $this->assertEquals(200, $handle->getOptions()->get(CURLOPT_TIMEOUT));
 }
 /**
  * @covers Guzzle\Http\Curl\CurlMulti
  */
 public function testRemovesQueuedRequests()
 {
     $request = RequestFactory::getInstance()->create('GET', 'http://127.0.0.1:9876/');
     $request->setClient(new Client());
     $request->setResponse(new Response(200), true);
     $this->multi->add($request);
     $this->multi->send();
     $this->assertTrue($this->mock->has(CurlMulti::ADD_REQUEST));
     $this->assertTrue($this->mock->has(CurlMulti::POLLING) === false);
     $this->assertTrue($this->mock->has(CurlMulti::COMPLETE) !== false);
 }