getContent() public method

Gets the current response content.
public getContent ( ) : string
return string Content
Exemplo n.º 1
0
 public function assertSuccess()
 {
     if ($this->response->getStatusCode() != 200) {
         $this->fail($this->response->getContent());
     }
     return $this;
 }
Exemplo n.º 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());
 }
Exemplo n.º 3
0
 /**
  * @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());
 }
Exemplo n.º 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);
     }
 }
Exemplo n.º 6
0
 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());
 }
Exemplo n.º 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;
 }
Exemplo n.º 10
0
 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);
 }
Exemplo n.º 12
0
 /**
  * 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);
     }
 }
Exemplo n.º 15
0
 /**
  * @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()));
     }
 }
Exemplo n.º 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);
 }
Exemplo n.º 17
0
 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;
 }
Exemplo n.º 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;
    }
Exemplo n.º 20
0
 protected function jsonResponseToResponse(Response $response)
 {
     $content = $response->getContent();
     $status = $response->getStatusCode();
     $response = $response->headers->all();
     return new Response($content, $status, $response);
 }
Exemplo n.º 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;
     }
 }
Exemplo n.º 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();
 }
Exemplo n.º 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'));
 }
Exemplo n.º 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);
 }
Exemplo n.º 25
0
 /**
  * @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());
 }
Exemplo n.º 26
0
 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');
 }
Exemplo n.º 28
0
 /**
  * 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);
 }
Exemplo n.º 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());
 }
Exemplo n.º 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;
 }