本文整理汇总了PHP中Drupal\Core\Render\BubbleableMetadata类的典型用法代码示例。如果您正苦于以下问题:PHP BubbleableMetadata类的具体用法?PHP BubbleableMetadata怎么用?PHP BubbleableMetadata使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了BubbleableMetadata类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: processOutbound
/**
* {@inheritdoc}
*/
public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL)
{
if ($route_name === '<current>') {
if ($current_route = $this->routeMatch->getRouteObject()) {
$requirements = $current_route->getRequirements();
// Setting _method and _schema is deprecated since 2.7. Using
// setMethods() and setSchemes() are now the recommended ways.
unset($requirements['_method']);
unset($requirements['_schema']);
$route->setRequirements($requirements);
$route->setPath($current_route->getPath());
$route->setSchemes($current_route->getSchemes());
$route->setMethods($current_route->getMethods());
$route->setOptions($current_route->getOptions());
$route->setDefaults($current_route->getDefaults());
$parameters = array_merge($parameters, $this->routeMatch->getRawParameters()->all());
if ($bubbleable_metadata) {
$bubbleable_metadata->addCacheContexts(['route']);
}
} else {
// If we have no current route match available, point to the frontpage.
$route->setPath('/');
}
}
}
示例2: providerTestCreateFromRenderArray
/**
* Provides test data for createFromRenderArray().
*
* @return array
*/
public function providerTestCreateFromRenderArray()
{
$data = [];
$empty_metadata = new BubbleableMetadata();
$nonempty_metadata = new BubbleableMetadata();
$nonempty_metadata->setCacheContexts(['qux'])->setCacheTags(['foo:bar'])->setAssets(['settings' => ['foo' => 'bar']]);
$empty_render_array = [];
$nonempty_render_array = ['#cache' => ['contexts' => ['qux'], 'tags' => ['foo:bar'], 'max-age' => Cache::PERMANENT], '#attached' => ['settings' => ['foo' => 'bar']], '#post_render_cache' => []];
$data[] = [$empty_render_array, $empty_metadata];
$data[] = [$nonempty_render_array, $nonempty_metadata];
return $data;
}
示例3: processOutbound
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
{
if (array_key_exists('purl_context', $options) && $options['purl_context'] == false) {
if (count($this->matchedModifiers->getMatched()) && $bubbleable_metadata) {
$cacheContexts = $bubbleable_metadata->getCacheContexts();
$cacheContexts[] = 'purl';
$bubbleable_metadata->setCacheContexts($cacheContexts);
}
return $this->contextHelper->processOutbound($this->matchedModifiers->createContexts(Context::EXIT_CONTEXT), $path, $options, $request, $bubbleable_metadata);
}
return $this->contextHelper->processOutbound($this->matchedModifiers->createContexts(), $path, $options, $request, $bubbleable_metadata);
}
示例4: processOutbound
/**
* Implements Drupal\Core\PathProcessor\OutboundPathProcessorInterface::processOutbound().
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
{
// Rewrite user/uid to user/username.
if (preg_match('!^/user/([0-9]+)(/.*)?!', $path, $matches)) {
if ($account = User::load($matches[1])) {
$matches += array(2 => '');
$path = '/user/' . $account->getUsername() . $matches[2];
if ($bubbleable_metadata) {
$bubbleable_metadata->addCacheTags($account->getCacheTags());
}
}
}
// Rewrite forum/ to community/.
return preg_replace('@^/forum(.*)@', '/community$1', $path);
}
示例5: processLinkitAutocomplete
/**
* Adds linkit custom autocomplete functionality to elements.
*
* Instead of using the core autocomplete, we use our own.
*
* {@inheritdoc}
*
* @see \Drupal\Core\Render\Element\FormElement::processAutocomplete
*/
public static function processLinkitAutocomplete(&$element, FormStateInterface $form_state, &$complete_form) {
$url = NULL;
$access = FALSE;
if (!empty($element['#autocomplete_route_name'])) {
$parameters = isset($element['#autocomplete_route_parameters']) ? $element['#autocomplete_route_parameters'] : array();
$url = Url::fromRoute($element['#autocomplete_route_name'], $parameters)->toString(TRUE);
/** @var \Drupal\Core\Access\AccessManagerInterface $access_manager */
$access_manager = \Drupal::service('access_manager');
$access = $access_manager->checkNamedRoute($element['#autocomplete_route_name'], $parameters, \Drupal::currentUser(), TRUE);
}
if ($access) {
$metadata = BubbleableMetadata::createFromRenderArray($element);
if ($access->isAllowed()) {
$element['#attributes']['class'][] = 'form-linkit-autocomplete';
$metadata->addAttachments(['library' => ['linkit/linkit.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;
}
示例6: testTokenReplacement
/**
* Tests core token replacements generated from a view.
*/
function testTokenReplacement()
{
$token_handler = \Drupal::token();
$view = Views::getView('test_tokens');
$view->setDisplay('page_1');
$this->executeView($view);
$expected = array('[view:label]' => 'Test tokens', '[view:description]' => 'Test view to token replacement tests.', '[view:id]' => 'test_tokens', '[view:title]' => 'Test token page', '[view:url]' => $view->getUrl(NULL, 'page_1')->setAbsolute(TRUE)->toString(), '[view:total-rows]' => (string) $view->total_rows, '[view:base-table]' => 'views_test_data', '[view:base-field]' => 'id', '[view:items-per-page]' => '10', '[view:current-page]' => '1', '[view:page-count]' => '1');
$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;
$metadata_tests['[view:page-count]'] = $base_bubbleable_metadata;
foreach ($expected as $token => $expected_output) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $token_handler->replace($token, array('view' => $view), [], $bubbleable_metadata);
$this->assertIdentical($output, $expected_output, format_string('Token %token replaced correctly.', array('%token' => $token)));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$token]);
}
}
示例7: testSystemSiteTokenReplacement
/**
* Tests the generation of all system site information tokens.
*/
public function testSystemSiteTokenReplacement()
{
$url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage);
$slogan = '<blink>Slogan</blink>';
$safe_slogan = Xss::filterAdmin($slogan);
// Set a few site variables.
$config = $this->config('system.site');
$config->set('name', '<strong>Drupal<strong>')->set('slogan', $slogan)->set('mail', 'simpletest@example.com')->save();
// Generate and test tokens.
$tests = array();
$tests['[site:name]'] = Html::escape($config->get('name'));
$tests['[site:slogan]'] = $safe_slogan;
$tests['[site:mail]'] = $config->get('mail');
$tests['[site:url]'] = \Drupal::url('<front>', [], $url_options);
$tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', \Drupal::url('<front>', [], $url_options));
$tests['[site:login-url]'] = \Drupal::url('user.page', [], $url_options);
$base_bubbleable_metadata = new BubbleableMetadata();
$metadata_tests = [];
$metadata_tests['[site:name]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
$metadata_tests['[site:slogan]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
$metadata_tests['[site:mail]'] = BubbleableMetadata::createFromObject(\Drupal::config('system.site'));
$bubbleable_metadata = clone $base_bubbleable_metadata;
$metadata_tests['[site:url]'] = $bubbleable_metadata->addCacheContexts(['url.site']);
$metadata_tests['[site:url-brief]'] = $bubbleable_metadata;
$metadata_tests['[site:login-url]'] = $bubbleable_metadata;
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$bubbleable_metadata = new BubbleableMetadata();
$output = $this->tokenService->replace($input, array(), array('langcode' => $this->interfaceLanguage->getId()), $bubbleable_metadata);
$this->assertEqual($output, $expected, new FormattableMarkup('System site information token %token replaced.', ['%token' => $input]));
$this->assertEqual($bubbleable_metadata, $metadata_tests[$input]);
}
}
示例8: filter
/**
* {@inheritdoc}
*/
public function filter(DataDefinitionInterface $definition, $value, array $arguments, BubbleableMetadata $bubbleable_metadata = NULL)
{
if ($definition->getDataType() != 'timestamp') {
// Convert the date to an timestamp.
$value = $this->getTypedDataManager()->create($definition, $value)->getDateTime()->getTimestamp();
}
$arguments += [0 => 'medium', 1 => '', 2 => NULL, 3 => NULL];
if ($arguments[0] != 'custom' && $bubbleable_metadata) {
$config = $this->dateFormatStorage->load($arguments[0]);
if (!$config) {
throw new \InvalidArgumentException("Unknown date format {$arguments['0']} given.");
}
$bubbleable_metadata->addCacheableDependency($config);
}
return $this->dateFormatter->format($value, $arguments[0], $arguments[1], $arguments[2], $arguments[3]);
}
示例9: build
/**
* {@inheritdoc}
*/
public function build()
{
// Grab test attachment fixtures from
// Drupal\render_attached_test\Controller\RenderAttachedTestController.
$controller = new RenderAttachedTestController();
$attached = BubbleableMetadata::mergeAttachments($controller->feed(), $controller->head());
$attached = BubbleableMetadata::mergeAttachments($attached, $controller->header());
$attached = BubbleableMetadata::mergeAttachments($attached, $controller->teapotHeaderStatus());
// Return some arbitrary markup so the block doesn't disappear.
$attached['#markup'] = 'Markup from attached_rendering_block.';
return $attached;
}
示例10: build
/**
* {@inheritdoc}
*/
public function build()
{
// Grab test attachment fixtures from
// Drupal\render_attached_test\Controller\TestController.
$controller = new TestController();
$attached = BubbleableMetadata::mergeAttachments($controller->feed(), $controller->head());
$attached = BubbleableMetadata::mergeAttachments($attached, $controller->header());
$attached = BubbleableMetadata::mergeAttachments($attached, $controller->teapotHeaderStatus());
// Use drupal_process_attached() to attach all the #attached stuff.
drupal_process_attached($attached);
// Return some arbitrary markup so the block doesn't disappear.
return ['#markup' => 'Headers handled by drupal_process_attached().'];
}
示例11: processOutbound
/**
* {@inheritdoc}
*/
public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL)
{
if ($route->hasRequirement('_csrf_token')) {
$path = ltrim($route->getPath(), '/');
// Replace the path parameters with values from the parameters array.
foreach ($parameters as $param => $value) {
$path = str_replace("{{$param}}", $value, $path);
}
// Adding this to the parameters means it will get merged into the query
// string when the route is compiled.
if (!$bubbleable_metadata) {
$parameters['token'] = $this->csrfToken->get($path);
} else {
// Generate a placeholder and a render array to replace it.
$placeholder = hash('sha1', $path);
$placeholder_render_array = ['#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]]];
// Instead of setting an actual CSRF token as the query string, we set
// the placeholder, which will be replaced at the very last moment. This
// ensures links with CSRF tokens don't break cacheability.
$parameters['token'] = $placeholder;
$bubbleable_metadata->addAttachments(['placeholders' => [$placeholder => $placeholder_render_array]]);
}
}
}
示例12: addCommand
/**
* Add an AJAX command to the response.
*
* @param \Drupal\Core\Ajax\CommandInterface $command
* An AJAX command object implementing CommandInterface.
* @param bool $prepend
* A boolean which determines whether the new command should be executed
* before previously added commands. Defaults to FALSE.
*
* @return AjaxResponse
* The current AjaxResponse.
*/
public function addCommand(CommandInterface $command, $prepend = FALSE)
{
if ($prepend) {
array_unshift($this->commands, $command->render());
} else {
$this->commands[] = $command->render();
}
if ($command instanceof CommandWithAttachedAssetsInterface) {
$assets = $command->getAttachedAssets();
$attachments = ['library' => $assets->getLibraries(), 'drupalSettings' => $assets->getSettings()];
$attachments = BubbleableMetadata::mergeAttachments($this->getAttachments(), $attachments);
$this->setAttachments($attachments);
}
return $this;
}
示例13: hook_tokens
/**
* Provide replacement values for placeholder tokens.
*
* This hook is invoked when someone calls
* \Drupal\Core\Utility\Token::replace(). That function first scans the text for
* [type:token] patterns, and splits the needed tokens into groups by type.
* Then hook_tokens() is invoked on each token-type group, allowing your module
* to respond by providing replacement text for any of the tokens in the group
* that your module knows how to process.
*
* A module implementing this hook should also implement hook_token_info() in
* order to list its available tokens on editing screens.
*
* @param $type
* The machine-readable name of the type (group) of token being replaced, such
* as 'node', 'user', or another type defined by a hook_token_info()
* implementation.
* @param $tokens
* An array of tokens to be replaced. The keys are the machine-readable token
* names, and the values are the raw [type:token] strings that appeared in the
* original text.
* @param array $data
* An associative array of data objects to be used when generating replacement
* values, as supplied in the $data parameter to
* \Drupal\Core\Utility\Token::replace().
* @param array $options
* An associative array of options for token replacement; see
* \Drupal\Core\Utility\Token::replace() for possible values.
* @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
* The bubbleable metadata. Prior to invoking this hook,
* \Drupal\Core\Utility\Token::generate() collects metadata for all of the
* data objects in $data. For any data sources not in $data, but that are
* used by the token replacement logic, such as global configuration (e.g.,
* 'system.site') and related objects (e.g., $node->getOwner()),
* implementations of this hook must add the corresponding metadata.
* For example:
* @code
* $bubbleable_metadata->addCacheableDependency(\Drupal::config('system.site'));
* $bubbleable_metadata->addCacheableDependency($node->getOwner());
* @endcode
*
* Additionally, implementations of this hook, must forward
* $bubbleable_metadata to the chained tokens that they invoke.
* For example:
* @code
* if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
* $replacements = $token_service->generate('date', $created_tokens, array('date' => $node->getCreatedTime()), $options, $bubbleable_metadata);
* }
* @endcode
*
* @return array
* An associative array of replacement values, keyed by the raw [type:token]
* strings from the original text.
*
* @see hook_token_info()
* @see hook_tokens_alter()
*/
function hook_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata)
{
$token_service = \Drupal::token();
$url_options = array('absolute' => TRUE);
if (isset($options['langcode'])) {
$url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
$langcode = $options['langcode'];
} else {
$langcode = NULL;
}
$sanitize = !empty($options['sanitize']);
$replacements = array();
if ($type == 'node' && !empty($data['node'])) {
/** @var \Drupal\node\NodeInterface $node */
$node = $data['node'];
foreach ($tokens as $name => $original) {
switch ($name) {
// Simple key values on the node.
case 'nid':
$replacements[$original] = $node->nid;
break;
case 'title':
$replacements[$original] = $sanitize ? Html::escape($node->getTitle()) : $node->getTitle();
break;
case 'edit-url':
$replacements[$original] = $node->url('edit-form', $url_options);
break;
// Default values for the chained tokens handled below.
// Default values for the chained tokens handled below.
case 'author':
$account = $node->getOwner() ? $node->getOwner() : User::load(0);
$replacements[$original] = $sanitize ? Html::escape($account->label()) : $account->label();
$bubbleable_metadata->addCacheableDependency($account);
break;
case 'created':
$replacements[$original] = format_date($node->getCreatedTime(), 'medium', '', NULL, $langcode);
break;
}
}
if ($author_tokens = $token_service->findWithPrefix($tokens, 'author')) {
$replacements = $token_service->generate('user', $author_tokens, array('user' => $node->getOwner()), $options, $bubbleable_metadata);
}
if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
//.........这里部分代码省略.........
示例14: 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
* \Drupal\Core\Utility\LinkGeneratorInterface::generate():
* - #title: The link text.
* - #url: The URL info either pointing to a route or a non routed path.
* - #options: (optional) An array of options to pass to 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 the link generator 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));
$element['#markup'] = $generated_link->getGeneratedLink();
$generated_link->merge(BubbleableMetadata::createFromRenderArray($element))->applyTo($element);
}
return $element;
}
示例15: processOutbound
/**
* {@inheritdoc}
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
{
if ($request) {
// The following values are not supposed to change during a single page
// request processing.
if (!isset($this->queryRewrite)) {
if ($this->currentUser->isAnonymous()) {
$languages = $this->languageManager->getLanguages();
$config = $this->config->get('language.negotiation')->get('session');
$this->queryParam = $config['parameter'];
$this->queryValue = $request->query->has($this->queryParam) ? $request->query->get($this->queryParam) : NULL;
$this->queryRewrite = isset($languages[$this->queryValue]);
} else {
$this->queryRewrite = FALSE;
}
}
// If the user is anonymous, the user language negotiation method is
// enabled, and the corresponding option has been set, we must preserve
// any explicit user language preference even with cookies disabled.
if ($this->queryRewrite) {
if (isset($options['query']) && is_string($options['query'])) {
$query = array();
parse_str($options['query'], $query);
$options['query'] = $query;
}
if (!isset($options['query'][$this->queryParam])) {
$options['query'][$this->queryParam] = $this->queryValue;
}
if ($bubbleable_metadata) {
// Cached URLs that have been processed by this outbound path
// processor must be:
$bubbleable_metadata->addCacheTags($this->config->get('language.negotiation')->getCacheTags())->addCacheContexts(['url.query_args:' . $this->queryParam]);
}
}
}
return $path;
}