Example #1
0
 public function parseRequest($data)
 {
     list($headers, $bodyBuffer) = explode("\r\n\r\n", $data, 2);
     $factory = new RequestFactory();
     $parsed = $factory->parseMessage($headers . "\r\n\r\n");
     $parsedQuery = array();
     if (0 === strpos($parsed['parts']['query'], '?')) {
         $query = substr($parsed['parts']['query'], 1);
         parse_str($query, $parsedQuery);
     }
     $request = new Request($parsed['method'], $parsed['parts']['path'], $parsedQuery, $parsed['protocol_version'], $parsed['headers']);
     return array($request, $bodyBuffer);
 }
 /**
  * @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()));
     }
 }
 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;
         }
     }
 }
Example #5
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;
 }
Example #6
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());
 }
Example #7
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());
 }
Example #8
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));
 }
 /**
  * {@inheritdoc}
  */
 public function create($method, $url, $headers = null, $body = null, array $options = array())
 {
     /** @var Request $request */
     $request = parent::create($method, $url, $headers, $body);
     $request->getQuery()->setAggregator(new DuplicateAggregator());
     return $request;
 }
Example #10
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);
 }
Example #11
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'));
 }
Example #12
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));
 }
 /**
  * {@inheritdoc}
  */
 public function create($method, $url, $headers = null, $body = null, array $options = array())
 {
     /** @var RequestInterface $request */
     $request = parent::create($method, $url, $headers, $body, $options);
     // Java web services do not expect [] behind multi-valued query string parameter names.
     // PHP: foo[]=1&foo[]=2
     // Java: foo=1&foo=2
     $request->getQuery()->setAggregator(new DuplicateAggregator());
     return $request;
 }
Example #15
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'));
 }
 /**
  * @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);
 }
Example #18
0
 public function testUrl()
 {
     $app = $this->getApp();
     if ($app['deprecated.php']) {
         $factory = new RequestFactory();
         $request = $factory->create('GET', '/');
         $response = new V3Response('200');
         $guzzle = $this->getMock('Guzzle\\Service\\Client', array('get', 'send'));
         $request->setClient($guzzle);
         $guzzle->expects($this->once())->method('send')->will($this->returnValue($response));
     } else {
         $factory = new MessageFactory();
         $request = $factory->createRequest('GET', '/');
         $response = new Response('200');
         $guzzle = $this->getMock('GuzzleHttp\\Client', array('get'));
     }
     $guzzle->expects($this->once())->method('get')->with('http://loripsum.net/api/1/veryshort')->will($this->returnValue($request));
     $app['guzzle.client'] = $guzzle;
     $app['prefill']->get('/1/veryshort');
 }
 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);
 }
 /**
  * @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());
 }
 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'));
 }
 /**
  * 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();
 }
Example #24
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());
     }
 }
 /**
  * @covers Guzzle\Aws\QueryStringAuthPlugin
  */
 public function testAddsQueryStringAuth()
 {
     $signature = new SignatureV2('a', 'b');
     $plugin = new QueryStringAuthPlugin($signature, '2009-04-15');
     $this->assertSame($signature, $plugin->getSignature());
     $this->assertEquals('2009-04-15', $plugin->getApiVersion());
     $request = RequestFactory::get('http://www.test.com/');
     $request->getEventManager()->attach($plugin);
     $request->getEventManager()->notify('request.before_send');
     $qs = $request->getQuery();
     $this->assertTrue($qs->hasKey('Timestamp') !== false);
     $this->assertEquals('2009-04-15', $qs->get('Version'));
     $this->assertEquals('2', $qs->get('SignatureVersion'));
     $this->assertEquals('HmacSHA256', $qs->get('SignatureMethod'));
     $this->assertEquals('a', $qs->get('AWSAccessKeyId'));
 }
 /**
  * @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'));
 }
 /**
  * @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();
 }
 /**
  * @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));
 }
 /**
  * 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());
     }
 }
Example #30
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'));
     }
 }