getContent() public method

Gets the current response content.
public getContent ( ) : string
return string Content
Beispiel #1
0
 public function assertSuccess()
 {
     if ($this->response->getStatusCode() != 200) {
         $this->fail($this->response->getContent());
     }
     return $this;
 }
Beispiel #2
0
 private function evaluateGoodXML(Response $response)
 {
     $dom_doc = new \DOMDocument();
     $dom_doc->loadXML($response->getContent());
     $this->assertInstanceOf('DOMDocument', $dom_doc);
     $this->assertEquals($dom_doc->saveXML(), $response->getContent());
 }
 /**
  * @Then /^I should see "([^"]*)"$/
  */
 public function iShouldSee($match)
 {
     if ($this->response instanceof \Exception) {
         throw $this->response;
     }
     PHPUnit_Framework_Assert::assertContains($match, $this->response->getContent());
 }
 public function testPlainRequest()
 {
     $testBody = 'test';
     $this->response->setContent($testBody);
     $this->listener->onResponse($this->event);
     $this->assertEquals($testBody, $this->response->getContent());
 }
Beispiel #5
0
 protected function doKernelResponse(Request $request, Response $response)
 {
     if (!$response instanceof DataResponse) {
         return;
     }
     $routeName = $request->attributes->get('_route');
     $route = $this->routes->get($routeName);
     if (!$route) {
         return;
     }
     $acceptedFormat = $route->getOption(RouteOptions::ACCEPTED_FORMAT);
     if (!$acceptedFormat) {
         $response->setContent('');
         $response->setStatusCode(406);
     }
     if ($this->encoder->supportsEncoding($acceptedFormat) && $acceptedFormat === 'json') {
         $contentType = $request->getMimeType($acceptedFormat);
         $jsonResponse = new JsonResponse($response->getContent());
         $response->setContent($jsonResponse->getContent());
         $response->headers->set('Content-Type', $contentType);
     } elseif ($this->encoder->supportsEncoding($acceptedFormat)) {
         $contentType = $request->getMimeType($acceptedFormat);
         $content = $this->encoder->encode($response->getContent(), $acceptedFormat);
         $response->setContent($content);
         $response->headers->set('Content-Type', $contentType);
     }
 }
 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());
 }
 /**
  * @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());
 }
Beispiel #8
0
 /**
  * Check if the response is valid
  * tests the status code, headers, and the content
  * @param Response $response
  * @param integer $statusCode
  * @param boolean $checkValidJson
  */
 protected function assertJsonResponse(Response $response, $statusCode, $checkValidJson = true)
 {
     $this->assertEquals($statusCode, $response->getStatusCode(), $response->getContent());
     if ($checkValidJson) {
         $this->assertTrue($response->headers->contains('Content-Type', 'application/json'), $response->headers);
         $decode = json_decode($response->getContent());
         $this->assertTrue($decode != null && $decode != false, 'Invalid JSON: [' . $response->getContent() . ']');
     }
 }
 /**
  * Creates a json log file containing the request and the response contents.
  *
  * @param Request  $request
  * @param Response $response
  *
  * @return string The new mock file path
  */
 public function logReponse(Request $request, Response $response)
 {
     $filename = $this->getFilePathByRequest($request);
     $requestJsonContent = json_decode($request->getContent(), true);
     $responseJsonContent = json_decode($response->getContent(), true);
     $dumpFileContent = ['request' => ['uri' => $request->getRequestUri(), 'method' => $request->getMethod(), 'parameters' => $request->request->all(), 'content' => $requestJsonContent ?: $request->getContent()], 'response' => ['statusCode' => $response->getStatusCode(), 'contentType' => $response->headers->get('Content-Type'), 'content' => $responseJsonContent ?: $response->getContent()]];
     $this->filesystem->dumpFile($this->mocksDir . $filename, self::jsonEncode($dumpFileContent, true));
     return $this->mocksDir . $filename;
 }
 public function after(Request $request, Response $response)
 {
     $now = new \DateTime("now");
     $mapper = new CacheRecordSQLMapper($this->app["db"]);
     $currentRouteName = $request->attributes->get("_route");
     if ($this->isCacheCompromiser($currentRouteName)) {
         /** @todo method check */
         $mapper = new CacheRecordSQLMapper($this->app["db"]);
         $compromisedCount = $mapper->compromiseAll();
         return;
     }
     if ($this->isRouteCacheable($currentRouteName) && $response->isOk()) {
         $cacheRecord = $mapper->findByUri($this->getCurrentUri());
         if (!$cacheRecord) {
             //                $this->createCacheRecord();
             $data = [];
             $data["uri"] = $this->getCurrentUri();
             $data["hash"] = md5($response->getContent());
             $data["lmt"] = $now->format("Y-m-d H:i:s");
             $cacheRecord = new CacheRecord($data);
             $mapper->create($cacheRecord);
             $response->setPublic();
             $response->setDate($now);
             $response->setMaxAge($this->config->getMaxAge());
             $response->setSharedMaxAge($this->config->getMaxAgeShared());
             $response->setLastModified($now);
             $response->headers->addCacheControlDirective('must-revalidate', true);
             return $response;
         }
         if ($cacheRecord->getCompromised()) {
             if ($cacheRecord->getHash() === md5($response->getContent())) {
                 $cacheRecord->setCompromised(false);
                 $mapper->update($cacheRecord->getId(), $cacheRecord);
                 $response = $this->createResponse($cacheRecord->getLmt());
                 $response->setNotModified();
                 return $response;
             } else {
                 $cacheRecord->setCompromised(false);
                 $cacheRecord->setHash(md5($response->getContent()));
                 $cacheRecord->setLmt(date("Y-m-d H:i:s"));
                 $mapper->update($cacheRecord->getId(), $cacheRecord);
                 return $response;
             }
         } else {
             $now = new \DateTime("2015-12-12");
             $response->setPublic();
             $response->setDate($now);
             $response->setMaxAge($this->config->getMaxAge());
             $response->setSharedMaxAge($this->config->getMaxAgeShared() + 1);
             $response->setLastModified(new \DateTime($cacheRecord->getLmt()));
             return $response;
         }
     }
 }
 public function handle(HTTPApiClient $apiClient, Response $response, ClientRequest $clientRequest)
 {
     $responseArray = @json_decode($response->getContent(), true);
     if (isset($responseArray['err_code'])) {
         if ($responseArray['err_code'] == '0') {
             return $response;
         }
     }
     $e = new UnknownException($response->getContent());
     $this->throwException($e, $response, $clientRequest);
 }
 /**
  * Return an object from a decoded response body.
  *
  * @return object
  * @throws InvalidArgumentException
  */
 public function getJsonObject($assoc, $depth, $options)
 {
     if (!preg_match(static::$jsonResponse, $this->response->headers->get('content-type'))) {
         throw new InvalidArgumentException("JsonParser requires response with json content type");
     }
     $object = json_decode($this->response->getContent(), $assoc, $depth, $options);
     $error = json_last_error();
     if (JSON_ERROR_NONE !== $error) {
         throw new InvalidArgumentException($this->transformError($error));
     }
     return $object;
 }
 /**
  * {@inheritDoc}
  */
 public function store(Response $response, $targetPath, $filter)
 {
     $storageResponse = $this->storage->create_object($this->bucket, $targetPath, array('body' => $response->getContent(), 'contentType' => $response->headers->get('Content-Type'), 'length' => strlen($response->getContent()), 'acl' => $this->acl));
     if ($storageResponse->isOK()) {
         $response->setStatusCode(301);
         $response->headers->set('Location', $this->getObjectUrl($targetPath));
     } else {
         if ($this->logger) {
             $this->logger->warn('The object could not be created on Amazon S3.', array('targetPath' => $targetPath, 'filter' => $filter, 's3_response' => $storageResponse));
         }
     }
     return $response;
 }
 /**
  * Injects the livereload script.
  *
  * @param Response $response A Response instance
  */
 protected function injectScript(Response $response)
 {
     if (function_exists('mb_stripos')) {
         $posrFunction = 'mb_strripos';
         $substrFunction = 'mb_substr';
     } else {
         $posrFunction = 'strripos';
         $substrFunction = 'substr';
     }
     $content = $response->getContent();
     $pos = $posrFunction($content, '</body>');
     if (false !== $pos) {
         $script = "livereload.js";
         if ($this->checkServerPresence) {
             // GET is required, as livereload apparently does not support HEAD requests ...
             $request = $this->httpClient->get($script);
             try {
                 $checkResponse = $this->httpClient->send($request);
                 if ($checkResponse->getStatusCode() !== 200) {
                     return;
                 }
             } catch (CurlException $e) {
                 // If error is connection failed, we assume the server is not running
                 if ($e->getCurlHandle()->getErrorNo() === 7) {
                     return;
                 }
                 throw $e;
             }
         }
         $content = $substrFunction($content, 0, $pos) . "\n" . '<script src="' . $this->httpClient->getBaseUrl() . $script . '"></script>' . "\n" . $substrFunction($content, $pos);
         $response->setContent($content);
     }
 }
 /**
  * @Given /^with content:$/
  */
 public function withContent(PyStringNode $content)
 {
     $expected = (string) $content;
     if ($this->response->getContent() !== $expected) {
         throw new \LogicException(sprintf('Content does not match, expected %s, but got a %s', $expected, $this->response->getContent()));
     }
 }
Beispiel #16
0
 public static function parseContent(Response $response, $content = FALSE)
 {
     $response->headers->set('Via', '1.1 ' . Keyserver::getConfig()->hostname . ':' . Keyserver::getConfig()->hkp_public_port . ' (' . (Keyserver::getConfig()->expose_keyserver ? $response->headers->get('Server') : 'php-proxy-keyserver') . ')');
     if (strpos($response->headers->get('Content-Disposition'), 'attachment') === 0 || !Keyserver::getRequest()->server->get('HTTP_USER_AGENT') || Keyserver::getRequest()->server->get('SERVER_PORT') === Keyserver::getConfig()->hkp_public_port && !Keyserver::getConfig()->layout_hkp_request && strpos(Keyserver::getRequest()->server->get('REQUEST_URI'), '/pks/') === 0) {
         return $response;
     }
     if (!$content) {
         $content = self::isPhtml() ? (string) new Phtml(FALSE, $response->getContent()) : $response->getContent();
     }
     if (self::isPhtml() && Keyserver::getConfig()->indent_strict_html) {
         $content = self::indentStrictHtml($content);
     }
     $response->headers->set('Content-Type', 'text/html;charset=UTF-8');
     $response->headers->set('Content-Length', strlen($content));
     return $response->setContent($content);
 }
 public function processAdaptation(\Symfony\Component\HttpFoundation\Response $response, $trkAjaxUrl)
 {
     $content = $response->getContent();
     $content = preg_replace('#(</body>)#', '<script type="text/javascript" src="' . $this->container->get('templating.helper.assets')->getUrl('bundles/skcmstracking/js/trk.js') . '"></script>' . '<script type="text/javascript">var trkAjaxUrl="' . $trkAjaxUrl . '";</script>' . '$1', $content);
     $response->setContent($content);
     return $response;
 }
Beispiel #18
0
 /**
  * Postprocess the rendered HTML: insert the snippets, and stuff.
  *
  * @param Response $response
  * @return string
  */
 public function postProcess(Response $response)
 {
     $html = $response->getContent();
     $html = $this->app['extensions']->processSnippetQueue($html);
     $this->cacheRequest($html);
     return $html;
 }
    /**
     * Injects the web debug toolbar into a given HTML string.
     *
     * @param string $content The HTML content
     *
     * @return Response A Response instance
     */
    protected function injectToolbar(Request $request, Response $response)
    {
        $data = '';
        foreach ($this->profiler->getCollectors() as $name => $collector) {
            $data .= $collector->getSummary();
        }
        $position = false === strpos($request->headers->get('user-agent'), 'Mobile') ? 'fixed' : 'absolute';
        $toolbar = <<<EOF

<!-- START of Symfony 2 Web Debug Toolbar -->
<div style="clear: both; height: 40px;"></div>
<div style="position: {$position}; bottom: 0px; left:0; z-index: 6000000; width: 100%; background: #dde4eb; border-top: 1px solid #bbb; padding: 5px; margin: 0; font: 11px Verdana, Arial, sans-serif; color: #222;">
    {$data}
</div>
<!-- END of Symfony 2 Web Debug Toolbar -->

EOF;
        $toolbar = "\n" . str_replace("\n", '', $toolbar) . "\n";
        $count = 0;
        $content = str_ireplace('</body>', $toolbar . '</body>', $response->getContent(), $count);
        if (!$count) {
            $content .= $toolbar;
        }
        return $content;
    }
Beispiel #20
0
 protected function jsonResponseToResponse(Response $response)
 {
     $content = $response->getContent();
     $status = $response->getStatusCode();
     $response = $response->headers->all();
     return new Response($content, $status, $response);
 }
Beispiel #21
0
 private function getPdfContent(PdfAnnotation $pdfAnnotation, Response $response, Request $request, $stylesheetContent)
 {
     try {
         $responseContent = $response->getContent();
         $pdfContent = null;
         if ($pdfAnnotation->enableCache) {
             $cacheKey = md5($responseContent . $stylesheetContent);
             if ($this->cache->test($cacheKey)) {
                 $pdfContent = $this->cache->load($cacheKey);
             }
         }
         if ($pdfContent === null) {
             $pdfFacade = $this->pdfFacadeBuilder->setDocumentParserType($pdfAnnotation->documentParserType)->build();
             $pdfContent = $pdfFacade->render($responseContent, $stylesheetContent);
             if ($pdfAnnotation->enableCache) {
                 $this->cache->save($pdfContent, $cacheKey);
             }
         }
         return $pdfContent;
     } catch (\Exception $e) {
         $request->setRequestFormat('html');
         $response->headers->set('content-type', 'text/html');
         throw $e;
     }
 }
Beispiel #22
0
 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();
 }
Beispiel #23
0
 /**
  * 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'));
 }
Beispiel #24
0
 /**
  * {@inheritdoc}
  */
 public function process(Request $request, Response $response)
 {
     $type = $response->headers->get('Content-Type');
     if (empty($type)) {
         $type = 'text/html';
     }
     $parts = explode(';', $type);
     if (!in_array($parts[0], $this->contentTypes)) {
         return $response;
     }
     // we don't use a proper XML parser here as we can have SSI tags in a plain text response
     $content = $response->getContent();
     $chunks = preg_split('#<!--\\#include\\s+(.*?)\\s*-->#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
     $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
     $i = 1;
     while (isset($chunks[$i])) {
         $options = array();
         preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
         foreach ($matches as $set) {
             $options[$set[1]] = $set[2];
         }
         if (!isset($options['virtual'])) {
             throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.');
         }
         $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, \'\', false) ?>' . "\n", var_export($options['virtual'], true));
         ++$i;
         $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
         ++$i;
     }
     $content = implode('', $chunks);
     $response->setContent($content);
     $response->headers->set('X-Body-Eval', 'SSI');
     // remove SSI/1.0 from the Surrogate-Control header
     $this->removeFromControl($response);
 }
 /**
  * @param string $content
  * @param int $status
  * @param array $headers
  * @return Response
  */
 function response_plain($content, $status = Response::HTTP_OK, array $headers = [])
 {
     // We have to do a little trick and do not allow WHMCS to sent all it's content.
     $response = new Response($content, $status, $headers);
     $response->sendHeaders();
     die($response->getContent());
 }
 public function after(Request $request, Response $response, Application $app)
 {
     if ($response->isRedirection()) {
         return;
     }
     // if ('application/json' === $request->headers->get('Accept')) {
     //     return $this->app()->json($this->data);
     // }
     //https://blog.yorunohikage.fr/
     //Pretty printing all JSON output in Silex PHP
     //if($response instanceof JsonResponse) {
     //    $response->setEncodingOptions(JSON_PRETTY_PRINT);
     //}
     if ($request->isXmlHttpRequest()) {
         $response_data = array('status' => 'OK', 'data' => $this->data);
         if (!is_null($this->error)) {
             $response_data['status'] = 'ERROR';
             $response_data['error'] = $this->error;
         }
         return $this->app->json($response_data);
     }
     if ($response->getContent() == '') {
         $this->initTwig();
         $response->setContent($this->twig()->render($this->template, $this->data));
     }
 }
 /**
  * @param  Response                                         $response
  * @return MethodFault|MethodResponse|MethodReturn
  * @throws \Seven\RpcBundle\Exception\InvalidJsonRpcVersion
  * @throws \Seven\RpcBundle\Exception\InvalidJsonRpcContent
  */
 public function createMethodResponse(Response $response)
 {
     $content = $response->getContent();
     if (empty($content)) {
         throw new InvalidJsonRpcContent('The JSON-RPC response is empty');
     }
     $data = json_decode($content, true);
     if (is_null($data)) {
         throw new InvalidJsonRpcContent('The JSON-RPC response is not valid', self::ERROR_PARSING);
     }
     if (empty($data['jsonrpc']) || version_compare($data['jsonrpc'], '2.0', '<')) {
         throw new InvalidJsonRpcVersion('The JSON-RPC response version is not supported');
     }
     if (isset($data['result'])) {
         return new MethodReturn($data['result']);
     } elseif (isset($data['error'])) {
         if (!isset($data['error']['message'])) {
             throw new InvalidJsonRpcContent('The JSON-RPC fault message is not passed');
         }
         if (!isset($data['error']['code'])) {
             throw new InvalidJsonRpcContent('The JSON-RPC fault code is not passed');
         }
         return new MethodFault(new Fault($data['error']['message'], $data['error']['code']));
     }
     throw new InvalidJsonRpcContent('The JSON-RPC response must have result or error properties');
 }
 /**
  * Injects the datatable scripts into the given HTTP Response.
  *
  * @param Response $response A Response instance
  */
 protected function _injectDatatableScript(Response $response, Request $request)
 {
     $content = $response->getContent();
     $pos_body = strripos($content, '</body>');
     if (!$pos_body) {
         return;
     }
     $session = $request->getSession();
     $dom = '<script id="alidatatable-scripts" type="text/javascript">';
     $pos_container = strripos($content, 'alidatatable-scripts');
     $sess_dta = $session->get('datatable');
     $dta_script = null;
     array_walk($sess_dta, function (&$part, &$key) {
         $part = trim(preg_replace('/\\s\\s+/', ' ', $part));
     });
     $dta_script = implode("\n", $sess_dta);
     $session->set('datatable', array());
     if (!$pos_container) {
         $dta_container = $dom;
         $content = substr_replace($content, $dta_container . '</script>', $pos_body, 0);
         $response->setContent($content);
     }
     $pos_dta = strripos($content, $dom);
     $content = substr_replace($content, $dta_script, $pos_dta + strlen($dom), 0);
     $response->setContent($content);
 }
Beispiel #29
0
 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());
 }
Beispiel #30
0
 private function transformResponse(Response $response)
 {
     $newContent = $this->markdown->transform($response->getContent());
     $response->setContent($newContent);
     $response->headers->set('Content-Type', 'text/html');
     return $response;
 }