createFromObject example


  protected function bubbleArgMetadata($arg) {
    // If it's a renderable, then it'll be up to the generated render array it     // returns to contain the necessary cacheability & attachment metadata. If     // it doesn't implement CacheableDependencyInterface or AttachmentsInterface     // then there is nothing to do here.     if ($arg instanceof RenderableInterface || !($arg instanceof CacheableDependencyInterface || $arg instanceof AttachmentsInterface)) {
      return;
    }

    $arg_bubbleable = [];
    BubbleableMetadata::createFromObject($arg)
      ->applyTo($arg_bubbleable);

    $this->renderer->render($arg_bubbleable);
  }

  /** * Wrapper around render() for twig printed output. * * If an object is passed which does not implement __toString(), * RenderableInterface or toString() then an exception is thrown; * Other objects are casted to string. However in the case that the * object is an instance of a \Twig\Markup object it is returned directly * to support auto escaping. * * If an array is passed it is rendered via render() and scalar values are * returned directly. * * @param mixed $arg * String, Object or Render Array. * * @throws \Exception * When $arg is passed as an object which does not implement __toString(), * RenderableInterface or toString(). * * @return mixed * The rendered output or a \Twig\Markup object. * * @see render * @see TwigNodeVisitor */
// Generate and test sanitized tokens for term1.     $tests = [];
    $tests['[term:tid]'] = $term1->id();
    $tests['[term:name]'] = $term1->getName();
    $tests['[term:description]'] = $term1->description->processed;
    $tests['[term:url]'] = $term1->toUrl('canonical', ['absolute' => TRUE])->toString();
    $tests['[term:node-count]'] = 0;
    $tests['[term:parent:name]'] = '[term:parent:name]';
    $tests['[term:vocabulary:name]'] = $this->vocabulary->label();
    $tests['[term:vocabulary]'] = $this->vocabulary->label();

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($term1);

    $metadata_tests = [];
    $metadata_tests['[term:tid]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:name]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:description]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:url]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:node-count]'] = $base_bubbleable_metadata;
    $metadata_tests['[term:parent:name]'] = $base_bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $metadata_tests['[term:vocabulary:name]'] = $bubbleable_metadata->addCacheTags($this->vocabulary->getCacheTags());
    $metadata_tests['[term:vocabulary]'] = $bubbleable_metadata->addCacheTags($this->vocabulary->getCacheTags());

    
'#cache' => [
        'max-age' => $max_age,
      ],
    ];
    $this->assertEquals($expected$object->toRenderable());

    // Test retrieving the formatted time difference string.     $this->assertEquals($string$object->getString());

    // Test applying cacheability data to an existing build.     $build = [];
    CacheableMetadata::createFromObject($object)->applyTo($build);
    $this->assertEquals($max_age$build['#cache']['max-age']);
  }

  /** * Tests that an RFC2822 formatted date always returns an English string. * * @see http://www.faqs.org/rfcs/rfc2822.html * * @covers ::format */
  public function testRfc2822DateFormat(): void {
    
    $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));

    $request_stack->push($request);
    $request_context->fromRequest($request);
    $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/');
    $this->assertEquals($this->urlGenerator->generateFromRoute('<current>', [][], TRUE)$url);

    // Test request with subdir on other page.     $server = [
      'SCRIPT_NAME' => '/subdir/index.php',
      'SCRIPT_FILENAME' => $this->root . '/index.php',
      'SERVER_NAME' => 'http://www.example.com',
    ];
    $request = Request::create('/subdir/node/add', 'GET', [][][]$server);
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));

    
/** * Throws a cacheable error exception. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which a revision was requested. * @param string $resource_version_identifier * The user input for the revision negotiation. * * @throws \Drupal\Core\Http\Exception\CacheableNotFoundHttpException */
  protected static function throwNotFoundHttpException(EntityInterface $entity$resource_version_identifier) {
    $cacheability = CacheableMetadata::createFromObject($entity)->addCacheContexts(['url.path', 'url.query_args:' . ResourceVersionRouteEnhancer::RESOURCE_VERSION_QUERY_PARAMETER]);
    $reason = sprintf('The requested version, identified by `%s`, could not be found.', $resource_version_identifier);
    throw new CacheableNotFoundHttpException($cacheability$reason);
  }

  /** * Throws a cacheable error exception. * * @param string $resource_version_identifier * The user input for the revision negotiation. * * @throws \Drupal\Core\Http\Exception\CacheableBadRequestHttpException */
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;
      }
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()[]);

    $full = [];
    foreach ($this->blockStorage->loadByProperties(['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;
      }
    }

    

          ],
        ];

        // An empty title attribute will disable title inheritance, so only         // add it if the resource has a title.         $title = $resource->getTitle();
        if ($title) {
          $element[$delta]['#attributes']['title'] = $title;
        }

        CacheableMetadata::createFromObject($resource)
          ->addCacheTags($this->config->getCacheTags())
          ->applyTo($element[$delta]);
      }
    }
    return $element;
  }

  /** * {@inheritdoc} */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    
$tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime()['langcode' => $language_interface->getId()]);
    $tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations()['langcode' => $language_interface->getId()]);
    $tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
    $tests['[comment:parent:title]'] = $parent_comment->getSubject();
    $tests['[comment:entity]'] = Html::escape($node->getTitle());
    // Test node specific tokens.     $tests['[comment:entity:nid]'] = $comment->getCommentedEntityId();
    $tests['[comment:entity:title]'] = Html::escape($node->getTitle());
    $tests['[comment:author:uid]'] = $comment->getOwnerId();
    $tests['[comment:author:name]'] = Html::escape($this->adminUser->getDisplayName());

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($comment);
    $metadata_tests = [];
    $metadata_tests['[comment:cid]'] = $base_bubbleable_metadata;
    $metadata_tests['[comment:hostname]'] = $base_bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $bubbleable_metadata->addCacheableDependency($this->adminUser);
    $metadata_tests['[comment:author]'] = $bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $bubbleable_metadata->addCacheableDependency($this->adminUser);
    $metadata_tests['[comment:mail]'] = $bubbleable_metadata;
    $metadata_tests['[comment:homepage]'] = $base_bubbleable_metadata;
    $metadata_tests['[comment:title]'] = $base_bubbleable_metadata;
    
$cacheability->addCacheableDependency($entity);
        if ($entity instanceof FieldableEntityInterface) {
          foreach ($entity as $field_name => $field_item_list) {
            /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
            if (is_null($sparse_fieldset) || in_array($field_name$sparse_fieldset)) {
              $field_access = static::entityFieldAccess($entity$field_name, 'view', $account);
              $cacheability->addCacheableDependency($field_access);
              if ($field_access->isAllowed()) {
                foreach ($field_item_list as $field_item) {
                  /** @var \Drupal\Core\Field\FieldItemInterface $field_item */
                  foreach (TypedDataInternalPropertiesHelper::getNonInternalProperties($field_item) as $property) {
                    $cacheability->addCacheableDependency(CacheableMetadata::createFromObject($property));
                  }
                }
              }
            }
          }
        }
      }
      return $cacheability;
    }new CacheableMetadata());
    $entity_type = reset($collection)->getEntityType();
    $cacheability->addCacheTags(['http_response']);
    
      // 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;
  }

  /** * {@inheritdoc} */
  protected function doCreate(array $values) {
    
if ($access) {
      $metadata = BubbleableMetadata::createFromRenderArray($element);
      if ($access->isAllowed()) {
        $element['#attributes']['class'][] = 'form-autocomplete';
        $metadata->addAttachments(['library' => ['core/drupal.autocomplete']]);
        // Provide a data attribute for the JavaScript behavior to bind to.         $element['#attributes']['data-autocomplete-path'] = $url->getGeneratedUrl();
        $metadata = $metadata->merge($url);
      }
      $metadata
        ->merge(BubbleableMetadata::createFromObject($access))
        ->applyTo($element);
    }

    return $element;
  }

}
'[view:id]' => 'test_tokens',
      '[view:title]' => 'Test token page',
      '[view:url]' => $view->getUrl(NULL, 'page_1')->setAbsolute(TRUE)->toString(),
      '[view:total-rows]' => '5',
      '[view:base-table]' => 'views_test_data',
      '[view:base-field]' => 'id',
      '[view:items-per-page]' => '4',
      '[view:current-page]' => '1',
      '[view:page-count]' => '2',
    ];

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($view->storage);
    $metadata_tests = [];
    $metadata_tests['[view:label]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:description]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:id]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:title]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:url]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:total-rows]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:base-table]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:base-field]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:items-per-page]'] = $base_bubbleable_metadata;
    $metadata_tests['[view:current-page]'] = $base_bubbleable_metadata;
    
/** * {@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));
        }
      }
/** * {@inheritdoc} */
  public function addCacheableDependency($dependency) {
    // A trait doesn't have a constructor, so initialize the cacheability     // metadata if that hasn't happened yet.     if (!isset($this->cacheabilityMetadata)) {
      $this->cacheabilityMetadata = new CacheableMetadata();
    }

    $this->cacheabilityMetadata = $this->cacheabilityMetadata->merge(CacheableMetadata::createFromObject($dependency));

    return $this;
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    // A trait doesn't have a constructor, so initialize the cacheability     // metadata if that hasn't happened yet.     if (!isset($this->cacheabilityMetadata)) {
      
Home | Imprint | This part of the site doesn't use cookies.