php Zend-Http-Response类(方法)实例源码

下面列出了php Zend-Http-Response 类(方法)源码代码实例,从而了解它的用法。

作者:zourc    项目:zourc   
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;
 }

作者:acelay    项目:zf2-acqrcod   
/**
  * 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;
 }

作者:fw    项目:securit   
/**
  * 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));
     }
 }

作者:wizzve    项目:ZffHtml2pd   
protected function assertResponseNotInjected()
 {
     $content = $this->response->getContent();
     $headers = $this->response->getHeaders();
     $this->assertEmpty($content);
     $this->assertFalse($headers->has('content-type'));
 }

作者:omusic    项目:zfr-res   
/**
  * 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);
 }

作者:ma-s    项目:apigility-clien   
/**
  * 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;
 }

作者:nickel71    项目:pinboard-archiv   
/**
  * @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());
 }

作者:zourc    项目:zourc   
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;
 }

作者:pnaq5    项目:zf2dem   
/**
  * @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());
 }

作者:publicitas-deploymen    项目:php-openid-connect-clien   
/**
  * {@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);
     }
 }

作者:matryoshka-mode    项目:service-ap   
/**
  * {@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;
 }

作者:ahyswan    项目:eva-engin   
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;
 }

作者:szmnmichalowsk    项目:zf2-nocaptch   
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());
 }

作者:sebak    项目:zend-mvc-controlle   
public function setUp()
 {
     $response = new Response();
     $response->setHeaders(new Headers());
     $mvcEvent = new MvcEvent();
     $mvcEvent->setResponse($response);
     $this->error = new ApiError($mvcEvent);
 }

作者:fousheez    项目:aut   
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;
 }

作者:necromant200    项目:zeu   
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;
 }

作者:binary-dat    项目:ZendOAut   
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());
 }

作者:haoyanfe    项目:zf   
public function getClientFail()
 {
     $response = new HttpResponse();
     $response->setStatusCode(404);
     $client = new ClientNotReset();
     $client->setResponse($response);
     return $client;
 }

作者:shabbirvividad    项目:magento   
/**
  * 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;
 }

作者:poka    项目:webarchiv   
/**
  * 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;
 }


问题


面经


文章

微信
公众号

扫码关注公众号