Esempio n. 1
0
 /**
  * @param ResponseInterface $response
  *
  * @return ApiResult
  */
 protected function _getResult($response)
 {
     if (!$response instanceof ResponseInterface) {
         throw new \InvalidArgumentException("{$response} should be an instance of ResponseInterface");
     }
     $result = new ApiResult();
     $result->setStatusCode($response->getStatusCode());
     $callId = $response->getHeader('X-Call-Id');
     if (!empty($callId)) {
         $result->setCallId($callId);
     }
     $decoded = json_decode((string) $response->getBody());
     if (isset($decoded->meta) && isset($decoded->data) && isset($decoded->meta->code) && $decoded->meta->code == $response->getStatusCode()) {
         $meta = $decoded->meta;
         $data = $decoded->data;
         if (isset($meta->message)) {
             $result->setStatusMessage($meta->message);
         }
         $result->setContent(json_encode($data));
     } else {
         $result->setContent((string) $response->getBody());
     }
     $result->setHeaders($response->getHeaders());
     return $result;
 }
Esempio n. 2
0
 public function save(RequestInterface $request, ResponseInterface $response)
 {
     $ttl = (int) $request->getConfig()->get('cache.ttl');
     $key = $this->getCacheKey($request);
     // Persist the response body if needed
     if ($response->getBody() && $response->getBody()->getSize() > 0) {
         $this->cache->save($key, array('code' => $response->getStatusCode(), 'headers' => $response->getHeaders(), 'body' => (string) $response->getBody()), $ttl);
         $request->getConfig()->set('cache.key', $key);
     }
 }
Esempio n. 3
0
 /**
  * @Then The CalDAV HTTP status code should be :code
  */
 public function theCaldavHttpStatusCodeShouldBe($code)
 {
     if ((int) $code !== $this->response->getStatusCode()) {
         throw new \Exception(sprintf('Expected %s got %s', (int) $code, $this->response->getStatusCode()));
     }
     $body = $this->response->getBody()->getContents();
     if ($body && substr($body, 0, 1) === '<') {
         $reader = new Sabre\Xml\Reader();
         $reader->xml($body);
         $this->responseXml = $reader->parse();
     }
 }
 /**
  * @param RequestInterface|ResponseInterface $message
  * @return string
  */
 protected function formatBody($message)
 {
     $header = $message->getHeader('Content-Type');
     if (JsonStringFormatter::isJsonHeader($header)) {
         $formatter = new JsonStringFormatter();
         return $formatter->format($message->getBody());
     } elseif (XmlStringFormatter::isXmlHeader($header)) {
         $formatter = new XmlStringFormatter();
         return $formatter->format($message->getBody());
     }
     $factory = new StringFactoryFormatter();
     return $factory->format($message->getBody());
 }
 protected function setStatusTestingApp($enabled)
 {
     $this->sendingTo($enabled ? 'post' : 'delete', '/cloud/apps/testing');
     $this->theHTTPStatusCodeShouldBe('200');
     $this->theOCSStatusCodeShouldBe('100');
     $this->sendingTo('get', '/cloud/apps?filter=enabled');
     $this->theHTTPStatusCodeShouldBe('200');
     if ($enabled) {
         PHPUnit_Framework_Assert::assertContains('testing', $this->response->getBody()->getContents());
     } else {
         PHPUnit_Framework_Assert::assertNotContains('testing', $this->response->getBody()->getContents());
     }
 }
 /**
  * @throws HttpException
  */
 protected function handleError()
 {
     $body = (string) $this->response->getBody();
     $code = (int) $this->response->getStatusCode();
     $content = json_decode($body);
     throw new HttpException(isset($content->message) ? $content->message : 'Request not processed.', $code);
 }
Esempio n. 7
0
 public function decode(ResponseInterface $raw, $totalTime = 0)
 {
     $executionTime = $callTime = 0;
     if ($raw->hasHeader('X-Execution-Time')) {
         $executionTime = $raw->getHeader('X-Execution-Time');
     }
     if ($raw->hasHeader('X-Call-Time')) {
         $callTime = $raw->getHeader('X-Call-Time');
     }
     $body = '';
     try {
         $body = (string) $raw->getBody();
         $result = $this->_getDecoder()->decode($body, self::FORMAT, $this->_getDecodeContext());
     } catch (\Exception $e) {
         if (!empty($body)) {
             $body = ' (' . $body . ')';
         }
         error_log("Invalid API Response: " . $body);
         throw new InvalidApiResponseException("Unable to decode raw api response.", 500, $e);
     }
     if (!property_exists($result, 'type') || !property_exists($result, 'status') || !property_exists($result, 'result') || !property_exists($result->status, 'message') || !property_exists($result->status, 'code')) {
         error_log("Invalid API Result: " . json_encode($result));
         throw new InvalidApiResponseException("Invalid api result", 500);
     }
     if ($executionTime === 0) {
         $executionTime = $totalTime;
     }
     if ($callTime === 0) {
         $callTime = $executionTime;
     }
     return ResponseBuilder::create(ApiCallData::create($result->type, $result->result, $result->status->code, $result->status->message, (double) str_replace([',', 'ms'], '', $totalTime), (double) str_replace([',', 'ms'], '', $executionTime), (double) str_replace([',', 'ms'], '', $callTime)));
 }
 /**
  * Decode an HTTP Response.
  * @static
  * @throws Google_Service_Exception
  * @param GuzzleHttp\Message\RequestInterface $response The http response to be decoded.
  * @param GuzzleHttp\Message\ResponseInterface $response
  * @return mixed|null
  */
 public static function decodeHttpResponse(ResponseInterface $response, RequestInterface $request = null)
 {
     $body = (string) $response->getBody();
     $code = $response->getStatusCode();
     $result = null;
     // return raw response when "alt" is "media"
     $isJson = !($request && 'media' == $request->getQuery()->get('alt'));
     // set the result to the body if it's not set to anything else
     if ($isJson) {
         try {
             $result = $response->json();
         } catch (ParseException $e) {
             $result = $body;
         }
     } else {
         $result = $body;
     }
     // retry strategy
     if (intVal($code) >= 300) {
         $errors = null;
         // Specific check for APIs which don't return error details, such as Blogger.
         if (isset($result['error']) && isset($result['error']['errors'])) {
             $errors = $result['error']['errors'];
         }
         throw new Google_Service_Exception($body, $code, null, $errors);
     }
     return $result;
 }
Esempio n. 9
0
    /**
     * Returns all tags for a given user
     *
     * @param string $user
     * @return array
     */
    private function requestTagsForUser($user)
    {
        try {
            $request = $this->client->createRequest('PROPFIND', $this->baseUrl . '/remote.php/dav/systemtags/', ['body' => '<?xml version="1.0"?>
<d:propfind  xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">
  <d:prop>
    <oc:id />
    <oc:display-name />
    <oc:user-visible />
    <oc:user-assignable />
  </d:prop>
</d:propfind>', 'auth' => [$user, $this->getPasswordForUser($user)], 'headers' => ['Content-Type' => 'application/json']]);
            $this->response = $this->client->send($request);
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            $this->response = $e->getResponse();
        }
        $tags = [];
        $service = new Sabre\Xml\Service();
        $parsed = $service->parse($this->response->getBody()->getContents());
        foreach ($parsed as $entry) {
            $singleEntry = $entry['value'][1]['value'][0]['value'];
            if (empty($singleEntry[0]['value'])) {
                continue;
            }
            $tags[$singleEntry[0]['value']] = ['display-name' => $singleEntry[1]['value'], 'user-visible' => $singleEntry[2]['value'], 'user-assignable' => $singleEntry[3]['value']];
        }
        return $tags;
    }
 function it_should_make_post_request(ResponseInterface $responce)
 {
     $responce->getHeader("Content-Type")->willReturn('blablaxmlblabla');
     $responce->getBody()->willReturn('<xml></xml>');
     $this->client->post(Argument::any(), Argument::any())->willReturn($responce);
     $responce->xml()->willReturn(new \SimpleXMLElement('<xml></xml>'));
     $this->post(Argument::type('string'))->shouldBeAnInstanceOf('Bxav\\Component\\ResellerClub\\Model\\XmlResponse');
 }
Esempio n. 11
0
 /**
  * @param ResponseInterface $response raw json response
  * @param bool              $throw    Should throw API errors as exceptions
  *
  * @throws \Exception
  */
 public function __construct(ResponseInterface $response = null, $throw = true)
 {
     if ($response !== null) {
         $this->_executionTime = $response->getHeader('X-Execution-Time');
         $this->_callTime = $response->getHeader('X-Call-Time');
         $this->readJson((string) $response->getBody(), $throw);
     }
 }
 function it_should_return_a_service_response_when_verifying_an_ipn_message(Client $httpClient, Message $message, ResponseInterface $response)
 {
     $response->getBody()->willReturn('foo');
     $httpClient->post(Argument::type('string'), Argument::type('array'))->willReturn($response);
     $message->getAll()->willReturn(['foo' => 'bar']);
     $response = $this->verifyIpnMessage($message);
     $response->shouldHaveType('Mdb\\PayPal\\Ipn\\ServiceResponse');
     $response->getBody()->shouldReturn('foo');
 }
Esempio n. 13
0
 /**
  * @param ResponseInterface|Response6Interface $response
  *
  * @return string
  *
  * @throws CommunicationException
  */
 public static function getRawResponseBody($response)
 {
     $statusCode = $response->getStatusCode();
     $rawResponse = $response->getBody()->getContents();
     if ($statusCode != 200) {
         throw CommunicationException::createFromHTTPResponse($statusCode, $rawResponse);
     }
     return $rawResponse;
 }
 /**
  * @throws ApiException
  */
 protected function handleError($getCode = false)
 {
     $code = (int) $this->response->getStatusCode();
     if ($getCode) {
         return $code;
     }
     $content = (string) $this->response->getBody();
     $this->reportError($code, $content);
 }
 /**
  * @param \GuzzleHttp\Message\ResponseInterface $response
  * @return Language[]
  */
 public function processResponse(\GuzzleHttp\Message\ResponseInterface $response)
 {
     $xml = simplexml_load_string($response->getBody()->getContents());
     $languages = [];
     foreach ($xml->string as $language) {
         $languages[] = new Language($language);
     }
     return $languages;
 }
Esempio n. 16
0
 private function getExpected(ResponseInterface $response)
 {
     if (!($body = $response->getBody())) {
         return false;
     } elseif ($response->hasHeader('Transfer-Encoding') || $response->hasHeader('Content-Encoding')) {
         // Currently does not support un-gzipping or inflating responses
         return false;
     }
     return call_user_func($this->expectedFn, $response);
 }
Esempio n. 17
0
 /**
  * @param ResponseInterface|Response6Interface $response
  *
  * @return string
  *
  * @throws CommunicationException
  */
 public static function getRawResponseBody($response)
 {
     $statusCode = $response->getStatusCode();
     $rawResponse = $response->getBody()->getContents();
     if ($statusCode != 200) {
         throw new CommunicationException("StatusCode: {$statusCode}, Contents: {$rawResponse}", CommunicationException::GENERAL_HTTP_ERROR);
     }
     static::checkForErrors($rawResponse);
     return $rawResponse;
 }
Esempio n. 18
0
 /**
  * Create the response object
  *
  * @param  ResponseInterface         $adapterResponse
  * @return \Tmdb\HttpClient\Response
  */
 private function createResponse(ResponseInterface $adapterResponse = null)
 {
     $response = new Response();
     if ($adapterResponse !== null) {
         $response->setCode($adapterResponse->getStatusCode());
         $response->setHeaders(new ParameterBag($adapterResponse->getHeaders()));
         $response->setBody((string) $adapterResponse->getBody());
     }
     return $response;
 }
Esempio n. 19
0
 /**
  * @When :user requests addressbook :addressBook with statuscode :statusCode
  */
 public function requestsAddressbookWithStatuscode($user, $addressBook, $statusCode)
 {
     $davUrl = $this->baseUrl . '/remote.php/dav/addressbooks/users/' . $addressBook;
     $password = $user === 'admin' ? 'admin' : '123456';
     try {
         $this->response = $this->client->get($davUrl, ['auth' => [$user, $password]]);
     } catch (\GuzzleHttp\Exception\ClientException $e) {
         $this->response = $e->getResponse();
     }
     if ((int) $statusCode !== $this->response->getStatusCode()) {
         throw new \Exception(sprintf('Expected %s got %s', (int) $statusCode, $this->response->getStatusCode()));
     }
     $body = $this->response->getBody()->getContents();
     if (substr($body, 0, 1) === '<') {
         $reader = new Sabre\Xml\Reader();
         $reader->xml($body);
         $this->responseXml = $reader->parse();
     }
 }
Esempio n. 20
0
 public function parse(ResponseInterface $response)
 {
     $collection = new Collection();
     if (!$response->getBody()) {
         return $collection;
     }
     // help bad responses be more multipart compliant
     $body = "\r\n" . $response->getBody()->__toString() . "\r\n";
     // multipart
     preg_match('/boundary\\=\\"(.*?)\\"/', $response->getHeader('Content-Type'), $matches);
     if (isset($matches[1])) {
         $boundary = $matches[1];
     } else {
         preg_match('/boundary\\=(.*?)(\\s|$|\\;)/', $response->getHeader('Content-Type'), $matches);
         $boundary = $matches[1];
     }
     // strip quotes off of the boundary
     $boundary = preg_replace('/^\\"(.*?)\\"$/', '\\1', $boundary);
     // clean up the body to remove a reamble and epilogue
     $body = preg_replace('/^(.*?)\\r\\n--' . $boundary . '\\r\\n/', "\r\n--{$boundary}\r\n", $body);
     // make the last one look like the rest for easier parsing
     $body = preg_replace('/\\r\\n--' . $boundary . '--/', "\r\n--{$boundary}\r\n", $body);
     // cut up the message
     $multi_parts = explode("\r\n--{$boundary}\r\n", $body);
     // take off anything that happens before the first boundary (the preamble)
     array_shift($multi_parts);
     // take off anything after the last boundary (the epilogue)
     array_pop($multi_parts);
     $message_parser = new MessageParser();
     $parser = new Single();
     // go through each part of the multipart message
     foreach ($multi_parts as $part) {
         // get Guzzle to parse this multipart section as if it's a whole HTTP message
         $parts = $message_parser->parseResponse("HTTP/1.1 200 OK\r\n" . $part);
         // now throw this single faked message through the Single GetObject response parser
         $single = new Response($parts['code'], $parts['headers'], Stream::factory($parts['body']));
         $obj = $parser->parse($single);
         // add information about this multipart to the returned collection
         $collection->push($obj);
     }
     return $collection;
 }
Esempio n. 21
0
 protected function getResponse(GuzzleResponse $response)
 {
     if (strpos($response->getHeader('Content-Type'), 'json')) {
         $returnResponse = new JsonResponse($response->getBody());
     } elseif (strpos($response->getHeader('Content-Type'), 'xml')) {
         $returnResponse = new XmlResponse($response->xml());
     } else {
         throw new \Exception('Unknow return type');
     }
     return $returnResponse;
 }
Esempio n. 22
0
 public function __invoke(ResponseInterface $response)
 {
     $code = (string) $response->getStatusCode();
     $data = ['type' => $code[0] == '4' ? 'client' : 'server', 'request_id' => null, 'code' => null, 'message' => null, 'parsed' => null];
     if ($body = $response->getBody()) {
         $this->parseBody(new \SimpleXMLElement($body), $data);
     } else {
         $this->parseHeaders($response, $data);
     }
     return $data;
 }
Esempio n. 23
0
 /**
  * @param GuzzleResponseInterface $response
  */
 public function __construct(GuzzleResponseInterface $response)
 {
     $this->response = $response;
     $this->body = json_decode($response->getBody());
     $this->errorCode = (int) $this->popField('errorCode');
     $this->errorMessage = $this->popField('errorMessage');
     $this->errorDetails = $this->popField('errorDetails');
     $this->statusCode = (int) $this->popField('statusCode');
     $this->statusReason = $this->popField('statusReason');
     $this->callId = $this->popField('callId');
     $this->time = DateTimeImmutable::createFromFormat(DateTime::ATOM, $this->popField('time'));
 }
Esempio n. 24
0
 public function parse(ResponseInterface $response)
 {
     $headers = $response->getHeaders();
     $obj = new Object();
     $obj->setContent($response->getBody() ? $response->getBody()->__toString() : null);
     $obj->setContentDescription(\array_get($headers, 'Content-Description', [null])[0]);
     $obj->setContentSubDescription(\array_get($headers, 'Content-Sub-Description', [null])[0]);
     $obj->setContentId(\array_get($headers, 'Content-ID', [null])[0]);
     $obj->setObjectId(\array_get($headers, 'Object-ID', [null])[0]);
     $obj->setContentType(\array_get($headers, 'Content-Type', [null])[0]);
     $obj->setLocation(\array_get($headers, 'Location', [null])[0]);
     $obj->setMimeVersion(\array_get($headers, 'MIME-Version', [null])[0]);
     $obj->setPreferred(\array_get($headers, 'Preferred', [null])[0]);
     if ($this->isError($response)) {
         $xml = $response->xml();
         $error = new RETSError();
         $error->setCode((string) \array_get($xml, 'ReplyCode'));
         $error->setMessage((string) \array_get($xml, 'ReplyText'));
         $obj->setError($error);
     }
     return $obj;
 }
 /**
  * @param \GuzzleHttp\Message\ResponseInterface       $response
  * @param \GuzzleHttp\Message\MessageParser           $parser
  * @param \GuzzleHttp\Message\MessageFactoryInterface $messageFactory
  */
 public function __construct(ResponseInterface $response, MessageParser $parser = null, MessageFactoryInterface $messageFactory = null)
 {
     $matches = null;
     $body = $response->getBody();
     $header = $response->getHeader('Content-Type');
     if (!preg_match('/boundary=(.*)$/', $header, $matches) || !isset($matches[1])) {
         throw new InvalidArgumentException("Unable to parse boundary from content type : '{$header}'");
     }
     $this->response = $response;
     $this->parser = $parser ?: new MessageParser();
     $this->factory = $messageFactory ?: new MessageFactory();
     $this->iterator = new MultipartStreamIterator($body, $matches[1]);
 }
Esempio n. 26
0
 /**
  * Checks that response body contains JSON from PyString.
  *
  * Do not check that the response body /only/ contains the JSON from PyString,
  *
  * @param PyStringNode $jsonString
  *
  * @throws \RuntimeException
  *
  * @Then /^(?:the )?response should contain json:$/
  */
 public function theResponseShouldContainJson(PyStringNode $jsonString)
 {
     $etalon = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true);
     $actual = json_decode((string) $this->response->getBody(), true);
     if (null === $etalon) {
         throw new \RuntimeException("Can not convert etalon to json:\n" . $this->replacePlaceHolder($jsonString->getRaw()));
     }
     Assertions::assertGreaterThanOrEqual(count($etalon), count($actual));
     foreach ($etalon as $key => $needle) {
         Assertions::assertArrayHasKey($key, $actual);
         Assertions::assertEquals($etalon[$key], $actual[$key]);
     }
 }
Esempio n. 27
0
 /**
  * @param CompleteEvent $event
  *
  * @throws \RuntimeException|ExceptionInterface
  */
 protected function handleResponse(CompleteEvent $event)
 {
     $this->response = $event->getResponse();
     if ($this->response->getStatusCode() >= 200 && $this->response->getStatusCode() <= 299) {
         return;
     }
     $body = $this->response->getBody();
     $code = $this->response->getStatusCode();
     if ($this->exception) {
         throw $this->exception->create($body, $code);
     }
     $content = $this->response->json();
     throw new \RuntimeException(sprintf('[%d] %s (%s)', $code, $content->message, $content->id), $code);
 }
 function let(SiteConfigBuilder $siteConfigBuilder, SiteConfig $siteConfig, Factory $authenticatorFactory, ClientInterface $guzzle, Emitter $emitter, BeforeEvent $beforeEvent, CompleteEvent $completeEvent, RequestInterface $request, ResponseInterface $response, Factory $authenticatorFactory)
 {
     $siteConfig->getHost()->willReturn('example.com');
     $siteConfigBuilder->buildForHost('example.com')->willReturn($siteConfig);
     $guzzle->getEmitter()->willReturn($emitter);
     $request->getHost()->willReturn('example.com');
     $beforeEvent->getRequest()->willReturn($request);
     $beforeEvent->getClient()->willReturn($guzzle);
     $response->getBody()->willReturn('<html></html>');
     $completeEvent->getResponse()->willReturn($response);
     $completeEvent->getRequest()->willReturn($request);
     $completeEvent->getClient()->willReturn($guzzle);
     $this->beConstructedWith($siteConfigBuilder, $authenticatorFactory);
 }
 /**
  * @When I send a access token request
  */
 public function iMakeAAccessTokenRequest()
 {
     $url = $this->parameters['token_url'];
     $this->response = $this->getPostResponseFromUrl($url, $this->requestBody);
     $contentType = (string) $this->response->getHeader('Content-type');
     if ($contentType !== 'application/json') {
         throw new \Exception(sprintf("Content-type must be application/json %s", $this->echoLastResponse()));
     }
     $this->data = json_decode($this->response->getBody(true));
     $this->lastErrorJson = json_last_error();
     if ($this->lastErrorJson != JSON_ERROR_NONE) {
         throw new \Exception(sprintf("Error parsing response JSON " . "\n\n %s", $this->echoLastResponse()));
     }
 }
Esempio n. 30
-1
 /**
  * @Then The webdav checksum should be empty
  */
 public function theWebdavChecksumShouldBeEmpty()
 {
     $service = new Sabre\Xml\Service();
     $parsed = $service->parse($this->response->getBody()->getContents());
     /*
      * Fetch the checksum array
      * Maybe we want to do this a bit cleaner ;)
      */
     $status = $parsed[0]['value'][1]['value'][1]['value'];
     if ($status !== 'HTTP/1.1 404 Not Found') {
         throw new \Exception("Expected 'HTTP/1.1 404 Not Found', got " . $status);
     }
 }