本文整理汇总了PHP中Drupal\Core\Cache\CacheableMetadata::createFromObject方法的典型用法代码示例。如果您正苦于以下问题:PHP CacheableMetadata::createFromObject方法的具体用法?PHP CacheableMetadata::createFromObject怎么用?PHP CacheableMetadata::createFromObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\Core\Cache\CacheableMetadata
的用法示例。
在下文中一共展示了CacheableMetadata::createFromObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getVisibleBlocksPerRegion
/**
* {@inheritdoc}
*/
public function getVisibleBlocksPerRegion(array &$cacheable_metadata = [])
{
$active_theme = $this->themeManager->getActiveTheme();
// Build an array of the region names in the right order.
$empty = array_fill_keys($active_theme->getRegions(), array());
$full = array();
foreach ($this->blockStorage->loadByProperties(array('theme' => $active_theme->getName())) as $block_id => $block) {
/** @var \Drupal\block\BlockInterface $block */
$access = $block->access('view', NULL, TRUE);
$region = $block->getRegion();
if (!isset($cacheable_metadata[$region])) {
$cacheable_metadata[$region] = CacheableMetadata::createFromObject($access);
} else {
$cacheable_metadata[$region] = $cacheable_metadata[$region]->merge(CacheableMetadata::createFromObject($access));
}
// Set the contexts on the block before checking access.
if ($access->isAllowed()) {
$full[$region][$block_id] = $block;
}
}
// Merge it with the actual values to maintain the region ordering.
$assignments = array_intersect_key(array_merge($empty, $full), $empty);
foreach ($assignments as &$assignment) {
// Suppress errors because PHPUnit will indirectly modify the contents,
// triggering https://bugs.php.net/bug.php?id=50688.
@uasort($assignment, 'Drupal\\block\\Entity\\Block::sort');
}
return $assignments;
}
示例2: createFromObject
/**
* Creates a bubbleable metadata object from a depended object.
*
* @param \Drupal\Core\Cache\CacheableDependencyInterface|mixed $object
* The object whose cacheability metadata to retrieve. If it implements
* CacheableDependencyInterface, its cacheability metadata will be used,
* otherwise, the passed in object must be assumed to be uncacheable, so
* max-age 0 is set.
*
* @return static
*/
public static function createFromObject($object)
{
$meta = parent::createFromObject($object);
if ($object instanceof AttachmentsInterface) {
$meta->attachments = $object->getAttachments();
}
return $meta;
}
示例3: 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;
}
示例4: getEntitiesToView
/**
* Returns the referenced entities for display.
*
* The method takes care of:
* - checking entity access,
* - placing the entities in the language expected for display.
* It is thus strongly recommended that formatters use it in their
* implementation of viewElements($items) rather than dealing with $items
* directly.
*
* For each entity, the EntityReferenceItem by which the entity is referenced
* is available in $entity->_referringItem. This is useful for field types
* that store additional values next to the reference itself.
*
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items
* The item list.
* @param string $langcode
* The language code of the referenced entities to display.
*
* @return \Drupal\Core\Entity\EntityInterface[]
* The array of referenced entities to display, keyed by delta.
*
* @see ::prepareView()
*/
protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode)
{
$entities = array();
foreach ($items as $delta => $item) {
// Ignore items where no entity could be loaded in prepareView().
if (!empty($item->_loaded)) {
$entity = $item->entity;
// Set the entity in the correct language for display.
if ($entity instanceof TranslatableInterface) {
$entity = \Drupal::entityManager()->getTranslationFromContext($entity, $langcode);
}
$access = $this->checkAccess($entity);
// Add the access result's cacheability, ::view() needs it.
$item->_accessCacheability = CacheableMetadata::createFromObject($access);
if ($access->isAllowed()) {
// Add the referring item, in case the formatter needs it.
$entity->_referringItem = $items[$delta];
$entities[$delta] = $entity;
}
}
}
return $entities;
}
示例5: testCreateFromObject
/**
* @covers ::createFromObject
* @dataProvider providerTestCreateFromObject
*/
public function testCreateFromObject($object, CacheableMetadata $expected)
{
$this->assertEquals($expected, CacheableMetadata::createFromObject($object));
}
示例6: buildItems
/**
* Builds the #items property for a menu tree's renderable array.
*
* Helper function for ::build().
*
* @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
* A data structure representing the tree, as returned from
* MenuLinkTreeInterface::load().
* @param \Drupal\Core\Cache\CacheableMetadata &$tree_access_cacheability
* Internal use only. The aggregated cacheability metadata for the access
* results across the entire tree. Used when rendering the root level.
* @param \Drupal\Core\Cache\CacheableMetadata &$tree_link_cacheability
* Internal use only. The aggregated cacheability metadata for the menu
* links across the entire tree. Used when rendering the root level.
*
* @return array
* The value to use for the #items property of a renderable menu.
*
* @throws \DomainException
*/
protected function buildItems(array $tree, CacheableMetadata &$tree_access_cacheability, CacheableMetadata &$tree_link_cacheability)
{
$items = array();
foreach ($tree as $data) {
/** @var \Drupal\Core\Menu\MenuLinkInterface $link */
$link = $data->link;
// Generally we only deal with visible links, but just in case.
if (!$link->isEnabled()) {
continue;
}
if ($data->access !== NULL && !$data->access instanceof AccessResultInterface) {
throw new \DomainException('MenuLinkTreeElement::access must be either NULL or an AccessResultInterface object.');
}
// Gather the access cacheability of every item in the menu link tree,
// including inaccessible items. This allows us to render cache the menu
// tree, yet still automatically vary the rendered menu by the same cache
// contexts that the access results vary by.
// However, if $data->access is not an AccessResultInterface object, this
// will still render the menu link, because this method does not want to
// require access checking to be able to render a menu tree.
if ($data->access instanceof AccessResultInterface) {
$tree_access_cacheability = $tree_access_cacheability->merge(CacheableMetadata::createFromObject($data->access));
}
// Gather the cacheability of every item in the menu link tree. Some links
// may be dynamic: they may have a dynamic text (e.g. a "Hi, <user>" link
// text, which would vary by 'user' cache context), or a dynamic route
// name or route parameters.
$tree_link_cacheability = $tree_link_cacheability->merge(CacheableMetadata::createFromObject($data->link));
// Only render accessible links.
if ($data->access instanceof AccessResultInterface && !$data->access->isAllowed()) {
continue;
}
$element = [];
// Set a variable for the <li> tag. Only set 'expanded' to true if the
// link also has visible children within the current tree.
$element['is_expanded'] = FALSE;
$element['is_collapsed'] = FALSE;
if ($data->hasChildren && !empty($data->subtree)) {
$element['is_expanded'] = TRUE;
} elseif ($data->hasChildren) {
$element['is_collapsed'] = TRUE;
}
// Set a helper variable to indicate whether the link is in the active
// trail.
$element['in_active_trail'] = FALSE;
if ($data->inActiveTrail) {
$element['in_active_trail'] = TRUE;
}
// Note: links are rendered in the menu.html.twig template; and they
// automatically bubble their associated cacheability metadata.
$element['attributes'] = new Attribute();
$element['title'] = $link->getTitle();
$element['url'] = $link->getUrlObject();
$element['url']->setOption('set_active_class', TRUE);
$element['below'] = $data->subtree ? $this->buildItems($data->subtree, $tree_access_cacheability, $tree_link_cacheability) : array();
if (isset($data->options)) {
$element['url']->setOptions(NestedArray::mergeDeep($element['url']->getOptions(), $data->options));
}
$element['original_link'] = $link;
// Index using the link's unique ID.
$items[$link->getPluginId()] = $element;
}
return $items;
}
示例7: 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);
}
示例8: 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;
}
示例9: process
/**
* {@inheritdoc}
*/
public function process($text, $langcode)
{
$result = new FilterProcessResult($text);
if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $node) {
/** @var \DOMElement $node */
$entity_type = $node->getAttribute('data-entity-type');
$entity = NULL;
$entity_output = '';
try {
// Load the entity either by UUID (preferred) or ID.
$id = $node->getAttribute('data-entity-uuid') ?: $node->getAttribute('data-entity-id');
$entity = $this->loadEntity($entity_type, $id);
if ($entity) {
// Protect ourselves from recursive rendering.
static $depth = 0;
$depth++;
if ($depth > 20) {
throw new RecursiveRenderingException(sprintf('Recursive rendering detected when rendering embedded %s entity %s.', $entity_type, $entity->id()));
}
// If a UUID was not used, but is available, add it to the HTML.
if (!$node->getAttribute('data-entity-uuid') && ($uuid = $entity->uuid())) {
$node->setAttribute('data-entity-uuid', $uuid);
}
$access = $entity->access('view', NULL, TRUE);
$access_metadata = CacheableMetadata::createFromObject($access);
$entity_metadata = CacheableMetadata::createFromObject($entity);
$result = $result->merge($entity_metadata)->merge($access_metadata);
$context = $this->getNodeAttributesAsArray($node);
$context += array('data-langcode' => $langcode);
$entity_output = $this->renderEntityEmbed($entity, $context);
$depth--;
} else {
throw new EntityNotFoundException(sprintf('Unable to load embedded %s entity %s.', $entity_type, $id));
}
} catch (\Exception $e) {
watchdog_exception('entity_embed', $e);
}
$this->replaceNodeContent($node, $entity_output);
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
示例10: calculateCacheMetadata
/**
* {@inheritdoc}
*/
public function calculateCacheMetadata()
{
$cache_metadata = new CacheableMetadata();
// Iterate over ordinary views plugins.
foreach (Views::getPluginTypes('plugin') as $plugin_type) {
$plugin = $this->getPlugin($plugin_type);
if ($plugin instanceof CacheableDependencyInterface) {
$cache_metadata = $cache_metadata->merge(CacheableMetadata::createFromObject($plugin));
}
}
// Iterate over all handlers. Note that at least the argument handler will
// need to ask all its subplugins.
foreach (array_keys(Views::getHandlerTypes()) as $handler_type) {
$handlers = $this->getHandlers($handler_type);
foreach ($handlers as $handler) {
if ($handler instanceof CacheableDependencyInterface) {
$cache_metadata = $cache_metadata->merge(CacheableMetadata::createFromObject($handler));
}
}
}
/** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
if ($cache_plugin = $this->getPlugin('cache')) {
$cache_plugin->alterCacheMetadata($cache_metadata);
}
return $cache_metadata;
}
示例11: build
/**
* {@inheritdoc}
*/
public function build()
{
/** @var $entity \Drupal\Core\Entity\EntityInterface */
$entity = $this->getContextValue('entity');
$view_builder = $this->entityManager->getViewBuilder($entity->getEntityTypeId());
$build = $view_builder->view($entity, $this->configuration['view_mode']);
CacheableMetadata::createFromObject($this->getContext('entity'))->applyTo($build);
return $build;
}
示例12: assertGenerateFromRoute
/**
* Asserts \Drupal\Core\Routing\UrlGenerator::generateFromRoute()'s output.
*
* @param $route_name
* The route name to test.
* @param array $route_parameters
* The route parameters to test.
* @param array $options
* The options to test.
* @param $expected_url
* The expected generated URL string.
* @param \Drupal\Core\Cache\CacheableMetadata $expected_cacheability
* The expected generated cacheability metadata.
*/
protected function assertGenerateFromRoute($route_name, array $route_parameters, array $options, $expected_url, CacheableMetadata $expected_cacheability)
{
// First, test with $collect_cacheability_metadata set to the default value.
$url = $this->generator->generateFromRoute($route_name, $route_parameters, $options);
$this->assertSame($expected_url, $url);
// Second, test with it set to TRUE.
$generated_url = $this->generator->generateFromRoute($route_name, $route_parameters, $options, TRUE);
$this->assertSame($expected_url, $generated_url->getGeneratedUrl());
$this->assertEquals($expected_cacheability, CacheableMetadata::createFromObject($generated_url));
}
示例13: addCacheableDependency
/**
* {@inheritdoc}
*/
public function addCacheableDependency($dependency)
{
$this->cacheabilityMetadata = $this->cacheabilityMetadata->merge(CacheableMetadata::createFromObject($dependency));
return $this;
}
示例14: doLoadMultiple
/**
* {@inheritdoc}
*/
protected function doLoadMultiple(array $ids = NULL)
{
$prefix = $this->getPrefix();
// Get the names of the configuration entities we are going to load.
if ($ids === NULL) {
$names = $this->configFactory->listAll($prefix);
} else {
$names = array();
foreach ($ids as $id) {
// Add the prefix to the ID to serve as the configuration object name.
$names[] = $prefix . $id;
}
}
// Load all of the configuration entities.
/** @var \Drupal\Core\Config\Config[] $configs */
$configs = [];
$records = [];
foreach ($this->configFactory->loadMultiple($names) as $config) {
$id = $config->get($this->idKey);
$records[$id] = $this->overrideFree ? $config->getOriginal(NULL, FALSE) : $config->get();
$configs[$id] = $config;
}
$entities = $this->mapFromStorageRecords($records, $configs);
// Config entities wrap config objects, and therefore they need to inherit
// the cacheability metadata of config objects (to ensure e.g. additional
// cacheability metadata added by config overrides is not lost).
foreach ($entities as $id => $entity) {
// But rather than simply inheriting all cacheability metadata of config
// objects, we need to make sure the self-referring cache tag that is
// present on Config objects is not added to the Config entity. It must be
// removed for 3 reasons:
// 1. When renaming/duplicating a Config entity, the cache tag of the
// original config object would remain present, which would be wrong.
// 2. Some Config entities choose to not use the cache tag that the under-
// lying Config object provides by default (For performance and
// cacheability reasons it may not make sense to have a unique cache
// tag for every Config entity. The DateFormat Config entity specifies
// the 'rendered' cache tag for example, because A) date formats are
// changed extremely rarely, so invalidating all render cache items is
// fine, B) it means fewer cache tags per page.).
// 3. Fewer cache tags is better for performance.
$self_referring_cache_tag = ['config:' . $configs[$id]->getName()];
$config_cacheability = CacheableMetadata::createFromObject($configs[$id]);
$config_cacheability->setCacheTags(array_diff($config_cacheability->getCacheTags(), $self_referring_cache_tag));
$entity->addCacheableDependency($config_cacheability);
}
return $entities;
}
示例15: valueForm
/**
* {@inheritdoc}
*/
protected function valueForm(&$form, FormStateInterface $form_state) {
parent::valueForm($form, $form_state);
// Apply cacheability metadata, because the parent class does not.
// @todo Remove this once https://www.drupal.org/node/2754103 is fixed.
$cacheability_metdata = CacheableMetadata::createFromObject($this);
$cacheability_metdata->applyTo($form);
return $form;
}