public function testGetStatusCodeReturnsTheStatusCode() { $response = new Response(); $this->assertEquals($response->getStatusCode(), null); $response->addHeader('1.0 200 OK'); $this->assertEquals($response->getStatusCode(), 200); }
/** * @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); }
/** @dataProvider provideSetError */ public function testSetError($expected, $statusCode, $error, $error_description = null, $error_uri = null) { $response = new Response(); $response->setError($statusCode, $error, $error_description, $error_uri); $this->assertEquals($expected, $response->getContent()); $this->assertEquals($statusCode, $response->getStatusCode()); }
/** * @test * @param $url * @param $statusCode * @dataProvider redirectDataProvider */ public function testIfRedirectReturnsCorrectHttpCodeAndLocationHeader($url, $statusCode) { $response = new Response(); $response->redirect($url, $statusCode); $this->assertEquals($url, $response->headers->get('Location')); $this->assertEquals($statusCode, $response->getStatusCode()); }
/** * @throws HttpException */ protected function handleError() { $body = (string) $this->response->getBody(); $code = (int) $this->response->getStatusCode(); $content = json_decode($body); $error = $content->errors[0]; throw new HttpException(isset($error) ? $error->description : 'Request not processed.', $code); }
public function testResponseValues() { $resource = $this->prophesize(Resource::CLASS); $resource->asJson()->willReturn('foobar'); $response = new Response($resource->reveal()); $this->assertSame(200, $response->getStatusCode()); $this->assertSame('application/hal+json', $response->getHeaderLine('Content-Type')); $this->assertSame('foobar', (string) $response->getBody()); }
/** * {@inheritdoc} */ public function render(Request $request, Response $response) { if (!$this->environment->isSilent()) { header('HTTP/1.1 ' . $response->getStatusCode() . ' ' . $response->getStatusMessage()); foreach ($response->getHeaders() as $name => $value) { header($name . ': ' . $value); } } echo $this->createTemplate($response); }
/** * Terminates application. * * Renders content or excute redirecting * * @param Response $response */ public function terminate(Response $response) { if ($response->getRedirectUrl() === null) { header("Content-Type: {$response->getContentType()}; charset=utf-8"); http_response_code($response->getStatusCode()); $response->display(); } else { header("Location: {$response->getRedirectUrl()}"); } exit; }
/** * {@inheritdoc} */ public function validateResponse(Request $request, Response $response) : bool { if (Response::SWITCHING_PROTOCOLS !== $response->getStatusCode()) { return false; } if ('upgrade' !== strtolower($response->getHeader('Connection'))) { return false; } if ('websocket' !== strtolower($response->getHeader('Upgrade'))) { return false; } $key = $request->getHeader('Sec-WebSocket-Key'); if (!$response->hasHeader('Sec-WebSocket-Accept')) { return false; } return $this->responseKey($key) === $response->getHeader('Sec-WebSocket-Accept'); }
/** * Formats the specified response. * @param Response $response the response to be formatted. */ public function format($response) { $charset = $this->encoding === null ? $response->charset : $this->encoding; if (stripos($this->contentType, 'charset') === false) { $this->contentType .= '; charset=' . $charset; } $response->getHeaders()->set('Content-Type', $this->contentType); if ($response->data !== null) { $dom = new DOMDocument($this->version, $charset); $root = new DOMElement($this->rootTag); $result = new DOMElement($this->itemTag); $code = new DOMElement($this->itemTag); $status = new DOMElement($this->itemTag); $dom->appendChild($root); $code->appendChild($response->getStatusCode()); $status->appendChild($response->getIsSuccessful() ? 'success' : 'error'); $messageText = ''; if (!$response->getIsOk()) { $messageText = $response->statusText; } if (is_string($response->data)) { //For string result we send it like 'message' $messageText = $response->data; } elseif ($response->getIsClientError() && isset($response->data['message'])) { //For HttpExceptions we save message field only to 'message' $messageText = $response->data['message']; unset($response->data['message']); $result->appendChild($response->data); } else { //Otherwise send all as result $result->appendChild($response->data); } if ($messageText !== '') { $message = new DOMElement($this->itemTag); $message->appendChild($messageText); $root->appendChild($message); } $root->appendChild($result); $root->appendChild($code); $root->appendChild($status); $this->buildXml($root, $response->data); $response->content = $dom->saveXML(); } }
protected function send($method, $path, $options) { list($url, $headers, $body) = $this->buildRequest($path, $options); $curl = $this->getCurlHandle(); curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($curl, CURLOPT_USERAGENT, $this->user_agent); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_VERBOSE, !!$this->debug); if ($this->debug) { curl_setopt($curl, CURLOPT_STDERR, is_string($this->debug) ? fopen($this->debug, "a+") : STDOUT); } curl_setopt($curl, CURLOPT_HEADER, true); switch ($method) { case 'PUT': curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); break; case 'DELETE': curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; case 'POST': curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); break; case 'GET': curl_setopt($curl, CURLOPT_HTTPGET, true); break; } $raw_request_headers = []; foreach ($headers as $key => $value) { $raw_request_headers[] = "{$key}: {$value}"; } curl_setopt($curl, CURLOPT_HTTPHEADER, $raw_request_headers); curl_setopt($curl, CURLOPT_URL, $url); $result = curl_exec($curl); $curl_info = curl_getinfo($curl); list($header, $body) = explode("\r\n\r\n", $result, 2); if ($body && $this->debug) { if (is_string($this->debug)) { error_log("{$body}\n", 3, $this->debug); } else { fwrite(is_resource($this->debug) ? $this->debug : STDOUT, "{$body}\n"); } } $response = new Response($header, $body, $curl_info); if ($this->http_errors && $response->getStatusCode() >= 400) { $exception = new BadResponseException(); $exception->setResponse($response); throw $exception; } return $response; }
/** * Converts the HttpKernel response to a BrowserKit response. * * @param Response $response A Response instance * * @return Response A Response instance */ protected function filterResponse($response) { $headers = $response->headers->all(); if ($response->headers->getCookies()) { $cookies = array(); foreach ($response->headers->getCookies() as $cookie) { $cookies[] = new DomCookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); } $headers['Set-Cookie'] = $cookies; } // this is needed to support StreamedResponse ob_start(); $response->sendContent(); $content = ob_get_clean(); return new DomResponse($content, $response->getStatusCode(), $headers); }
/** * * @param TiiSubmission $submission */ public function replaceSubmission($submission) { $params_merge = $this->getResubmissionFormHash($submission); if (is_null($submission->getSubmissionDataPath()) && is_null($submission->getSubmissionDataUrl())) { $params_merge['custom_submission_data'] = $submission->getSubmissionDataText(); } else { if (is_null($submission->getSubmissionDataUrl())) { // CURL uploading with @ has been deprecated in PHP 5.5 if (class_exists('CURLFile')) { $finfo = new finfo(FILEINFO_MIME); $mimetype = $finfo->file($submission->getSubmissionDataPath()); $params_merge['custom_submission_data'] = new CurlFile($submission->getSubmissionDataPath(), $mimetype); } else { $params_merge['custom_submission_data'] = '@' . $submission->getSubmissionDataPath(); } } } $transport = $this->transportData($params_merge); $response = new Response($this); if ($response->getStatusCode() == 'failure') { throw new TurnitinSDKException($response->getStatusCode(), $response->getDescription()); } else { $dom = $response->getDomObject(); $tiiSubmission = new TiiSubmission(); $tiiSubmission->setSubmissionId($dom->getElementsByTagName('lis_result_sourcedid')->item(0)->nodeValue); $tiiSubmission->setTextExtract(@$dom->getElementsByTagName('submission_data_extract')->item(0)->nodeValue); $response->setSubmission($tiiSubmission); } return $response; }
/** * {@inheritdoc} */ public function encodeResponse(Response $response) : string { return sprintf("HTTP/%s %d %s\r\n%s\r\n", $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase(), $this->encodeHeaders($response->getHeaders())); }
public function testReturnsStatusCode() { $response = new Response('', 201); $this->assertSame(201, $response->getStatusCode()); }
/** * @param Response $response * * @return \Exception */ protected function handleResponse(Response $response) { if ($this->exception) { return $this->exception->create($response->getContent(), $response->getStatusCode()); } $content = json_decode($response->getContent()); return new \RuntimeException(sprintf('[%d] %s (%s)', $response->getStatusCode(), $content->message, $content->id)); }
/** * Assert that the response status is 200 * * @param Response $response The response to check */ protected function assert200Response($response) { $this->assertEquals(200, $response->getStatusCode()); }
/** * Converts the HttpKernel response to a BrowserKit response. * * @param Response $response A Response instance * * @return Response A Response instance */ protected function filterResponse($response) { return new DomResponse($response->getContent(), $response->getStatusCode(), $response->headers->all()); }
/** * Converts the HttpKernel response to a BrowserKit response. * * @param Response $response A Response instance * * @return Response A Response instance */ protected function filterResponse($response) { $headers = $response->headers->all(); if ($response->headers->getCookies()) { $cookies = array(); foreach ($response->headers->getCookies() as $cookie) { $cookies[] = new DomCookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); } $headers['Set-Cookie'] = $cookies; } return new DomResponse($response->getContent(), $response->getStatusCode(), $headers); }
public function findClasses($class) { try { $queryObject = array('queryObject' => json_encode(array('coursesection_title' => $class->getTitle(), 'date_from' => $class->getDateFrom(), 'integration_id' => $class->getIntegrationId(), 'user_id' => $class->getUserId(), 'user_role' => $class->getUserRole()))); $soap = $this->discoverCourseSectionIds($queryObject); $response = new Response($this); if ($response->getStatus() == 'error') { throw new TurnitinSDKException($response->getStatusCode(), $response->getDescription(), parent::getLogPath()); } else { $tiiClass = new TiiClass(); $classids = array(); if (isset($soap->sourcedIdSet->sourcedId)) { if (!is_array($soap->sourcedIdSet->sourcedId)) { $soap->sourcedIdSet->sourcedId = array($soap->sourcedIdSet->sourcedId); } foreach ($soap->sourcedIdSet->sourcedId as $id) { $classids[] = $id; } } $tiiClass->setClassIds($classids); $response->setClass($tiiClass); } return $response; } catch (SoapFault $e) { throw new TurnitinSDKException($e->faultcode, $e->faultstring, parent::getLogPath()); } }
/** * Checks the success state of a response * * @param Response $response Response object * @param bool $success to define whether the response is expected to be successful * @param string $type * * @return void */ public function isSuccessful($response, $success = true, $type = 'text/html') { try { $crawler = new Crawler(); $crawler->addContent($response->getContent(), $type); if (!count($crawler->filter('title'))) { $title = '[' . $response->getStatusCode() . '] - ' . $response->getContent(); } else { $title = $crawler->filter('title')->text(); } } catch (\Exception $e) { $title = $e->getMessage(); } if ($success) { $this->assertTrue($response->isSuccessful(), 'The Response was not successful: ' . $title); } else { $this->assertFalse($response->isSuccessful(), 'The Response was successful: ' . $title); } }
/** * Parse a signed JSON response * * @param Response $response * @param SignaturePublicKey $publicKey * @return mixed * @throws SignatureFailed * @throws TransferException */ public function parseSignedJSON(Response $response, SignaturePublicKey $publicKey) { $code = $response->getStatusCode(); if ($code >= 200 && $code < 300) { $body = (string) $response->getBody(); $firstNewLine = \strpos($body, "\n"); // There should be a newline immediately after the base64urlsafe-encoded signature if ($firstNewLine !== self::ENCODED_SIGNATURE_LENGTH) { throw new SignatureFailed(\sprintf("First newline found at position %s, expected %d.\n%s", \print_r($firstNewLine, true), \print_r(self::ENCODED_SIGNATURE_LENGTH, true), Base64::encode($body))); } $sig = Base64UrlSafe::decode(Binary::safeSubstr($body, 0, 88)); $msg = Binary::safeSubstr($body, 89); if (!Asymmetric::verify($msg, $publicKey, $sig, true)) { throw new SignatureFailed(); } return \Airship\parseJSON($msg, true); } throw new TransferException(); }
public function findMemberships($membership) { try { $soap = $this->readMembershipIdsForCollection(array('groupSourcedId' => $membership->getClassId(), 'collection' => 'courseSection')); $response = new Response($this); if ($response->getStatus() == 'error') { throw new TurnitinSDKException($response->getStatusCode(), $response->getDescription()); } else { $tiiMembership = new TiiMembership(); $membershipids = array(); if (isset($soap->sourcedIdSet->sourcedId)) { if (!is_array($soap->sourcedIdSet->sourcedId)) { $soap->sourcedIdSet->sourcedId = array($soap->sourcedIdSet->sourcedId); } foreach ($soap->sourcedIdSet->sourcedId as $id) { $membershipids[] = $id; } } $tiiMembership->setMembershipIds($membershipids); $response->setMembership($tiiMembership); } return $response; } catch (SoapFault $e) { throw new TurnitinSDKException($e->faultcode, $e->faultstring, parent::getLogPath()); } }
public function testGetStatus() { $expectedStatus = 200; $response = new Response($expectedStatus); $this->assertEquals($expectedStatus, $response->getStatusCode()); }
public function findUser($user) { try { $request = array('queryObject' => $user->getEmail()); $soap = $this->discoverPersonIds($request); $response = new Response($this); if ($response->getStatus() == 'error') { throw new TurnitinSDKException($response->getStatusCode(), $response->getDescription()); } else { $tiiUser = new TiiUser(); if (isset($soap->sourcedIdSet->sourcedId)) { $tiiUser->setUserId($soap->sourcedIdSet->sourcedId); } $response->setUser($tiiUser); } return $response; } catch (SoapFault $e) { throw new TurnitinSDKException($e->faultcode, $e->faultstring, parent::getLogPath()); } }
public function createSubmission($submission) { try { $request = array(); $request['resultRecord']['sourcedGUID']['sourcedId'] = ''; $request['resultRecord']['result']['personSourcedId'] = $submission->getAuthorUserId(); $request['resultRecord']['result']['lineItemSourcedId'] = $submission->getAssignmentId(); $request['resultRecord']['result']['extension']['extensionNameVocabulary'] = self::$extensionname_vocab; $request['resultRecord']['result']['extension']['extensionValueVocabulary'] = self::$extensionvalue_vocab; $request['resultRecord']['result']['extension']['extensionField'][0]['fieldName'] = 'Submitter'; $request['resultRecord']['result']['extension']['extensionField'][0]['fieldType'] = 'Integer'; $request['resultRecord']['result']['extension']['extensionField'][0]['fieldValue'] = $submission->getSubmitterUserId(); $soap = $this->createByProxyResult($request); $response = new Response($this); if ($response->getStatus() == 'error') { throw new TurnitinSDKException($response->getStatusCode(), $response->getDescription()); } else { $tiiSubmission = new TiiSubmission(); $tiiSubmission->setSubmissionId($soap->sourcedId); $response->setSubmission($tiiSubmission); } return $response; } catch (SoapFault $e) { throw new TurnitinSDKException($e->faultcode, $e->faultstring, parent::getLogPath()); } }
/** * Filters the Response. * * @param Response $response The Response to filter * * @return Response */ protected function filterResponse($response) { $headers = $response->headers->all(); if ($cookies = $response->headers->getCookies()) { ///\out::e($cookies); /* $cookies = array(); foreach($response->headers->getCookies() as $cookie){ $cookies[] = new Cookie( $cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly() ); }//foreach */ $headers['Set-Cookie'] = implode(', ', $cookies); } //if $bk_response = new BrowserKitResponse($response->getContent(), $response->getStatusCode(), $headers); return $bk_response; }
public function findAssignments($assignment) { try { $soap = $this->readLineItemIdsForCourseSection(array('sectionSourcedId' => $assignment->getClassId())); $response = new Response($this); if ($response->getStatus() == 'error') { throw new TurnitinSDKException($response->getStatusCode(), $response->getDescription()); } else { $tiiAssignment = new TiiAssignment(); $assignmentids = array(); if (isset($soap->sourcedIdSet->sourcedId)) { if (!is_array($soap->sourcedIdSet->sourcedId)) { $soap->sourcedIdSet->sourcedId = array($soap->sourcedIdSet->sourcedId); } foreach ($soap->sourcedIdSet->sourcedId as $id) { $assignmentids[] = $id; } } $tiiAssignment->setAssignmentIds($assignmentids); $response->setAssignment($tiiAssignment); } return $response; } catch (SoapFault $e) { throw new TurnitinSDKException($e->faultcode, $e->faultstring, parent::getLogPath()); } }
/** * Add a response * * @param Response $response */ public function addResponse(Response $response) { $this->responses[$response->getStatusCode()] = $response; }
/** * @param Response $response * @param int $statusCode */ protected function assertJsonResponse(Response $response, $statusCode = 200) { $this->assertEquals($statusCode, $response->getStatusCode(), $response->getContent()); $this->assertTrue($response->headers->contains('Content-Type', 'application/json'), $response->headers); }