HtmlResponse example

$this->sendNoJsPlaceholders($pre_scripts_bottom . $post_scripts_bottom$no_js_placeholders$cumulative_assets);

    // If additional asset libraries or drupalSettings were attached by any of     // the placeholders, then we need to re-render scripts_bottom.     if ($cumulative_assets_initial != $cumulative_assets) {
      // Create a new HtmlResponse. Ensure the CSS and (non-bottom) JS is sent       // before the HTML they're associated with.       // @see \Drupal\Core\Render\HtmlResponseSubscriber       // @see template_preprocess_html()       $js_bottom_placeholder = '<nojs-bigpipe-placeholder-scripts-bottom-placeholder token="' . Crypt::randomBytesBase64(55) . '">';

      $html_response = new HtmlResponse();
      $html_response->setContent([
        '#markup' => BigPipeMarkup::create($js_bottom_placeholder),
        '#attached' => [
          'drupalSettings' => $cumulative_assets->getSettings(),
          'library' => $cumulative_assets->getAlreadyLoadedLibraries(),
          'html_response_attachment_placeholders' => [
            'scripts_bottom' => $js_bottom_placeholder,
          ],
        ],
      ]);
      $html_response->getCacheableMetadata()->setCacheMaxAge(0);

      

  public function testHandleWithPostRequest() {
    $request = Request::create('/test', 'POST', ['name' => 'druplicon', 'pass' => '12345']);

    $request_context = new RequestContext();
    $request_context->fromRequest($request);
    $this->accessUnawareRouter->expects($this->any())
      ->method('getContext')
      ->willReturn($request_context);

    $this->kernel->expects($this->once())->method('handle')->willReturnCallback(function DRequest $request) {
      return new HtmlResponse($request->getMethod());
    });

    $event = new ExceptionEvent($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST, new NotFoundHttpException('foo'));

    $this->customPageSubscriber->onException($event);

    $response = $event->getResponse();
    $result = $response->getContent() . " " . UrlHelper::buildQuery($request->request->all());
    $this->assertEquals('POST name=druplicon&pass=12345', $result);
    $this->assertEquals(AccessResult::allowed()->addCacheTags(['foo', 'bar'])$request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT));
  }

  
$content = $this->renderCache->getCacheableRenderArray($html);

    // Also associate the required cache contexts.     // (Because we use ::render() above and not ::renderRoot(), we manually must     // ensure the HTML response varies by the required cache contexts.)     $content['#cache']['contexts'] = Cache::mergeContexts($content['#cache']['contexts']$this->rendererConfig['required_cache_contexts']);

    // Also associate the "rendered" cache tag. This allows us to invalidate the     // entire render cache, regardless of the cache bin.     $content['#cache']['tags'][] = 'rendered';

    $response = new HtmlResponse($content, 200, [
      'Content-Type' => 'text/html; charset=UTF-8',
    ]);

    return $response;
  }

  /** * Prepares the HTML body: wraps the main content in #type 'page'. * * @param array $main_content * The render array representing the main content. * @param \Symfony\Component\HttpFoundation\Request $request * The request object, for context. * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * The route match, for context. * * @return array * An array with two values: * 0. A #type 'page' render array. * 1. The page title. * * @throws \LogicException * If the selected display variant does not implement PageVariantInterface. */
'AjaxResponse, which implements AttachmentsInterface' => [AjaxResponse::class],
      'A dummy that implements AttachmentsInterface' => [get_class((new Prophet())->prophesize(AttachmentsInterface::class)->reveal())],
    ];
  }

  /** * @covers ::processAttachments * * @dataProvider attachmentsProvider */
  public function testHtmlResponse(array $attachments) {
    $big_pipe_response = new BigPipeResponse(new HtmlResponse('original'));
    $big_pipe_response->setAttachments($attachments);

    // This mock is the main expectation of this test: verify that the decorated     // service (that is this mock) never receives BigPipe placeholder     // attachments, because it doesn't know (nor should it) how to handle them.     $html_response_attachments_processor = $this->prophesize(AttachmentsResponseProcessorInterface::class);
    $html_response_attachments_processor->processAttachments(Argument::that(function D$response) {
      return $response instanceof HtmlResponse && empty(array_intersect(['big_pipe_placeholders', 'big_pipe_nojs_placeholders']array_keys($response->getAttachments())));
    }))
      ->will(function D$args) {
        /** @var \Symfony\Component\HttpFoundation\Response|\Drupal\Core\Render\AttachmentsInterface $response */
        

  public function on404(ExceptionEvent $event) {
    $request = $event->getRequest();

    $config = $this->configFactory->get('system.performance');
    $exclude_paths = $config->get('fast_404.exclude_paths');
    if ($config->get('fast_404.enabled') && $exclude_paths && !preg_match($exclude_paths$request->getPathInfo())) {
      $fast_paths = $config->get('fast_404.paths');
      if ($fast_paths && preg_match($fast_paths$request->getPathInfo())) {
        $fast_404_html = strtr($config->get('fast_404.html')['@path' => Html::escape($request->getUri())]);
        $response = new HtmlResponse($fast_404_html, Response::HTTP_NOT_FOUND);
        // Some routes such as system.files conditionally throw a         // NotFoundHttpException depending on URL parameters instead of just the         // route and route parameters, so add the URL cache context to account         // for this.         $cacheable_metadata = new CacheableMetadata();
        $cacheable_metadata->setCacheContexts(['url']);
        $cacheable_metadata->addCacheTags(['4xx-response']);
        $response->addCacheableDependency($cacheable_metadata);
        $event->setResponse($response);
      }
    }
  }
$session = $this->prophesize(SessionInterface::class);
    $session->start()->willReturn(TRUE);
    $session->save()->shouldBeCalled();
    $bigpipe = new BigPipe(
      $this->prophesize(RendererInterface::class)->reveal(),
      $session->reveal(),
      $this->prophesize(RequestStack::class)->reveal(),
      $this->prophesize(HttpKernelInterface::class)->reveal(),
      $this->prophesize(EventDispatcherInterface::class)->reveal(),
      $this->prophesize(ConfigFactoryInterface::class)->reveal()
    );
    $response = new BigPipeResponse(new HtmlResponse());

    // Add many placeholders.     $many_placeholders = [];
    for ($i = 0; $i < 400; $i++) {
      $many_placeholders[$this->randomMachineName(80)] = $this->randomMachineName(80);
    }
    $attachments = [
      'library' => [],
      'big_pipe_nojs_placeholders' => $many_placeholders,
    ];
    $response->setAttachments($attachments);

    
// Hash the URL and max dimensions, and ensure it is equal to the hash     // parameter passed in the query string.     $hash = $this->iFrameUrlHelper->getHash($url$max_width$max_height);
    if (!hash_equals($hash$request->query->get('hash', ''))) {
      throw new BadRequestHttpException('This resource is not available');
    }

    // Return a response instead of a render array so that the frame content     // will not have all the blocks and page elements normally rendered by     // Drupal.     $response = new HtmlResponse('', HtmlResponse::HTTP_OK, [
      'Content-Type' => 'text/html; charset=UTF-8',
    ]);
    $response->addCacheableDependency(Url::createFromRequest($request));

    try {
      $resource_url = $this->urlResolver->getResourceUrl($url$max_width$max_height);
      $resource = $this->resourceFetcher->fetchResource($resource_url);

      $placeholder_token = Crypt::randomBytesBase64(55);

      // Render the content in a new render context so that the cacheability
// For backwards compatibility.     // @todo In Drupal 9, add a $show_messages function parameter.     if (!isset($page_additions['#show_messages']) || $page_additions['#show_messages'] === TRUE) {
      $html['page']['highlighted'] = ['#type' => 'status_messages'];
    }

    // Add the bare minimum of attachments from the system module and the     // current maintenance theme.     system_page_attachments($html['page']);
    $this->renderer->renderRoot($html);

    $response = new HtmlResponse();
    $response->setContent($html);
    // Process attachments, because this does not go via the regular render     // pipeline, but will be sent directly.     $response = $this->htmlResponseAttachmentsProcessor->processAttachments($response);
    return $response;
  }

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