executeInRenderContext example


  protected function executeQueryInRenderContext(QueryInterface $query, CacheableMetadata $query_cacheability) {
    $context = new RenderContext();
    $results = $this->renderer->executeInRenderContext($contextfunction D) use ($query) {
      return $query->execute();
    });
    if (!$context->isEmpty()) {
      $query_cacheability->addCacheableDependency($context->pop());
    }
    return $results;
  }

  /** * Gets the related resource. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type for the request to be served. * @param \Drupal\Core\Entity\FieldableEntityInterface $entity * The requested entity. * @param string $related * The related field name. * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * * @return \Drupal\jsonapi\ResourceResponse * The response. */

  public function renderRoot(&$elements) {
    // Disallow calling ::renderRoot() from within another ::renderRoot() call.     if ($this->isRenderingRoot) {
      $this->isRenderingRoot = FALSE;
      throw new \LogicException('A stray renderRoot() invocation is causing bubbling of attached assets to break.');
    }

    // Render in its own render context.     $this->isRenderingRoot = TRUE;
    $output = $this->executeInRenderContext(new RenderContext()function D) use (&$elements) {
      return $this->render($elements, TRUE);
    });
    $this->isRenderingRoot = FALSE;

    return $output;
  }

  /** * {@inheritdoc} */
  public function renderPlain(&$elements) {
    

  protected function processText($text$langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, array $filter_ids = ['media_embed']) {
    $manager = $this->container->get('plugin.manager.filter');
    $bag = new FilterPluginCollection($manager[]);
    $filters = [];
    foreach ($filter_ids as $filter_id) {
      $filters[] = $bag->get($filter_id);
    }

    $render_context = new RenderContext();
    /** @var \Drupal\filter\FilterProcessResult $filter_result */
    $filter_result = $this->container->get('renderer')->executeInRenderContext($render_contextfunction D) use ($text$filters$langcode) {
      $metadata = new BubbleableMetadata();
      foreach ($filters as $filter) {
        /** @var \Drupal\filter\FilterProcessResult $result */
        $result = $filter->process($text$langcode);
        $metadata = $metadata->merge($result);
        $text = $result->getProcessedText();
      }
      return (new FilterProcessResult($text))->merge($metadata);
    });
    if (!$render_context->isEmpty()) {
      $filter_result = $filter_result->merge($render_context->pop());
    }

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

    $view = Views::getView('test_field_tokens');
    $this->executeView($view);

    $random_text = $this->randomMachineName();
    $view->field['job']->setTestValue($random_text);
    $output = $renderer->executeInRenderContext(new RenderContext()function D) use ($view) {
      return $view->field['job']->theme($view->result[0]);
    });
    $this->assertEquals($random_text$output, 'Make sure the render method rendered the manual set value.');
  }

  /** * Tests all things related to the query. */
  public function testQuery() {
    // Tests adding additional fields to the query.     $view = Views::getView('test_view');
    

  public function testPlaceholderingDisabledForPostRequests($test_element$args) {
    $this->setUpUnusedCache();
    $this->setUpRequest('POST');

    $element = $test_element;

    // Render without replacing placeholders, to allow this test to see which     // #attached[placeholders] there are, if any.     $this->renderer->executeInRenderContext(new RenderContext()function D) use (&$element) {
      return $this->renderer->render($element);
    });
    // Only test cases where the placeholders have been specified manually are     // allowed to have placeholders. This means that of the different situations     // listed in providerPlaceholders(), only type B can have attached     // placeholders. Everything else, whether:     // 1. manual placeholdering     // 2. automatic placeholdering via already-present cacheability metadata     // 3. automatic placeholdering via bubbled cacheability metadata     // All three of those should NOT result in placeholders.     if (!isset($test_element['#attached']['placeholders'])) {
      
if (is_array($arg) && isset($arg['#type']) && $arg['#type'] === 'link') {
      $arg = Link::createFromRoute($arg['#title']$arg['#url']);
    }

    $context = new RenderContext();
    // Use a closure here since we need to render with a render context.     $theme_render_and_autoescape = function D) use ($arg) {
      return theme_render_and_autoescape($arg);
    };
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');
    $output = $renderer->executeInRenderContext($context$theme_render_and_autoescape);
    $this->assertEquals($expected$output);
    $this->assertIsString($output);
  }

  /** * Provide test examples. */
  public function providerTestThemeRenderAndAutoescape() {
    return [
      'empty string unchanged' => ['', ''],
      'simple string unchanged' => ['ab', 'ab'],
      

  public function testBuild(SvgIconBuilder $icon_builder$icon_map$expected) {
    $renderer = $this->container->get('renderer');

    $build = $icon_builder->build($icon_map);

    $output = (string) $renderer->executeInRenderContext(new RenderContext()function D) use ($build$renderer) {
      return $renderer->render($build);
    });
    $this->assertSame($expected$output);
  }

  public function providerTestBuild() {
    $data = [];
    $data['empty'][] = (new SvgIconBuilder());
    $data['empty'][] = [];
    $data['empty'][] = <<<'EOD' <svg width="125" height="150" class="layout-icon"></svg>


  /** * {@inheritdoc} */
  public function mail($module$key$to$langcode$params = []$reply = NULL, $send = TRUE) {
    // Mailing can invoke rendering (e.g., generating URLs, replacing tokens),     // but e-mails are not HTTP responses: they're not cached, they don't have     // attachments. Therefore we perform mailing inside its own render context,     // to ensure it doesn't leak into the render context for the HTTP response     // to the current request.     return $this->renderer->executeInRenderContext(new RenderContext()function D) use ($module$key$to$langcode$params$reply$send) {
      return $this->doMail($module$key$to$langcode$params$reply$send);
    });
  }

  /** * Composes and optionally sends an email message. * * @param string $module * A module name to invoke hook_mail() on. The {$module}_mail() hook will be * called to complete the $message structure which will already contain * common defaults. * @param string $key * A key to identify the email sent. The final message ID for email altering * will be {$module}_{$key}. * @param string $to * The email address or addresses where the message will be sent to. The * formatting of this string will be validated with the * @link http://php.net/manual/filter.filters.validate.php PHP email validation filter. @endlink * Some examples are: * - user@example.com * - user@example.com, anotheruser@example.com * - User <user@example.com> * - User <user@example.com>, Another User <anotheruser@example.com> * @param string $langcode * Language code to use to compose the email. * @param array $params * (optional) Parameters to build the email. Use the key '_error_message' * to provide translatable markup to display as a message if an error * occurs, or set this to false to disable error display. * @param string|null $reply * Optional email address to be used to answer. * @param bool $send * If TRUE, call an implementation of * \Drupal\Core\Mail\MailInterface->mail() to deliver the message, and * store the result in $message['result']. Modules implementing * hook_mail_alter() may cancel sending by setting $message['send'] to * FALSE. * * @return array * The $message array structure containing all details of the message. If * already sent ($send = TRUE), then the 'result' element will contain the * success indicator of the email, failure being already written to the * watchdog. (Success means nothing more than the message being accepted at * php-level, which still doesn't guarantee it to be delivered.) * * @see \Drupal\Core\Mail\MailManagerInterface::mail() */
protected function renderComponentRenderArray(array $component, ?BubbleableMetadata $metadata = NULL): Crawler {
    $component = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'sdc-wrapper',
      ],
      'component' => $component,
    ];
    $metadata = $metadata ?: new BubbleableMetadata();
    $context = new RenderContext();
    $renderer = \Drupal::service('renderer');
    $output = $renderer->executeInRenderContext($contextfn () => $renderer->render($component));
    if (!$context->isEmpty()) {
      $metadata->addCacheableDependency($context->pop());
    }
    return new Crawler((string) $output);
  }

}
'callable' => 'toolbar_menu_navigation_links'],
    ];
    $tree = $menu_tree->transform($tree$manipulators);
    $subtrees = [];
    // Calculated the combined cacheability of all subtrees.     $cacheability = CacheableMetadata::createFromRenderArray($data);
    foreach ($tree as $element) {
      /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
      $link = $element->link;
      if ($element->subtree) {
        $subtree = $menu_tree->build($element->subtree);
        $output = $renderer->executeInRenderContext(new RenderContext()function D) use ($renderer$subtree) {
          return $renderer->render($subtree);
        });
        $cacheability = $cacheability->merge(CacheableMetadata::createFromRenderArray($subtree));
      }
      else {
        $output = '';
      }
      // Many routes have dots as route name, while some special ones like       // <front> have <> characters in them.       $url = $link->getUrlObject();
      $id = str_replace(['.', '<', '>']['-', '', '']$url->isRouted() ? $url->getRouteName() : $url->getUri());

      


    return $safe_method_test_cases + $unsafe_method_bodied_test_cases + $unsafe_method_bodyless_test_cases;
  }

  /** * @return \Drupal\rest\EventSubscriber\ResourceResponseSubscriber */
  protected function getFunctioningResourceResponseSubscriber(RouteMatchInterface $route_match) {
    // Create a dummy of the renderer service.     $renderer = $this->prophesize(RendererInterface::class);
    $renderer->executeInRenderContext(Argument::type(RenderContext::class), Argument::type('callable'))
      ->will(function D$args) {
        $callable = $args[1];
        return $callable();
      });

    // Instantiate the ResourceResponseSubscriber we will test.     $resource_response_subscriber = new ResourceResponseSubscriber(
      new Serializer([][new JsonEncoder()new XmlEncoder()]),
      $renderer->reveal(),
      $route_match
    );

    


    // The special page regions will appear directly in html.html.twig, not in     // page.html.twig, hence add them here, just before rendering html.html.twig.     $this->buildPageTopAndBottom($html);

    // Render, but don't replace placeholders yet, because that happens later in     // the render pipeline. To not replace placeholders yet, we use     // RendererInterface::render() instead of RendererInterface::renderRoot().     // @see \Drupal\Core\Render\HtmlResponseAttachmentsProcessor.     $render_context = new RenderContext();
    $this->renderer->executeInRenderContext($render_contextfunction D) use (&$html) {
      // RendererInterface::render() renders the $html render array and updates       // it in place. We don't care about the return value (which is just       // $html['#markup']), but about the resulting render array.       // @todo Simplify this when https://www.drupal.org/node/2495001 lands.       $this->renderer->render($html);
    });
    // RendererInterface::render() always causes bubbleable metadata to be     // stored in the render context, no need to check it conditionally.     $bubbleable_metadata = $render_context->pop();
    $bubbleable_metadata->applyTo($html);
    $content = $this->renderCache->getCacheableRenderArray($html);

    
/** * Tests the caption filter with Twig debugging on. */
  public function testCaptionFilter() {
    $manager = $this->container->get('plugin.manager.filter');
    $bag = new FilterPluginCollection($manager[]);
    $filter = $bag->get('filter_caption');

    $renderer = $this->container->get('renderer');

    $test = function D$input) use ($filter$renderer) {
      return $renderer->executeInRenderContext(new RenderContext()function D) use ($input$filter) {
        return $filter->process($input, 'und');
      });
    };

    // No data-caption attribute.     $input = '<img src="llama.jpg" />';
    $expected = $input;
    $this->assertEquals($expected$test($input)->getProcessedText());

    // Data-caption attribute.     $input = '<img src="llama.jpg" data-caption="Loquacious llama!" />';
    
$this->executeView($view);
    $row = $view->result[0];
    $id_field = $view->field['id'];

    // Setup the general settings required to build a link.     $id_field->options['alter']['make_link'] = TRUE;
    $id_field->options['alter']['path'] = $path = $this->randomMachineName();

    // Tests that the suffix/prefix appears on the output.     $id_field->options['alter']['prefix'] = $prefix = $this->randomMachineName();
    $id_field->options['alter']['suffix'] = $suffix = $this->randomMachineName();
    $output = $renderer->executeInRenderContext(new RenderContext()function D) use ($id_field$row) {
      return $id_field->theme($row);
    });
    $this->assertSubString($output$prefix);
    $this->assertSubString($output$suffix);
    unset($id_field->options['alter']['prefix']);
    unset($id_field->options['alter']['suffix']);

    $output = $renderer->executeInRenderContext(new RenderContext()function D) use ($id_field$row) {
      return $id_field->theme($row);
    });
    $this->assertSubString($output$path, 'Make sure that the path is part of the output');

    
'#attached' => [
          'html_response_attachment_placeholders' => [
            'styles' => '<css-placeholder token="' . $placeholder_token . '">',
          ],
          'library' => [
            'media/oembed.frame',
          ],
        ],
        '#placeholder_token' => $placeholder_token,
      ];
      $context = new RenderContext();
      $content = $this->renderer->executeInRenderContext($contextfunction D) use ($element) {
        return $this->renderer->render($element);
      });
      $response
        ->setContent($content)
        ->setAttachments($element['#attached'])
        ->addCacheableDependency($resource)
        ->addCacheableDependency(CacheableMetadata::createFromRenderArray($element));

      // Modules and themes implementing hook_media_oembed_iframe_preprocess()       // can add additional #cache and #attachments to a render array. If this       // occurs, the render context won't be empty, and we need to ensure the
Home | Imprint | This part of the site doesn't use cookies.