本文整理汇总了PHP中Drupal\Core\Url类的典型用法代码示例。如果您正苦于以下问题:PHP Url类的具体用法?PHP Url怎么用?PHP Url使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Url类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state)
{
$forum_config = $this->config('forum.settings');
$vid = $forum_config->get('vocabulary');
$vocabulary = $this->entityManager->getStorage('taxonomy_vocabulary')->load($vid);
if (!$vocabulary) {
throw new NotFoundHttpException();
}
// Build base taxonomy term overview.
$form = parent::buildForm($form, $form_state, $vocabulary);
foreach (Element::children($form['terms']) as $key) {
if (isset($form['terms'][$key]['#term'])) {
$term = $form['terms'][$key]['#term'];
$form['terms'][$key]['term']['#url'] = Url::fromRoute('forum.page', ['taxonomy_term' => $term->id()]);
unset($form['terms'][$key]['operations']['#links']['delete']);
$route_parameters = $form['terms'][$key]['operations']['#links']['edit']['url']->getRouteParameters();
if (!empty($term->forum_container->value)) {
$form['terms'][$key]['operations']['#links']['edit']['title'] = $this->t('edit container');
$form['terms'][$key]['operations']['#links']['edit']['url'] = Url::fromRoute('entity.taxonomy_term.forum_edit_container_form', $route_parameters);
} else {
$form['terms'][$key]['operations']['#links']['edit']['title'] = $this->t('edit forum');
$form['terms'][$key]['operations']['#links']['edit']['url'] = Url::fromRoute('entity.taxonomy_term.forum_edit_form', $route_parameters);
}
// We don't want the redirect from the link so we can redirect the
// delete action.
unset($form['terms'][$key]['operations']['#links']['edit']['query']['destination']);
}
}
// Remove the alphabetical reset.
unset($form['actions']['reset_alphabetical']);
// Use the existing taxonomy overview submit handler.
$form['terms']['#empty'] = $this->t('No containers or forums available. <a href="@container">Add container</a> or <a href="@forum">Add forum</a>.', array('@container' => $this->url('forum.add_container'), '@forum' => $this->url('forum.add_forum')));
return $form;
}
示例2: assertPageCacheContextsAndTags
/**
* Asserts page cache miss, then hit for the given URL; checks cache headers.
*
* @param \Drupal\Core\Url $url
* The URL to test.
* @param string[] $expected_contexts
* The expected cache contexts for the given URL.
* @param string[] $expected_tags
* The expected cache tags for the given URL.
*/
protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
{
$absolute_url = $url->setAbsolute()->toString();
sort($expected_contexts);
sort($expected_tags);
// Assert cache miss + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$this->assertCacheTags($expected_tags);
$this->assertCacheContexts($expected_contexts);
// Assert cache hit + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$this->assertCacheTags($expected_tags);
$this->assertCacheContexts($expected_contexts);
// Assert page cache item + expected cache tags.
$cid_parts = array($url->setAbsolute()->toString(), 'html');
$cid = implode(':', $cid_parts);
$cache_entry = \Drupal::cache('render')->get($cid);
sort($cache_entry->tags);
$this->assertEqual($cache_entry->tags, $expected_tags);
if ($cache_entry->tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
}
}
示例3: generate
/**
* {@inheritdoc}
*
* For anonymous users, the "active" class will be calculated on the server,
* because most sites serve each anonymous user the same cached page anyway.
* For authenticated users, the "active" class will be calculated on the
* client (through JavaScript), only data- attributes are added to links to
* prevent breaking the render cache. The JavaScript is added in
* system_page_attachments().
*
* @see system_page_attachments()
*/
public function generate($text, Url $url, $collect_cacheability_metadata = FALSE)
{
// Performance: avoid Url::toString() needing to retrieve the URL generator
// service from the container.
$url->setUrlGenerator($this->urlGenerator);
// Start building a structured representation of our link to be altered later.
$variables = array('text' => is_array($text) ? drupal_render($text) : $text, 'url' => $url, 'options' => $url->getOptions());
// Merge in default options.
$variables['options'] += array('attributes' => array(), 'query' => array(), 'language' => NULL, 'set_active_class' => FALSE, 'absolute' => FALSE);
// Add a hreflang attribute if we know the language of this link's url and
// hreflang has not already been set.
if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {
$variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();
}
// Set the "active" class if the 'set_active_class' option is not empty.
if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {
// Add a "data-drupal-link-query" attribute to let the
// drupal.active-link library know the query in a standardized manner.
if (!empty($variables['options']['query'])) {
$query = $variables['options']['query'];
ksort($query);
$variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);
}
// Add a "data-drupal-link-system-path" attribute to let the
// drupal.active-link library know the path in a standardized manner.
if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {
// @todo System path is deprecated - use the route name and parameters.
$system_path = $url->getInternalPath();
// Special case for the front page.
$variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;
}
}
// Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
// only when a quick strpos() gives suspicion tags are present.
if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
$variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
}
// Allow other modules to modify the structure of the link.
$this->moduleHandler->alter('link', $variables);
// Move attributes out of options since generateFromRoute() doesn't need
// them. Include a placeholder for the href.
$attributes = array('href' => '') + $variables['options']['attributes'];
unset($variables['options']['attributes']);
$url->setOptions($variables['options']);
if (!$collect_cacheability_metadata) {
$url_string = $url->toString($collect_cacheability_metadata);
} else {
$generated_url = $url->toString($collect_cacheability_metadata);
$url_string = $generated_url->getGeneratedUrl();
$generated_link = GeneratedLink::createFromObject($generated_url);
}
// The result of the URL generator is a plain-text URL to use as the href
// attribute, and it is escaped by \Drupal\Core\Template\Attribute.
$attributes['href'] = $url_string;
$result = SafeMarkup::format('<a@attributes>@text</a>', array('@attributes' => new Attribute($attributes), '@text' => $variables['text']));
return $collect_cacheability_metadata ? $generated_link->setGeneratedLink($result) : $result;
}
示例4: basicAuthGet
/**
* Performs a HTTP request with Basic authentication.
*
* We do not use \Drupal\simpletest\WebTestBase::drupalGet because we need to
* set curl settings for basic authentication.
*
* @param \Drupal\Core\Url $url
* A Url object.
* @param string $username
* The user name to authenticate with.
* @param string $password
* The password.
* @param string $mime_type
* The MIME type for the Accept header.
*
* @return string
* Curl output.
*/
protected function basicAuthGet(Url $url, $username, $password, $mime_type = NULL)
{
if (!isset($mime_type)) {
$mime_type = $this->defaultMimeType;
}
$out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $url->setAbsolute()->toString(), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $username . ':' . $password, CURLOPT_HTTPHEADER => array('Accept: ' . $mime_type)));
$this->verbose('GET request to: ' . $url->toString() . '<hr />' . $out);
return $out;
}
示例5: deleteSubmit
/**
* Submits the delete form.
*/
public function deleteSubmit(array &$form, FormStateInterface $form_state)
{
$url = new Url('path.delete', array('pid' => $form_state->getValue('pid')));
if ($this->getRequest()->query->has('destination')) {
$url->setOption('query', $this->getDestinationArray());
$this->getRequest()->query->remove('destination');
}
$form_state->setRedirectUrl($url);
}
示例6: testUrlBubbleableMetadataBubbling
/**
* Tests bubbling of cacheable metadata for URLs.
*
* @param bool $collect_bubbleable_metadata
* Whether bubbleable metadata should be collected.
* @param int $invocations
* The expected amount of invocations for the ::bubble() method.
* @param array $options
* The URL options.
*
* @covers ::bubble
*
* @dataProvider providerUrlBubbleableMetadataBubbling
*/
public function testUrlBubbleableMetadataBubbling($collect_bubbleable_metadata, $invocations, array $options)
{
$self = $this;
$this->renderer->expects($this->exactly($invocations))->method('render')->willReturnCallback(function ($build) use($self) {
$self->assertTrue(!empty($build['#cache']));
});
$url = new Url('test_1', [], $options);
$url->setUrlGenerator($this->generator);
$url->toString($collect_bubbleable_metadata);
}
示例7: assertPageCacheContextsAndTags
/**
* Asserts page cache miss, then hit for the given URL; checks cache headers.
*
* @param \Drupal\Core\Url $url
* The URL to test.
* @param string[] $expected_contexts
* The expected cache contexts for the given URL.
* @param string[] $expected_tags
* The expected cache tags for the given URL.
*/
protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
{
$absolute_url = $url->setAbsolute()->toString();
sort($expected_contexts);
sort($expected_tags);
$get_cache_header_values = function ($header_name) {
$header_value = $this->drupalGetHeader($header_name);
if (empty($header_value)) {
return [];
} else {
return explode(' ', $header_value);
}
};
// Assert cache miss + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
$actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
$actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
$this->assertIdentical($actual_contexts, $expected_contexts);
if ($actual_contexts !== $expected_contexts) {
debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
}
$this->assertIdentical($actual_tags, $expected_tags);
if ($actual_tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
}
// Assert cache hit + expected cache contexts + tags.
$this->drupalGet($absolute_url);
$actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
$actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
$this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
$this->assertIdentical($actual_contexts, $expected_contexts);
if ($actual_contexts !== $expected_contexts) {
debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
}
$this->assertIdentical($actual_tags, $expected_tags);
if ($actual_tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
}
// Assert page cache item + expected cache tags.
$cid_parts = array($url->setAbsolute()->toString(), 'html');
$cid = implode(':', $cid_parts);
$cache_entry = \Drupal::cache('render')->get($cid);
sort($cache_entry->tags);
$this->assertEqual($cache_entry->tags, $expected_tags);
if ($cache_entry->tags !== $expected_tags) {
debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
}
}
示例8: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, $pid = NULL)
{
$form = parent::buildForm($form, $form_state, $pid);
$form['#title'] = $this->path['alias'];
$form['pid'] = array('#type' => 'hidden', '#value' => $this->path['pid']);
$url = new Url('path.delete', array('pid' => $this->path['pid']));
if ($this->getRequest()->query->has('destination')) {
$url->setOption('query', $this->getDestinationArray());
}
$form['actions']['delete'] = array('#type' => 'link', '#title' => $this->t('Delete'), '#url' => $url, '#attributes' => array('class' => array('button', 'button--danger')));
return $form;
}
示例9: save
/**
* {@inheritdoc}
*/
public function save(array $form, array &$form_state)
{
$brand = $this->entity;
$status = $brand->save();
if ($status) {
// Setting the success message.
drupal_set_message($this->t('Saved the brand: @name.', array('@name' => $brand->name)));
} else {
drupal_set_message($this->t('The @name brand was not saved.', array('@name' => $brand->name)));
}
$url = new Url('brandConfig.list');
$form_state['redirect'] = $url->toString();
}
示例10: save
/**
* {@inheritdoc}
*/
public function save(array $form, array &$form_state)
{
$sirenMapper = $this->entity;
$status = $sirenMapper->save();
if ($status) {
// Setting the success message.
drupal_set_message($this->t('Saved the siren mapper: @name.', array('@name' => $sirenMapper->name)));
} else {
drupal_set_message($this->t('The @name siren mapper was not saved.', array('@name' => $sirenMapper->name)));
}
$url = new Url('siren_mapper.list');
$form_state['redirect'] = $url->toString();
}
示例11: generate
/**
* {@inheritdoc}
*
* For anonymous users, the "active" class will be calculated on the server,
* because most sites serve each anonymous user the same cached page anyway.
* For authenticated users, the "active" class will be calculated on the
* client (through JavaScript), only data- attributes are added to links to
* prevent breaking the render cache. The JavaScript is added in
* system_page_attachments().
*
* @see system_page_attachments()
*/
public function generate($text, Url $url)
{
// Performance: avoid Url::toString() needing to retrieve the URL generator
// service from the container.
$url->setUrlGenerator($this->urlGenerator);
// Start building a structured representation of our link to be altered later.
$variables = array('text' => is_array($text) ? drupal_render($text) : $text, 'url' => $url, 'options' => $url->getOptions());
// Merge in default options.
$variables['options'] += array('attributes' => array(), 'query' => array(), 'language' => NULL, 'set_active_class' => FALSE, 'absolute' => FALSE);
// Add a hreflang attribute if we know the language of this link's url and
// hreflang has not already been set.
if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {
$variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();
}
// Set the "active" class if the 'set_active_class' option is not empty.
if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {
// Add a "data-drupal-link-query" attribute to let the
// drupal.active-link library know the query in a standardized manner.
if (!empty($variables['options']['query'])) {
$query = $variables['options']['query'];
ksort($query);
$variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);
}
// Add a "data-drupal-link-system-path" attribute to let the
// drupal.active-link library know the path in a standardized manner.
if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {
// @todo System path is deprecated - use the route name and parameters.
$system_path = $url->getInternalPath();
// Special case for the front page.
$variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;
}
}
// Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
// only when a quick strpos() gives suspicion tags are present.
if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
$variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
}
// Allow other modules to modify the structure of the link.
$this->moduleHandler->alter('link', $variables);
// Move attributes out of options. generateFromRoute(() doesn't need them.
$attributes = new Attribute($variables['options']['attributes']);
unset($variables['options']['attributes']);
$url->setOptions($variables['options']);
// The result of the url generator is a plain-text URL. Because we are using
// it here in an HTML argument context, we need to encode it properly.
$url = String::checkPlain($url->toString());
// Make sure the link text is sanitized.
$safe_text = SafeMarkup::escape($variables['text']);
return SafeMarkup::set('<a href="' . $url . '"' . $attributes . '>' . $safe_text . '</a>');
}
示例12: attachTo
public function attachTo(array &$build, $display_id, Url $feed_url, $title)
{
$url_options = array();
$input = $this->view->getExposedInput();
if ($input) {
$url_options['query'] = $input;
}
$url_options['absolute'] = TRUE;
$url = $feed_url->setOptions($url_options)->toString();
// Add the RSS icon to the view.
$this->view->feedIcons[] = ['#theme' => 'feed_icon', '#url' => $url, '#title' => $title];
// Attach a link to the RSS feed, which is an alternate representation.
$build['#attached']['html_head_link'][][] = array('rel' => 'alternate', 'type' => 'application/rss+xml', 'title' => $title, 'href' => $url);
}
示例13: getElement
/**
* {@inheritdoc}
*/
public function getElement(array &$form, FormStateInterface $form_state)
{
// Construct the group elements.
$group = $this->getGroup($form, $form_state);
$plugin_id = $this->getPluginId();
if (!isset($group->{$plugin_id})) {
// Set properties from the plugin definition.
foreach ($this->getElementProperties() as $name => $value) {
$group->{$plugin_id}->setProperty($name, $value);
}
// Set default value from the stored form state value or theme setting.
$default_value = $form_state->getValue($plugin_id, $this->theme->getSetting($plugin_id));
$group->{$plugin_id}->setProperty('default_value', $default_value);
// Append additional "see" link references to the description.
$description = (string) $group->{$plugin_id}->getProperty('description') ?: '';
/** @var \Drupal\Core\Render\Renderer $renderer */
$renderer = \Drupal::service('renderer');
$links = [];
foreach ($this->pluginDefinition['see'] as $url => $title) {
$link = ['#type' => 'link', '#url' => Url::fromUri($url), '#title' => $title, '#attributes' => ['target' => '_blank']];
$links[] = (string) $renderer->render($link);
}
if (!empty($links)) {
$description .= '<br>';
$description .= t('See also:');
$description .= ' ' . implode(', ', $links);
$group->{$plugin_id}->setProperty('description', $description);
}
}
return $group->{$plugin_id};
}
示例14: testMenuBlockLinksAccessCheck
/**
* Tests menu link for route with access check.
*
* @see \Drupal\menu_test\Access\AccessCheck::access()
*/
public function testMenuBlockLinksAccessCheck()
{
$this->drupalPlaceBlock('system_menu_block:account');
// Test that there's link rendered on the route.
$this->drupalGet('menu_test_access_check_session');
$this->assertLink('Test custom route access check');
// Page still accessible but thre should not be menu link.
$this->drupalGet('menu_test_access_check_session');
$this->assertResponse(200);
$this->assertNoLink('Test custom route access check');
// Test that page is no more accessible.
$this->drupalGet('menu_test_access_check_session');
$this->assertResponse(403);
// Check for access to a restricted local task from a default local task.
$this->drupalGet('foo/asdf');
$this->assertResponse(200);
$this->assertLinkByHref('foo/asdf');
$this->assertLinkByHref('foo/asdf/b');
$this->assertNoLinkByHref('foo/asdf/c');
// Attempt to access a restricted local task.
$this->drupalGet('foo/asdf/c');
$this->assertResponse(403);
$elements = $this->xpath('//ul[@class=:class]/li/a[@href=:href]', array(':class' => 'tabs primary', ':href' => Url::fromRoute('menu_test.router_test1', ['bar' => 'asdf'])->toString()));
$this->assertTrue(empty($elements), 'No tab linking to foo/asdf found');
$this->assertNoLinkByHref('foo/asdf/b');
$this->assertNoLinkByHref('foo/asdf/c');
}
示例15: assertBreadcrumbParts
/**
* Assert that a trail exists in the internal browser.
*
* @param array $trail
* An associative array whose keys are expected breadcrumb link paths and
* whose values are expected breadcrumb link texts (not sanitized).
*/
protected function assertBreadcrumbParts($trail)
{
// Compare paths with actual breadcrumb.
$parts = $this->getBreadcrumbParts();
$pass = TRUE;
// There may be more than one breadcrumb on the page. If $trail is empty
// this test would go into an infinite loop, so we need to check that too.
while ($trail && !empty($parts)) {
foreach ($trail as $path => $title) {
// If the path is empty, generate the path from the <front> route. If
// the path does not start with a leading slash, then run it through
// Url::fromUri('base:')->toString() to get the correct base
// prepended.
if ($path == '') {
$url = Url::fromRoute('<front>')->toString();
} elseif ($path[0] != '/') {
$url = Url::fromUri('base:' . $path)->toString();
} else {
$url = $path;
}
$part = array_shift($parts);
$pass = $pass && $part['href'] === $url && $part['text'] === SafeMarkup::checkPlain($title);
}
}
// No parts must be left, or an expected "Home" will always pass.
$pass = $pass && empty($parts);
$this->assertTrue($pass, format_string('Breadcrumb %parts found on @path.', array('%parts' => implode(' » ', $trail), '@path' => $this->getUrl())));
}