本文整理汇总了PHP中Zend\Http\Response类的典型用法代码示例。如果您正苦于以下问题:PHP Response类的具体用法?PHP Response怎么用?PHP Response使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Response类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: vCardAction
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;
}
示例2: createResponse
/**
* 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;
}
示例3: sendHeaders
/**
* 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));
}
}
示例4: assertResponseNotInjected
protected function assertResponseNotInjected()
{
$content = $this->response->getContent();
$headers = $this->response->getHeaders();
$this->assertEmpty($content);
$this->assertFalse($headers->has('content-type'));
}
示例5: onDispatchError
/**
* 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);
}
示例6: checkResponseStatus
/**
* 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;
}
示例7: testSubmitBookmarkHttpError
/**
* @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());
}
示例8: onRoute
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;
}
示例9: testSendHeadersTwoTimesSendsOnlyOnce
/**
* @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());
}
示例10: handleResponse
/**
* {@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);
}
}
示例11: decode
/**
* {@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;
}
示例12: _parseParameters
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;
}
示例13: testConstructorWithHttpResponse
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());
}
示例14: setUp
public function setUp()
{
$response = new Response();
$response->setHeaders(new Headers());
$mvcEvent = new MvcEvent();
$mvcEvent->setResponse($response);
$this->error = new ApiError($mvcEvent);
}
示例15: setResponseContent
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;
}