public function vCardAction() { $contact = $this->contactService->find($this->params('id')); if (!$contact) { return $this->notFoundAction(); } $builder = new VCardBuilder(); switch (true) { case $contact instanceof Company: $vcard = $builder->buildCompany($contact); break; case $contact instanceof Person: $vcard = $builder->buildPerson($contact); break; default: throw new RuntimeException('Invalid type provided.'); } $data = $vcard->serialize(); $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_200); $response->setContent($data); $headers = $response->getHeaders(); $headers->addHeaderLine('Content-Disposition', 'attachment; filename="' . $contact->getDisplayName() . '.vcf"'); $headers->addHeaderLine('Content-Length', strlen($data)); $headers->addHeaderLine('Content-Type', 'text/plain'); return $response; }
/** * Creates the response to be returned for a QR Code * @param $content * @param $contentType * @return HttpResponse */ protected function createResponse($content, $contentType) { $resp = new HttpResponse(); $resp->setStatusCode(200)->setContent($content); $resp->getHeaders()->addHeaders(array('Content-Length' => strlen($content), 'Content-Type' => $contentType)); return $resp; }
/** * Immediately send headers from a Zend\Http\Response * * @param ZendResponse $zresponse Zend\Http\Response * * @return void */ public static function sendHeaders(ZendResponse $zresponse) { $headers = $zresponse->getHeaders()->toArray(); foreach ($headers as $key => $value) { header(sprintf('%s: %s', $key, $value)); } }
protected function assertResponseNotInjected() { $content = $this->response->getContent(); $headers = $this->response->getHeaders(); $this->assertEmpty($content); $this->assertFalse($headers->has('content-type')); }
/** * Get the exception and optionally set status code, reason message and additional errors * * @internal * @param MvcEvent $event * @return void */ public function onDispatchError(MvcEvent $event) { $exception = $event->getParam('exception'); if (isset($this->exceptionMap[get_class($exception)])) { $exception = $this->createHttpException($exception); } // We just deal with our Http error codes here ! if (!$exception instanceof HttpExceptionInterface || $event->getResult() instanceof HttpResponse) { return; } // We clear the response for security purpose $response = new HttpResponse(); $response->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $exception->prepareResponse($response); // NOTE: I'd like to return a JsonModel instead, and let ZF handle the request, but I couldn't make // it work because for unknown reasons, the Response get replaced "somewhere" in the MVC workflow, // so the simplest is simply to do that $content = ['status_code' => $response->getStatusCode(), 'message' => $response->getReasonPhrase()]; if ($errors = $exception->getErrors()) { $content['errors'] = $errors; } $response->setContent(json_encode($content)); $event->setResponse($response); $event->setResult($response); $event->stopPropagation(true); }
/** * Check response status * * @throws ApigilityClient\Exception\RuntimeException * @return Bool */ private function checkResponseStatus() { if (!$this->httpResponse->isSuccess()) { return new TriggerException($this->httpClient, $this->httpResponse); } return true; }
/** * @expectedException Exception * @expectedExceptionMessage request failed * @excpetedExceptionCode 1 */ public function testSubmitBookmarkHttpError() { $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_403); $this->mockSubmitClient($response); $this->sut->submitBookmark($this->getBookmark()); }
public function onRoute(MvcEvent $e) { $serviceManager = $e->getApplication()->getServiceManager(); $routeMatchName = $e->getRouteMatch()->getMatchedRouteName(); if (strpos($routeMatchName, '.rest.') !== false || strpos($routeMatchName, '.rpc.') !== false) { return; } $config = $serviceManager->get('Config'); $identityGuards = $config['zource_guard']['identity']; $needsIdentity = null; foreach ($identityGuards as $guard => $needed) { if (fnmatch($guard, $routeMatchName)) { $needsIdentity = $needed; break; } } if ($needsIdentity === null) { throw new RuntimeException(sprintf('The identity guard "%s" has not been configured.', $routeMatchName)); } if (!$needsIdentity) { return; } $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService'); if ($authenticationService->hasIdentity()) { return; } $returnUrl = $e->getRouter()->assemble([], ['name' => $routeMatchName, 'force_canonical' => true, 'query' => $e->getRequest()->getUri()->getQuery()]); $url = $e->getRouter()->assemble([], ['name' => 'login', 'query' => ['redir' => $returnUrl]]); $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_302); $response->getHeaders()->addHeaderLine('Location: ' . $url); return $response; }
/** * @runInSeparateProcess */ public function testSendHeadersTwoTimesSendsOnlyOnce() { if (!function_exists('xdebug_get_headers')) { $this->markTestSkipped('Xdebug extension needed, skipped test'); } $headers = array('Content-Length: 2000', 'Transfer-Encoding: chunked'); $response = new Response(); $response->getHeaders()->addHeaders($headers); $mockSendResponseEvent = $this->getMock('Zend\\Mvc\\ResponseSender\\SendResponseEvent', array('getResponse')); $mockSendResponseEvent->expects($this->any())->method('getResponse')->will($this->returnValue($response)); $responseSender = $this->getMockForAbstractClass('Zend\\Mvc\\ResponseSender\\AbstractResponseSender'); $responseSender->sendHeaders($mockSendResponseEvent); $sentHeaders = xdebug_get_headers(); $diff = array_diff($sentHeaders, $headers); if (count($diff)) { $header = array_shift($diff); $this->assertContains('XDEBUG_SESSION', $header); $this->assertEquals(0, count($diff)); } $expected = array(); if (version_compare(phpversion('xdebug'), '2.2.0', '>=')) { $expected = xdebug_get_headers(); } $responseSender->sendHeaders($mockSendResponseEvent); $this->assertEquals($expected, xdebug_get_headers()); }
/** * {@inheritdoc} * @see \InoOicClient\Oic\AbstractResponseHandler::handleResponse() */ public function handleResponse(\Zend\Http\Response $httpResponse) { $responseData = null; $decodeException = null; try { $responseData = $this->getJsonCoder()->decode($httpResponse->getBody()); } catch (\Exception $e) { $decodeException = $e; } if (!$httpResponse->isSuccess()) { if (isset($responseData[Param::ERROR])) { $error = $this->getErrorFactory()->createErrorFromArray($responseData); $this->setError($error); return; } else { throw new HttpErrorStatusException(sprintf("Error code '%d' from server", $httpResponse->getStatusCode())); } } if (null !== $decodeException) { throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $decodeException); } try { $this->response = $this->getResponseFactory()->createResponse($responseData); } catch (\Exception $e) { throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e); } }
/** * Parses the HTTP response from a userinfo request. * * @param Http\Response $httpResponse * @throws HttpAuthenticateException * @throws HttpErrorStatusException * @throws InvalidResponseFormatException * @throws Exception\InvalidResponseException */ public function handleResponse(Http\Response $httpResponse) { if (!$httpResponse->isSuccess()) { $statusCode = $httpResponse->getStatusCode(); if (401 === $statusCode && ($authenticateHeader = $httpResponse->getHeaders()->get($this->wwwAuthenticateHeaderName)->current())) { $params = $this->parseAuthenticateHeaderValue($authenticateHeader->getFieldValue()); if (isset($params['error'])) { $this->setError($this->getErrorFactory()->createErrorFromArray($params)); return; } throw new HttpAuthenticateException(sprintf("Missing error information in WWW-Authenticate header: %s", $authenticateHeader->getFieldValue())); } throw new HttpErrorStatusException(sprintf("Error status response from server: %s", $statusCode)); } try { $responseData = $this->getJsonCoder()->decode($httpResponse->getBody()); } catch (\Exception $e) { throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $e); } try { $this->response = $this->getResponseFactory()->createResponse($responseData); } catch (\Exception $e) { throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e); } }
/** * {@inheritdoc} */ public function decode(Response $response) { $headers = $response->getHeaders(); if (!$headers->has('Content-Type')) { $exception = new Exception\InvalidResponseException('Content-Type missing'); $exception->setResponse($response); throw $exception; } /* @var $contentType \Zend\Http\Header\ContentType */ $contentType = $headers->get('Content-Type'); switch (true) { case $contentType->match('*/json'): $payload = Json::decode($response->getBody(), Json::TYPE_ARRAY); break; //TODO: xml // case $contentType->match('*/xml'): // $xml = Security::scan($response->getBody()); // $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY); // break; //TODO: xml // case $contentType->match('*/xml'): // $xml = Security::scan($response->getBody()); // $payload = Json::decode(Json::encode((array) $xml), Json::TYPE_ARRAY); // break; default: throw new Exception\InvalidFormatException(sprintf('The "%s" media type is invalid or not supported', $contentType->getMediaType())); break; } $this->lastPayload = $payload; if ($contentType->match('*/hal+*')) { return $this->extractResourceFromHal($payload, $this->getPromoteTopCollection()); } //else return (array) $payload; }
protected function _parseParameters(HTTPResponse $response) { $params = array(); $body = $response->getBody(); if (empty($body)) { return; } $tokenFormat = $this->getTokenFormat(); switch ($tokenFormat) { case 'json': $params = \Zend\Json\Json::decode($body); break; case 'jsonp': break; case 'pair': $parts = explode('&', $body); foreach ($parts as $kvpair) { $pair = explode('=', $kvpair); $params[rawurldecode($pair[0])] = rawurldecode($pair[1]); } break; default: throw new Exception\InvalidArgumentException(sprintf('Unable to handle access token response by undefined format %', $tokenFormat)); } return (array) $params; }
public function testConstructorWithHttpResponse() { $httpResponse = new Response(); $httpResponse->setStatusCode(200); $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html'); $response = new CaptchaResponse($httpResponse); $this->assertSame(true, $response->getStatus()); }
public function setUp() { $response = new Response(); $response->setHeaders(new Headers()); $mvcEvent = new MvcEvent(); $mvcEvent->setResponse($response); $this->error = new ApiError($mvcEvent); }
protected function setResponseContent(Response $response, array $data) { if ($response instanceof \Zend\Http\PhpEnvironment\Response) { $response->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $response->setContent(json_encode(array_merge(array('status' => $response->getStatusCode()), $data))); } return $response; }
protected function _parseResponse(\Zend\Http\Response $response) { $body = \Zend\Json\Decoder::decode($response->getBody()); if (array_key_exists(self::PARSE_ERROR, $body)) { throw new \Exception($body[self::PARSE_REASON]); } return $body; }
public function testIsValidDetectsGoodResponse() { $body = 'oauth_token=jZaee4GF52O3lUb9&oauth_token_secret=J4Ms4n8sxjYc0A8K0KOQFCTL0EwUQTri'; $response = new HTTPResponse(); $response->setContent($body)->setStatusCode(200); $token = new AccessToken($response); $this->assertTrue($token->isValid()); }
public function getClientFail() { $response = new HttpResponse(); $response->setStatusCode(404); $client = new ClientNotReset(); $client->setResponse($response); return $client; }
/** * Encode data as JSON and set response header * * @param mixed $data * @param array $jsonOptions Options to pass to JsonFormatter::encode() * @return string|void */ public function __invoke($data, array $jsonOptions = array()) { $data = JsonFormatter::encode($data, null, $jsonOptions); if ($this->response instanceof Response) { $headers = $this->response->getHeaders(); $headers->addHeaderLine('Content-Type', 'application/json'); } return $data; }
/** * Create the crawler from body given by response. * * @param Response $response * * @return Crawler */ protected function getCrawler(Response $response) { if (null === $this->crawler) { $this->crawler = new Crawler(); $this->crawler->addContent($response->getBody()); $this->crawler = $this->crawler->filter('#wbCalendar .date'); } return $this->crawler; }
/** * @param int $status * @param array $body */ private function rawResponse($status, $body) { $zfResponse = new ZfResponse(); $zfResponse->setStatusCode($status); $reasonPhrase = $zfResponse->getReasonPhrase(); \header('HTTP/1.0 ' . $status . ' ' . $reasonPhrase); \header('Content-Type: application/json'); die(json_encode($body)); }
/** * @param HttpResponse $response * * @return $this */ public function setFromResponseObj(HttpResponse $response) { if ($response->isSuccess()) { $this->setStatus($response->isSuccess()); } else { $this->setError($response->getReasonPhrase()); } return $this; }
/** * @dataProvider exceptionDataProvider */ public function testExceptionsAreThrownOnErrors($statusCode, $expectedException) { $method = new ReflectionMethod('SlmMail\\Service\\MailgunService', 'parseResponse'); $method->setAccessible(true); $response = new HttpResponse(); $response->setStatusCode($statusCode); $this->setExpectedException($expectedException); $method->invoke($this->service, $response); }
function it_traps_unauthorized(MvcEvent $event, Response $response, Application $application) { unset($_SERVER['HTTP_X_REQUESTED_WITH']); $event->getTarget()->willReturn($application); $event->setRouteMatch(new RouteMatch(['controller' => 'Controller', 'action' => 'Action']))->shouldBeCalled(); $response->setStatusCode(403)->shouldBeCalled(); $event->getResponse()->willReturn($response); $this->handle($event, AccessService::ACCESS_UNAUTHORIZED)->shouldBe(true); }
/** * Creates a Perun response from the HTTP response. * * @param Http\Response $httpResponse * @param Request $request * @throws GeneralException\MissingDependencyException * @return Response */ public function createResponseFromHttpResponse(Http\Response $httpResponse, Request $request) { $serializer = $this->getSerializer(); if (!$serializer) { throw new GeneralException\MissingDependencyException('serializer', $this); } $payload = $this->getPayloadFactory()->createPayload(); $payload = $serializer->unserialize($httpResponse->getBody(), $payload); return $this->createResponseFromPayload($payload, $request); }
/** * Exception factory. * * Returns a RequestErrorException or RemoteErrorException depending on * the response's status code. * * @param Response $response Server response * * @return RequestErrorException|RemoteErrorException */ public static function createFromResponse(Response $response) { $status = $response->getStatusCode(); $phrase = $response->getReasonPhrase(); if ($status >= 500) { return new RemoteErrorException($status . ' ' . $phrase, $status, $response); } else { return new RequestErrorException($status . ' ' . $phrase, $status, $response); } }
public function testConstructorWithMissingStatus() { $params = array('error' => 'error'); $httpResponse = new Response(); $httpResponse->setStatusCode(200); $httpResponse->getHeaders()->addHeaderLine('Content-Type', 'text/html'); $httpResponse->setContent(json_encode($params)); $response = new CaptchaResponse($httpResponse); $this->assertSame(false, $response->getStatus()); }
/** * Creates a new entry * * @param mixed $data * @return Response */ public function create($data) { $sintegra = new Sintegra(); $sintegra->exchangeArray($data); $this->getSintegraTable()->saveSintegra($sintegra); $response = new Response(); $response->setStatusCode(200); $response->setContent(json_encode(array('status' => 'ok'))); return $response; }
/** * Listen for specific thrown exceptions and display the proper error page * and code for each. * * @param MvcEvent $e */ public function handleException(MvcEvent $e) { $result = $e->getResult(); // Don't interfere with a complete response. if ($result instanceof ResponseInterface) { return; } // Only handle exceptions. if ($e->getError() !== ZendApplication::ERROR_EXCEPTION) { return; } $exception = $e->getParam('exception'); $this->getServiceLocator()->get('Omeka\\Logger')->err((string) $exception); if ($exception instanceof AclException\PermissionDeniedException) { $template = 'error/403'; $status = 403; } else { if ($exception instanceof ApiException\NotFoundException || $exception instanceof MvcException\NotFoundException) { $template = 'error/404'; $status = 404; } else { return; } } $model = new ViewModel(['exception' => $exception]); $model->setTemplate($template); $response = $e->getResponse(); if (!$response) { $response = new Response(); } $response->setStatusCode($status); $e->setResponse($response); $e->getViewModel()->addChild($model); }