CacheableResponse example


  public function content(Request $request) {
    if ($request->getRequestFormat() === 'json' && $request->query->get('_wrapper_format') === 'drupal_ajax') {
      $response = new CacheableAjaxResponse(['content' => 'oh hai this is ajax']);
    }
    elseif ($request->getRequestFormat() === 'json') {
      $response = new CacheableJsonResponse(['content' => 'oh hai this is json']);
    }
    else {
      $response = new CacheableResponse("<p>oh hai this is html.</p>");
    }
    $response->addCacheableDependency((new CacheableMetadata())->addCacheContexts(['url.query_args:_wrapper_format']));
    return $response;
  }

}

  protected function flattenResponse(ResourceResponseInterface $response) {
    $final_response = ($response instanceof CacheableResponseInterface) ? new CacheableResponse() : new Response();
    $final_response->setContent($response->getContent());
    $final_response->setStatusCode($response->getStatusCode());
    $final_response->setProtocolVersion($response->getProtocolVersion());
    if ($response->getCharset()) {
      $final_response->setCharset($response->getCharset());
    }
    $final_response->headers = clone $response->headers;
    if ($final_response instanceof CacheableResponseInterface) {
      $final_response->addCacheableDependency($response->getCacheableMetadata());
    }
    return $final_response;
  }
<?php
namespace Drupal\default_format_test;

use Drupal\Core\Cache\CacheableResponse;
use Symfony\Component\HttpFoundation\Request;

class DefaultFormatTestController {

  public function content(Request $request) {
    $format = $request->getRequestFormat();
    return new CacheableResponse('format:' . $format, 200, ['Content-Type' => $request->getMimeType($format)]);
  }

}
public function authorizeInit($page_title) {
    $authorize_url = Url::fromUri('base:core/authorize.php', ['absolute' => TRUE])->toString();
    system_authorized_init('system_test_authorize_run', __DIR__ . '/../../system_test.module', []$page_title);
    return new RedirectResponse($authorize_url);
  }

  /** * Sets a header. */
  public function setHeader(Request $request) {
    $query = $request->query->all();
    $response = new CacheableResponse();
    $response->headers->set($query['name']$query['value']);
    $response->getCacheableMetadata()->addCacheContexts(['url.query_args:name', 'url.query_args:value']);
    $response->setContent($this->t('The following header was set: %name: %value', ['%name' => $query['name'], '%value' => $query['value']]));

    return $response;
  }

  /** * A simple page callback that uses a plain Symfony response object. */
  public function respondWithResponse(Request $request) {
    
return 'feed';
  }

  /** * {@inheritdoc} */
  public static function buildResponse($view_id$display_id, array $args = []) {
    $build = static::buildBasicRenderable($view_id$display_id$args);

    // Set up an empty response, so for example RSS can set the proper     // Content-Type header.     $response = new CacheableResponse('', 200);
    $build['#response'] = $response;

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $output = (string) $renderer->renderRoot($build);

    if (empty($output)) {
      throw new NotFoundHttpException();
    }

    
&& (!$route_has_format || array_intersect($route_formats$view_route_formats) != []);
  }

  /** * {@inheritdoc} */
  public static function buildResponse($view_id$display_id, array $args = []) {
    $build = static::buildBasicRenderable($view_id$display_id$args);

    // Setup an empty response so headers can be added as needed during views     // rendering and processing.     $response = new CacheableResponse('', 200);
    $build['#response'] = $response;

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

    $output = (string) $renderer->renderRoot($build);

    $response->setContent($output);
    $cache_metadata = CacheableMetadata::createFromRenderArray($build);
    $response->addCacheableDependency($cache_metadata);

    
return new Response('foobar');
  }

  /** * A route returning a CacheableResponse object. * * @return \Drupal\Core\Cache\CacheableResponseInterface * A CacheableResponseInterface object. */
  public function cacheableResponse() {
    $user = User::load(1);
    $response = new CacheableResponse($user->label());
    $response->addCacheableDependency($user);
    return $response;
  }

  /** * A route returning a render array (without cache contexts, so cacheable). * * @return array * A render array. */
  public function html() {
    

  public function on4xx(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    if ($exception && $exception instanceof HttpExceptionInterface && str_starts_with($exception->getStatusCode(), '4')) {
      $message = PlainTextOutput::renderFromHtml($exception->getMessage());
      // If the exception is cacheable, generate a cacheable response.       if ($exception instanceof CacheableDependencyInterface) {
        $response = new CacheableResponse($message$exception->getStatusCode()['Content-Type' => 'text/plain']);
        $response->addCacheableDependency($exception);
      }
      else {
        $response = new Response($message$exception->getStatusCode()['Content-Type' => 'text/plain']);
      }

      $response->headers->add($exception->getHeaders());
      $event->setResponse($response);
    }
  }

  

  protected static function flattenResponse(ResourceResponse $response, Request $request) {
    $final_response = ($response instanceof CacheableResponseInterface && $request->isMethodCacheable()) ? new CacheableResponse() : new Response();
    $final_response->setContent($response->getContent());
    $final_response->setStatusCode($response->getStatusCode());
    $final_response->setProtocolVersion($response->getProtocolVersion());
    if ($charset = $response->getCharset()) {
      $final_response->setCharset($charset);
    }
    $final_response->headers = clone $response->headers;
    if ($final_response instanceof CacheableResponseInterface) {
      $final_response->addCacheableDependency($response->getCacheableMetadata());
    }
    return $final_response;
  }
$format = $request->getRequestFormat();
    $content = ['message' => $exception->getMessage()];
    $encoded_content = $this->serializer->serialize($content$format);
    $headers = $exception->getHeaders();

    // Add the MIME type from the request to send back in the header.     $headers['Content-Type'] = $request->getMimeType($format);

    // If the exception is cacheable, generate a cacheable response.     if ($exception instanceof CacheableDependencyInterface) {
      $response = new CacheableResponse($encoded_content$exception->getStatusCode()$headers);
      $response->addCacheableDependency($exception);
    }
    else {
      $response = new Response($encoded_content$exception->getStatusCode()$headers);
    }

    $event->setResponse($response);
  }

}
'contexts' => ['url'],
        'tags' => ['foo'],
        'max-age' => 60,
      ],
      'content' => [
        '#markup' => 'test18',
      ],
    ];
  }

  public function test21() {
    return new CacheableResponse('test21');
  }

  public function test23() {
    return new Psr7Response(200, [], 'test23');
  }

  public function test24() {
    $this->removeExceptionLogger();
    throw new \Exception('Escaped content: <p> <br> <h3>');
  }

  
Home | Imprint | This part of the site doesn't use cookies.