当前位置: 首页>>代码示例>>PHP>>正文


PHP CacheableMetadata::createFromRenderArray方法代码示例

本文整理汇总了PHP中Drupal\Core\Cache\CacheableMetadata::createFromRenderArray方法的典型用法代码示例。如果您正苦于以下问题:PHP CacheableMetadata::createFromRenderArray方法的具体用法?PHP CacheableMetadata::createFromRenderArray怎么用?PHP CacheableMetadata::createFromRenderArray使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Drupal\Core\Cache\CacheableMetadata的用法示例。


在下文中一共展示了CacheableMetadata::createFromRenderArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: view

 /**
  * {@inheritdoc}
  *
  * @see ::prepareView()
  * @see ::getEntitiestoView()
  */
 public function view(FieldItemListInterface $items, $langcode = NULL)
 {
     $elements = parent::view($items, $langcode);
     $field_level_access_cacheability = new CacheableMetadata();
     // Try to map the cacheability of the access result that was set at
     // _accessCacheability in getEntitiesToView() to the corresponding render
     // subtree. If no such subtree is found, then merge it with the field-level
     // access cacheability.
     foreach ($items as $delta => $item) {
         // Ignore items for which access cacheability could not be determined in
         // prepareView().
         if (!empty($item->_accessCacheability)) {
             if (isset($elements[$delta])) {
                 CacheableMetadata::createFromRenderArray($elements[$delta])->merge($item->_accessCacheability)->applyTo($elements[$delta]);
             } else {
                 $field_level_access_cacheability = $field_level_access_cacheability->merge($item->_accessCacheability);
             }
         }
     }
     // Apply the cacheability metadata for the inaccessible entities and the
     // entities for which the corresponding render subtree could not be found.
     // This causes the field to be rendered (and cached) according to the cache
     // contexts by which the access results vary, to ensure only users with
     // access to this field can view it. It also tags this field with the cache
     // tags on which the access results depend, to ensure users that cannot view
     // this field at the moment will gain access once any of those cache tags
     // are invalidated.
     $field_level_access_cacheability->applyTo($elements);
     return $elements;
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:36,代码来源:EntityReferenceFormatterBase.php

示例2: createFromRenderArray

 /**
  * Creates a bubbleable metadata object with values taken from a render array.
  *
  * @param array $build
  *   A render array.
  *
  * @return static
  */
 public static function createFromRenderArray(array $build)
 {
     $meta = parent::createFromRenderArray($build);
     $meta->attached = isset($build['#attached']) ? $build['#attached'] : [];
     $meta->postRenderCache = isset($build['#post_render_cache']) ? $build['#post_render_cache'] : [];
     return $meta;
 }
开发者ID:nstielau,项目名称:drops-8,代码行数:15,代码来源:BubbleableMetadata.php

示例3: setContent

 /**
  * {@inheritdoc}
  */
 public function setContent($content)
 {
     // A render array can automatically be converted to a string and set the
     // necessary metadata.
     if (is_array($content) && isset($content['#markup'])) {
         $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));
         $this->setAttachments($content['#attached']);
         $content = $content['#markup'];
     }
     parent::setContent($content);
 }
开发者ID:RealLukeMartin,项目名称:drupal8tester,代码行数:14,代码来源:HtmlResponse.php

示例4: setContent

 /**
  * {@inheritdoc}
  */
 public function setContent($content)
 {
     // A render array can automatically be converted to a string and set the
     // necessary metadata.
     if (is_array($content) && isset($content['#markup'])) {
         $content += ['#attached' => ['html_response_attachment_placeholders' => [], 'placeholders' => []]];
         $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));
         $this->setAttachments($content['#attached']);
         $content = $content['#markup'];
     }
     return parent::setContent($content);
 }
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:15,代码来源:HtmlResponse.php

示例5: renderResponse

 /**
  * {@inheritdoc}
  */
 public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match)
 {
     $json = [];
     $json['content'] = (string) $this->renderer->renderRoot($main_content);
     if (!empty($main_content['#title'])) {
         $json['title'] = (string) $main_content['#title'];
     } else {
         $json['title'] = (string) $this->titleResolver->getTitle($request, $route_match->getRouteObject());
     }
     $response = new CacheableJsonResponse($json, 200);
     $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($main_content));
     return $response;
 }
开发者ID:sarahwillem,项目名称:OD8,代码行数:16,代码来源:JsonRenderer.php

示例6: buildSelectorForm

 /**
  * {@inheritdoc}
  */
 public function buildSelectorForm(array $form, FormStateInterface $form_state)
 {
     $form = parent::buildSelectorForm($form, $form_state);
     $available_plugins = [];
     $cacheability_metadata = CacheableMetadata::createFromRenderArray($form);
     foreach (array_keys($this->selectablePluginDiscovery->getDefinitions()) as $plugin_id) {
         $available_plugin = $this->selectablePluginFactory->createInstance($plugin_id);
         $available_plugins[] = $available_plugin;
         $cacheability_metadata = $cacheability_metadata->merge(CacheableMetadata::createFromObject($available_plugin));
     }
     $cacheability_metadata->applyTo($form);
     $plugin_selector_form_state_key = static::setPluginSelector($form_state, $this);
     $form['container'] = array('#attributes' => array('class' => array('plugin-selector-' . Html::getClass($this->getPluginId()))), '#available_plugins' => $available_plugins, '#plugin_selector_form_state_key' => $plugin_selector_form_state_key, '#process' => [[get_class(), 'processBuildSelectorForm']], '#tree' => TRUE, '#type' => 'container');
     return $form;
 }
开发者ID:nishantkumar155,项目名称:drupal8.crackle,代码行数:18,代码来源:AdvancedPluginSelectorBase.php

示例7: buildResponse

 /**
  * {@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();
     }
     $response->setContent($output);
     $cache_metadata = CacheableMetadata::createFromRenderArray($build);
     $response->addCacheableDependency($cache_metadata);
     return $response;
 }
开发者ID:ddrozdik,项目名称:dmaps,代码行数:21,代码来源:Feed.php

示例8: preRenderLink

 /**
  * Pre-render callback: Renders a link into #markup.
  *
  * Doing so during pre_render gives modules a chance to alter the link parts.
  *
  * @param array $element
  *   A structured array whose keys form the arguments to _l():
  *   - #title: The link text to pass as argument to _l().
  *   - #url: The URL info either pointing to a route or a non routed path.
  *   - #options: (optional) An array of options to pass to _l() or the link
  *     generator.
  *
  * @return array
  *   The passed-in element containing a rendered link in '#markup'.
  */
 public static function preRenderLink($element)
 {
     // By default, link options to pass to _l() are normally set in #options.
     $element += array('#options' => array());
     // However, within the scope of renderable elements, #attributes is a valid
     // way to specify attributes, too. Take them into account, but do not override
     // attributes from #options.
     if (isset($element['#attributes'])) {
         $element['#options'] += array('attributes' => array());
         $element['#options']['attributes'] += $element['#attributes'];
     }
     // This #pre_render callback can be invoked from inside or outside of a Form
     // API context, and depending on that, a HTML ID may be already set in
     // different locations. #options should have precedence over Form API's #id.
     // #attributes have been taken over into #options above already.
     if (isset($element['#options']['attributes']['id'])) {
         $element['#id'] = $element['#options']['attributes']['id'];
     } elseif (isset($element['#id'])) {
         $element['#options']['attributes']['id'] = $element['#id'];
     }
     // Conditionally invoke self::preRenderAjaxForm(), if #ajax is set.
     if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
         // If no HTML ID was found above, automatically create one.
         if (!isset($element['#id'])) {
             $element['#id'] = $element['#options']['attributes']['id'] = HtmlUtility::getUniqueId('ajax-link');
         }
         $element = static::preRenderAjaxForm($element);
     }
     if (!empty($element['#url']) && $element['#url'] instanceof CoreUrl) {
         $options = NestedArray::mergeDeep($element['#url']->getOptions(), $element['#options']);
         /** @var \Drupal\Core\Utility\LinkGenerator $link_generator */
         $link_generator = \Drupal::service('link_generator');
         $generated_link = $link_generator->generate($element['#title'], $element['#url']->setOptions($options), TRUE);
         $element['#markup'] = $generated_link->getGeneratedLink();
         $generated_link->merge(CacheableMetadata::createFromRenderArray($element))->applyTo($element);
     }
     return $element;
 }
开发者ID:nstielau,项目名称:drops-8,代码行数:53,代码来源:Link.php

示例9: responseToRenderArray

 /**
  * Embeds a Response object in a render array so that RenderCache can cache it.
  *
  * @param \Drupal\Core\Cache\CacheableResponseInterface $response
  *   A cacheable response.
  *
  * @return array
  *   A render array that embeds the given cacheable response object, with the
  *   cacheability metadata of the response object present in the #cache
  *   property of the render array.
  *
  * @see renderArrayToResponse()
  *
  * @todo Refactor/remove once https://www.drupal.org/node/2551419 lands.
  */
 protected function responseToRenderArray(CacheableResponseInterface $response)
 {
     $response_as_render_array = $this->dynamicPageCacheRedirectRenderArray + ['#response' => $response, '#cache_properties' => ['#response'], '#markup' => '', '#attached' => ''];
     // Merge the response's cacheability metadata, so that RenderCache can take
     // care of cache redirects for us.
     CacheableMetadata::createFromObject($response->getCacheableMetadata())->merge(CacheableMetadata::createFromRenderArray($response_as_render_array))->applyTo($response_as_render_array);
     return $response_as_render_array;
 }
开发者ID:sgtsaughter,项目名称:d8portfolio,代码行数:23,代码来源:DynamicPageCacheSubscriber.php

示例10: buildResponse

 /**
  * {@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);
     $response->headers->set('Content-type', $build['#content_type']);
     return $response;
 }
开发者ID:eigentor,项目名称:tommiblog,代码行数:19,代码来源:RestExport.php

示例11: setResponse

 /**
  * Prior to set the response it check if we can redirect.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event object.
  * @param \Drupal\Core\Url $url
  *   The Url where we want to redirect.
  */
 protected function setResponse(GetResponseEvent $event, Url $url)
 {
     $request = $event->getRequest();
     $this->context->fromRequest($request);
     parse_str($request->getQueryString(), $query);
     $url->setOption('query', $query);
     $url->setAbsolute(TRUE);
     // We can only check access for routed URLs.
     if (!$url->isRouted() || $this->checker->canRedirect($request, $url->getRouteName())) {
         // Add the 'rendered' cache tag, so that we can invalidate all responses
         // when settings are changed.
         $response = new TrustedRedirectResponse($url->toString(), 301);
         $response->addCacheableDependency(CacheableMetadata::createFromRenderArray([])->addCacheTags(['rendered']));
         $event->setResponse($response);
     }
 }
开发者ID:CIGIHub,项目名称:bsia-drupal8,代码行数:24,代码来源:RedirectRequestSubscriber.php

示例12: prepareResults

 /**
  * Prepares search results for rendering.
  *
  * @param \Drupal\Core\Database\StatementInterface $found
  *   Results found from a successful search query execute() method.
  *
  * @return array
  *   Array of search result item render arrays (empty array if no results).
  */
 protected function prepareResults(StatementInterface $found)
 {
     $results = array();
     $node_storage = $this->entityManager->getStorage('node');
     $node_render = $this->entityManager->getViewBuilder('node');
     $keys = $this->keywords;
     foreach ($found as $item) {
         // Render the node.
         /** @var \Drupal\node\NodeInterface $node */
         $node = $node_storage->load($item->sid)->getTranslation($item->langcode);
         $build = $node_render->view($node, 'search_result', $item->langcode);
         /** @var \Drupal\node\NodeTypeInterface $type*/
         $type = $this->entityManager->getStorage('node_type')->load($node->bundle());
         unset($build['#theme']);
         $build['#pre_render'][] = array($this, 'removeSubmittedInfo');
         // Fetch comments for snippet.
         $rendered = $this->renderer->renderPlain($build);
         $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
         $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]);
         $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]);
         $language = $this->languageManager->getLanguage($item->langcode);
         $username = array('#theme' => 'username', '#account' => $node->getOwner());
         $result = array('link' => $node->url('canonical', array('absolute' => TRUE, 'language' => $language)), 'type' => $type->label(), 'title' => $node->label(), 'node' => $node, 'extra' => $extra, 'score' => $item->calculated_score, 'snippet' => search_excerpt($keys, $rendered, $item->langcode), 'langcode' => $node->language()->getId());
         $this->addCacheableDependency($node);
         // We have to separately add the node owner's cache tags because search
         // module doesn't use the rendering system, it does its own rendering
         // without taking cacheability metadata into account. So we have to do it
         // explicitly here.
         $this->addCacheableDependency($node->getOwner());
         if ($type->displaySubmitted()) {
             $result += array('user' => $this->renderer->renderPlain($username), 'date' => $node->getChangedTime());
         }
         $results[] = $result;
     }
     return $results;
 }
开发者ID:ravibarnwal,项目名称:laraitassociate.in,代码行数:45,代码来源:NodeSearch.php

示例13: renderResponse

 /**
  * {@inheritdoc}
  *
  * The entire HTML: takes a #type 'page' and wraps it in a #type 'html'.
  */
 public function renderResponse(array $main_content, Request $request, RouteMatchInterface $route_match)
 {
     list($page, $title) = $this->prepare($main_content, $request, $route_match);
     if (!isset($page['#type']) || $page['#type'] !== 'page') {
         throw new \LogicException('Must be #type page');
     }
     $page['#title'] = $title;
     // Now render the rendered page.html.twig template inside the html.html.twig
     // template, and use the bubbled #attached metadata from $page to ensure we
     // load all attached assets.
     $html = ['#type' => 'html', 'page' => $page];
     // 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);
     // The three parts of rendered markup in html.html.twig (page_top, page and
     // page_bottom) must be rendered with drupal_render_root(), so that their
     // #post_render_cache callbacks are executed (which may attach additional
     // assets).
     // html.html.twig must be able to render the final list of attached assets,
     // and hence may not execute any #post_render_cache_callbacks (because they
     // might add yet more assets to be attached), and therefore it must be
     // rendered with drupal_render(), not drupal_render_root().
     $this->renderer->render($html['page'], TRUE);
     if (isset($html['page_top'])) {
         $this->renderer->render($html['page_top'], TRUE);
     }
     if (isset($html['page_bottom'])) {
         $this->renderer->render($html['page_bottom'], TRUE);
     }
     $content = $this->renderer->render($html);
     // Set the generator in the HTTP header.
     list($version) = explode('.', \Drupal::VERSION, 2);
     $response = new CacheableResponse($content, 200, ['Content-Type' => 'text/html; charset=UTF-8', 'X-Generator' => 'Drupal ' . $version . ' (https://www.drupal.org)']);
     // Bubble the cacheability metadata associated with the rendered render
     // arrays to the response.
     foreach (['page_top', 'page', 'page_bottom'] as $region) {
         if (isset($html[$region])) {
             $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($html[$region]));
         }
     }
     // Also associate the "rendered" cache tag. This allows us to invalidate the
     // entire render cache, regardless of the cache bin.
     $default = new CacheableMetadata();
     $default->setCacheTags(['rendered']);
     $response->addCacheableDependency($default);
     return $response;
 }
开发者ID:nstielau,项目名称:drops-8,代码行数:52,代码来源:HtmlRenderer.php

示例14: testCreateFromRenderArray

 /**
  * @covers ::createFromRenderArray
  * @dataProvider providerTestCreateFromRenderArray
  */
 public function testCreateFromRenderArray(array $render_array, CacheableMetadata $expected)
 {
     $this->assertEquals($expected, CacheableMetadata::createFromRenderArray($render_array));
 }
开发者ID:nstielau,项目名称:drops-8,代码行数:8,代码来源:CacheableMetadataTest.php

示例15: addCacheableDependency

 /**
  * {@inheritdoc}
  */
 public function addCacheableDependency(array &$elements, $dependency)
 {
     $meta_a = CacheableMetadata::createFromRenderArray($elements);
     $meta_b = CacheableMetadata::createFromObject($dependency);
     $meta_a->merge($meta_b)->applyTo($elements);
 }
开发者ID:nstielau,项目名称:drops-8,代码行数:9,代码来源:Renderer.php


注:本文中的Drupal\Core\Cache\CacheableMetadata::createFromRenderArray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。