public function assertSuccess() { if ($this->response->getStatusCode() != 200) { $this->fail($this->response->getContent()); } return $this; }
public function testUnspecified() { $this->mapping->setParameter('missing'); $this->action->execute($this->mapping, null, $this->request, $this->response); $this->assertNotEmpty($this->response->getContent()); $this->assertEquals(400, $this->response->getStatusCode()); }
public static function parseNonPhtml(Response $response, $file) { if (!file_exists($file = file_exists($file = self::getPath() . $file) ? $file : (file_exists($file . '.html') ? $file . '.html' : (file_exists($file . '.xhtml') ? $file . '.xhtml' : (file_exists($file . '.php') ? $file . '.php' : $file))))) { if ($response->getStatusCode() == 200) { $response->setStatusCode(404); } $response->setContent($file = (string) new Phtml('/errors/' . $response->getStatusCode(), FALSE, 'default')); } else { if (strpos($file = realpath($file), realpath(Skin::getPath())) !== 0) { throw new \Exception('Unknown skin path: "' . $file . '".'); } $file = str_replace('sitemap.xml.php', 'sitemap.xml', $file); $repository = new PhpRepository(); $response->headers->set('Content-Type', $repository->findType(strtolower(substr(strrchr($file, '.'), 1)) ?: $file) ?: 'text/plain'); if (basename($file) == 'sitemap.xml') { $phtml = new Phtml(NULL); $file = $phtml->parsePhtml($file . '.php'); } else { $file = file_get_contents($file); } $response->setContent($file); } $response->headers->set('Cache-Control', 'max-age=604800'); $response->headers->set('Content-Length', strlen($file)); return $response; }
/** * @return int */ public function getStatusCode() { if ($this->response === null) { return null; } return $this->response->getStatusCode(); }
/** * Logs a response * * @param Response $response */ protected function logResponse(Response $response) { if ($response instanceof RedirectResponse) { $this->logger->info('< ' . $response->getStatusCode() . ' ' . $response->getTargetUrl()); } else { $this->logger->info('< ' . $response->getStatusCode()); } }
/** * @param \Symfony\Component\HttpFoundation\Response $response * * @return void */ protected function logResponse(Response $response) { if ($response instanceof RedirectResponse) { $message = sprintf('%s Response %s [%s], target URL %s', $this->getSapi(), APPLICATION, $response->getStatusCode(), $response->getTargetUrl()); } else { $message = sprintf('%s Response %s [%s]', $this->getSapi(), APPLICATION, $response->getStatusCode()); } $this->logger->info($message, ['response' => $response]); }
/** * @param InternalResponse $iResponse * @return Response */ public function adaptResponse(InternalResponse $iResponse) { $response = new Response($iResponse->getContent(), $iResponse->getStatusCode(), $iResponse->getHeaders()); if ($this->request) { $response->prepare($this->request); } if ($response->getStatusCode() !== 200) { $response->setContent(Response::$statusTexts[$response->getStatusCode()]); return $response; } return $response; }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $responseHeaders = $response->headers->all(); $cookies = array(); foreach ($response->headers->getCookies() as $cookie) { $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpire(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); } if (count($cookies) > 0) { $responseHeaders['Set-Cookie'] = $cookies; } $attributes = array(); foreach ($request->attributes->all() as $key => $value) { $attributes[$key] = is_object($value) ? sprintf('Object(%s)', get_class($value)) : $value; } $this->data = array( 'format' => $request->getRequestFormat(), 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), 'request_request' => $request->request->all(), 'request_headers' => $request->headers->all(), 'request_server' => $request->server->all(), 'request_cookies' => $request->cookies->all(), 'request_attributes' => $attributes, 'response_headers' => $responseHeaders, 'session_attributes' => $request->hasSession() ? $request->getSession()->getAttributes() : array(), ); }
/** * Serialize a response. * * @param \Symfony\Component\HttpFoundation\Response $response * * @return string */ public function serialize(Response $response) { $content = $response->getContent(); $statusCode = $response->getStatusCode(); $headers = $response->headers; return serialize(compact('content', 'statusCode', 'headers')); }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $responseHeaders = $response->headers->all(); $cookies = array(); foreach ($response->headers->getCookies() as $cookie) { $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); } if (count($cookies) > 0) { $responseHeaders['Set-Cookie'] = $cookies; } $attributes = array(); foreach ($request->attributes->all() as $key => $value) { if (is_object($value)) { $attributes[$key] = sprintf('Object(%s)', get_class($value)); if (is_callable(array($value, '__toString'))) { $attributes[$key] .= sprintf(' = %s', (string) $value); } } else { $attributes[$key] = $value; } } $content = null; try { $content = $request->getContent(); } catch (\LogicException $e) { // the user already got the request content as a resource $content = false; } $this->data = array('format' => $request->getRequestFormat(), 'content' => $content, 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), 'request_request' => $request->request->all(), 'request_headers' => $request->headers->all(), 'request_server' => $request->server->all(), 'request_cookies' => $request->cookies->all(), 'request_attributes' => $attributes, 'response_headers' => $responseHeaders, 'session_attributes' => $request->hasSession() ? $request->getSession()->all() : array(), 'path_info' => $request->getPathInfo()); }
private function getMessage(Response $response) { if (500 >= $response->getStatusCode() && $response->getStatusCode() < 600) { $crawler = new Crawler(); $crawler->addHtmlContent($response->getContent()); if ($crawler->filter('.text-exception h1')->count() > 0) { $exceptionMessage = trim($crawler->filter('.text-exception h1')->text()); $trace = ''; if ($crawler->filter('#traces-0 li')->count() > 0) { list($trace) = explode("\n", trim($crawler->filter('#traces-0 li')->text())); } return $message = 'Internal Server Error: ' . $exceptionMessage . ' ' . $trace; } } return $response->getContent(); }
/** * Test API response status * * @param Response $response * @param int $statusCode * @param string $contentType */ public static function assertJsonResponse($response, $statusCode = 201, $contentType = 'application/json') { \PHPUnit_Framework_TestCase::assertEquals($statusCode, $response->getStatusCode(), $response->getContent()); if ($contentType !== '') { \PHPUnit_Framework_TestCase::assertTrue($response->headers->contains('Content-Type', $contentType), $response->headers); } }
/** * @param Response $response * @param int $statusCode * @param bool $checkValidJson * @param string $contentType * @return array Json decoded */ protected function assertJsonResponse(Response $response, $statusCode = 200, $checkValidJson = true, $contentType = 'application/json') { $content = null; $this->assertEquals($statusCode, $response->getStatusCode(), sprintf("Status code is not expected %d, got %d instead\n%s", $statusCode, $response->getStatusCode(), $response->getContent())); // If content-type is an URL, check for Location header (DELETE) if (strpos($contentType, '://') === false) { $this->assertTrue($response->headers->contains('Content-Type', $contentType), sprintf('No "Content-Type" header set to %s', $contentType)); } else { $this->assertTrue($response->headers->contains('Location', $contentType), sprintf('No "Location" header set to %s', $contentType)); } if ($checkValidJson) { $content = json_decode($response->getContent(), true); $this->assertTrue($content !== null && $content !== false, 'is response valid json: [' . $response->getContent() . ']'); } return $content; }
/** * @param HTTPApiClient $apiClient * @param Response $response * @param ClientRequest $clientRequest * @return mixed */ public function handle(HTTPApiClient $apiClient, Response $response, ClientRequest $clientRequest) { if (200 != $response->getStatusCode()) { $e = new BadResponseException(); $this->throwException($e, $response, $clientRequest); } }
/** * @param Response $response */ protected function assertForm(Response $response) { $this->assertEquals(200, $response->getStatusCode()); $this->assertRegExp('/form/', $response->getContent()); $this->assertNotRegExp('/<html/', $response->getContent()); $this->assertNotRegExp('/_username/', $response->getContent()); }
/** * @param Response $response */ public function setItems(Response $response) { if ($response->getStatusCode() > 299) { return; } $this->items = json_decode($response->getContent()); }
protected function dumpResponse($prefix, $fqcn, $test, Response $response) { preg_match('#([^\\\\]+)$#', $fqcn, $match); $shortname = $match[1]; $filepath = sys_get_temp_dir() . sprintf("/%s-%s-%s-%d.html", $prefix, $shortname, $test, $response->getStatusCode()); file_put_contents($filepath, $response->getContent()); }
/** * @Then /^I should see a (\d+) response$/ */ public function iShouldSeeAResponse($statusCode) { $expected = (int) $statusCode; if ($this->response->getStatusCode() !== $expected) { throw new \LogicException(sprintf('Status Code does not match, expected %d, but got a %d', $expected, $this->response->getStatusCode())); } }
protected function jsonResponseToResponse(Response $response) { $content = $response->getContent(); $status = $response->getStatusCode(); $response = $response->headers->all(); return new Response($content, $status, $response); }
/** * Sending back a response to mongrel2 webserver. * * @param Request $request * @param Response $response */ private function sendResponseToMongrel(Request $request, Response $response) { $response->prepare($request); // Map back our Symfony Response to a MongrelResponse. $mongrelResponse = new MongrelResponse($request->attributes->get('mongrel2_uuid'), [$request->attributes->get('mongrel2_listener')]); $mongrelResponse->setContent($response->getContent()); $headers = $response->headers->all(); foreach ($response->headers->getCookies() as $cookie) { $headers['Set-Cookie'][] = $cookie; } $mongrelResponse->setHeaders($headers); $mongrelResponse->setHttpVersion($response->getProtocolVersion()); $mongrelResponse->setStatusCode($response->getStatusCode()); $mongrelResponse->setReasonPhrase(Response::$statusTexts[$response->getStatusCode()]); $this->handler->sendResponse($mongrelResponse); }
public function needConsoleInjection(Request $request, Response $response) { if ($request->isXmlHttpRequest() || !$response->headers->has('X-Debug-Token') || '3' === substr($response->getStatusCode(), 0, 1) || $response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html') || 'html' !== $request->getRequestFormat()) { return false; } return true; }
/** * Logs the duration of a specific request through the application * * @param Request $request * @param Response $response * @param double $startTime */ protected static function logDuration(Request $request, Response $response, $startTime) { $duration = microtime(true) - $startTime; $metric = self::prefix('request_time'); $tags = ["url" => $request->getSchemeAndHttpHost() . $request->getRequestUri(), "status_code" => $response->getStatusCode()]; Datadog::timing($metric, $duration, 1, $tags); }
/** * @param HTTPApiClient $apiClient * @param Response $response * @param ClientRequest $clientRequest * @return Response * @throws MQSEmptyMessageException * @throws MQSResponseException */ public function handle(HTTPApiClient $apiClient, Response $response, ClientRequest $clientRequest) { if ((int) $response->getStatusCode() >= 400) { if ((int) $response->getStatusCode() == 404) { //404 有可能是 Message not exist. 或者是 The queue name you provided is not exist. if (strpos($response->getContent(), 'Message not exist.')) { throw new MQSEmptyMessageException(); } } $e = new MQSResponseException("MQS返回状态码:" . $response->getStatusCode()); $e->setExceptionMetaData('content', $response->getContent()); $e->setExceptionMetaData('header', $response->headers); $e->setExceptionMetaData('request', $clientRequest->toArray()); throw $e; } return $response; }
protected function logResponse(Response $response, Request $request) { if ($response->getStatusCode() >= 500) { $color = LogLevel::ERROR; } elseif ($response->getStatusCode() >= 400) { $color = LogLevel::WARNING; } elseif ($response->getStatusCode() >= 300) { $color = LogLevel::NOTICE; } elseif ($response->getStatusCode() >= 200) { $color = LogLevel::INFO; } else { $color = LogLevel::INFO; } $msg = 'Response {response_status_code} for "{request_method} {request_uri}"'; $context = array('request_method' => $request->getMethod(), 'request_uri' => $request->getRequestUri(), 'response_status_code' => $response->getStatusCode(), 'response_charset' => $response->getCharset(), 'response_date' => $response->getDate(), 'response_etag' => $response->getEtag(), 'response_expires' => $response->getExpires(), 'response_last_modified' => $response->getLastModified(), 'response_max_age' => $response->getMaxAge(), 'response_protocol_version' => $response->getProtocolVersion(), 'response_ttl' => $response->getTtl(), 'response_vary' => $response->getVary()); $this->logger->log($color, $msg, $context); }
/** * @inheritdoc */ protected function assertOAuthError(Response $responseObj) { $response = json_decode($responseObj->getContent()); $this->assertSame(Response::HTTP_UNAUTHORIZED, $responseObj->getStatusCode()); $this->assertTrue($response instanceof \stdClass); $this->assertObjectHasAttribute('error', $response); $this->assertObjectHasAttribute('error_description', $response); }
/** * @param HTTPApiClientException $e * @param Response $response * @param ClientRequest $clientRequest * @throws HTTPApiClientException */ protected function throwException(HTTPApiClientException $e, Response $response, ClientRequest $clientRequest) { $e->setExceptionMetaData('status_code', $response->getStatusCode()); $e->setExceptionMetaData('content', $response->getContent()); $e->setExceptionMetaData('header', $response->headers); $e->setExceptionMetaData('request', $clientRequest->toArray()); throw $e; }
private function doSetFromHttpContext(ApiLog $log, Request $request, Response $response) { $log->setRoute($request->getPathInfo()); $log->setMethod($request->getMethod()); $log->setStatusCode($response->getStatusCode()); $log->setFormat($response->headers->get('content-type')); $this->setDetails($log, $request, $response); }
/** * Constructor. * * @param Response $response * @param \Exception|null $previous */ public function __construct(Response $response, \Exception $previous = null) { if (!$response->headers->has('X-Status-Code')) { $response->headers->set('X-Status-Code', $response->getStatusCode()); } $this->response = $response; parent::__construct('This exception has no message. Use $exception->getResponse() instead.', 0, $previous); }
/** * {@inheritdoc} */ public function collect(Request $request, Response $response, \Exception $exception = null) { $responseHeaders = $response->headers->all(); $cookies = array(); foreach ($response->headers->getCookies() as $cookie) { $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly()); } if (count($cookies) > 0) { $responseHeaders['Set-Cookie'] = $cookies; } $attributes = array(); foreach ($request->attributes->all() as $key => $value) { if ('_route' == $key && is_object($value)) { $value = $value->getPattern(); } $attributes[$key] = $this->varToString($value); } $content = null; try { $content = $request->getContent(); } catch (\LogicException $e) { // the user already got the request content as a resource $content = false; } $sessionMetadata = array(); $sessionAttributes = array(); $flashes = array(); if ($request->hasSession()) { $session = $request->getSession(); if ($session->isStarted()) { $sessionMetadata['Created'] = date(DATE_RFC822, $session->getMetadataBag()->getCreated()); $sessionMetadata['Last used'] = date(DATE_RFC822, $session->getMetadataBag()->getLastUsed()); $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime(); $sessionAttributes = $session->all(); $flashes = $session->getFlashBag()->peekAll(); } } $this->data = array('format' => $request->getRequestFormat(), 'content' => $content, 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), 'request_request' => $request->request->all(), 'request_headers' => $request->headers->all(), 'request_server' => $request->server->all(), 'request_cookies' => $request->cookies->all(), 'request_attributes' => $attributes, 'response_headers' => $responseHeaders, 'session_metadata' => $sessionMetadata, 'session_attributes' => $sessionAttributes, 'flashes' => $flashes, 'path_info' => $request->getPathInfo(), 'controller' => 'n/a', 'locale' => $request->getLocale()); if (isset($this->controllers[$request])) { $controller = $this->controllers[$request]; if (is_array($controller)) { try { $r = new \ReflectionMethod($controller[0], $controller[1]); $this->data['controller'] = array('class' => is_object($controller[0]) ? get_class($controller[0]) : $controller[0], 'method' => $controller[1], 'file' => $r->getFilename(), 'line' => $r->getStartLine()); } catch (\ReflectionException $re) { if (is_callable($controller)) { // using __call or __callStatic $this->data['controller'] = array('class' => is_object($controller[0]) ? get_class($controller[0]) : $controller[0], 'method' => $controller[1], 'file' => 'n/a', 'line' => 'n/a'); } } } elseif ($controller instanceof \Closure) { $this->data['controller'] = 'Closure'; } else { $this->data['controller'] = (string) $controller ?: 'n/a'; } unset($this->controllers[$request]); } }
/** * Logs a response. * * @param Response $response */ protected function logResponse(Response $response) { $response->headers->set('trace-token', TracingRequest::getInstance()->getTraceId()); if ($response instanceof RedirectResponse) { $this->logger->info('< ' . $response->getStatusCode() . ' ' . $response->getTargetUrl()); } else { $this->logger->info('HTTP response: ' . $response->getStatusCode() . ' #TRACE#{"event":"response.send"}'); } }