/**
  * Tests configuration renaming.
  */
 public function testConfigurationRename()
 {
     $content_type = entity_create('node_type', array('type' => Unicode::strtolower($this->randomName(16)), 'name' => $this->randomName()));
     $content_type->save();
     $staged_type = $content_type->type;
     $active = $this->container->get('config.storage');
     $staging = $this->container->get('config.storage.staging');
     $config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id();
     // Emulate a staging operation.
     $this->copyConfig($active, $staging);
     // Change the machine name of the content type.
     $content_type->type = Unicode::strtolower($this->randomName(8));
     $content_type->save();
     $active_type = $content_type->type;
     $renamed_config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id();
     $this->assertTrue($active->exists($renamed_config_name), 'The content type has the new name in the active store.');
     $this->assertFalse($active->exists($config_name), "The content type's old name does not exist active store.");
     $this->configImporter()->reset();
     $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('create')), 'There are no configuration items to create.');
     $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('delete')), 'There are no configuration items to delete.');
     $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('update')), 'There are no configuration items to update.');
     // We expect that changing the machine name of the content type will
     // rename five configuration entities: the node type, the body field
     // instance, two entity form displays, and the entity view display.
     // @see \Drupal\node\Entity\NodeType::postSave()
     $expected = array('node.type.' . $active_type . '::node.type.' . $staged_type, 'entity.form_display.node.' . $active_type . '.default::entity.form_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.default::entity.view_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.teaser::entity.view_display.node.' . $staged_type . '.teaser', 'field.instance.node.' . $active_type . '.body::field.instance.node.' . $staged_type . '.body');
     $renames = $this->configImporter()->getUnprocessedConfiguration('rename');
     $this->assertIdentical($expected, $renames);
     $this->drupalGet('admin/config/development/configuration');
     foreach ($expected as $rename) {
         $names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename);
         $this->assertText(String::format('!source_name to !target_name', array('!source_name' => $names['old_name'], '!target_name' => $names['new_name'])));
         // Test that the diff link is present for each renamed item.
         $href = \Drupal::urlGenerator()->getPathFromRoute('config.diff', array('source_name' => $names['old_name'], 'target_name' => $names['new_name']));
         $this->assertLinkByHref($href);
         $hrefs[$rename] = $href;
     }
     // Ensure that the diff works for each renamed item.
     foreach ($hrefs as $rename => $href) {
         $this->drupalGet($href);
         $names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename);
         $config_entity_type = \Drupal::service('config.manager')->getEntityTypeIdByName($names['old_name']);
         $entity_type = \Drupal::entityManager()->getDefinition($config_entity_type);
         $old_id = ConfigEntityStorage::getIDFromConfigName($names['old_name'], $entity_type->getConfigPrefix());
         $new_id = ConfigEntityStorage::getIDFromConfigName($names['new_name'], $entity_type->getConfigPrefix());
         // Because table columns can be on multiple lines, need to assert a regex
         // pattern rather than normal text.
         $id_key = $entity_type->getKey('id');
         $text = "{$id_key}: {$old_id}";
         $this->assertTextPattern('/\\-\\s+' . preg_quote($text, '/') . '/', "'-{$text}' found.");
         $text = "{$id_key}: {$new_id}";
         $this->assertTextPattern('/\\+\\s+' . preg_quote($text, '/') . '/', "'+{$text}' found.");
     }
     // Run the import.
     $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all'));
     $this->assertText(t('There are no configuration changes.'));
     $this->assertFalse(entity_load('node_type', $active_type), 'The content no longer exists with the old name.');
     $content_type = entity_load('node_type', $staged_type);
     $this->assertIdentical($staged_type, $content_type->type);
 }
Example #2
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installSchema('system', ['router']);
     \Drupal::service('router.builder')->rebuild();
     $this->urlGenerator = \Drupal::urlGenerator();
 }
Example #3
0
 /**
  * Tests support for different cache items with different Accept headers.
  */
 function testAcceptHeaderRequests()
 {
     $config = $this->config('system.performance');
     $config->set('cache.page.use_internal', 1);
     $config->set('cache.page.max_age', 300);
     $config->save();
     $url_generator = \Drupal::urlGenerator();
     $url_generator->setContext(new RequestContext());
     $accept_header_cache_uri = $url_generator->getPathFromRoute('system_test.page_cache_accept_header');
     $json_accept_header = array('Accept: application/json');
     $this->drupalGet($accept_header_cache_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'HTML page was not yet cached.');
     $this->drupalGet($accept_header_cache_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'HTML page was cached.');
     $this->assertRaw('<p>oh hai this is html.</p>', 'The correct HTML response was returned.');
     $this->drupalGet($accept_header_cache_uri, array(), $json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Json response was not yet cached.');
     $this->drupalGet($accept_header_cache_uri, array(), $json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Json response was cached.');
     $this->assertRaw('{"content":"oh hai this is json"}', 'The correct Json response was returned.');
     // Enable REST support for nodes and hal+json.
     \Drupal::service('module_installer')->install(['node', 'rest', 'hal']);
     $this->drupalCreateContentType(['type' => 'article']);
     $node = $this->drupalCreateNode(['type' => 'article']);
     $node_uri = 'node/' . $node->id();
     $hal_json_accept_header = ['Accept: application/hal+json'];
     /** @var \Drupal\user\RoleInterface $role */
     $role = Role::load('anonymous');
     $role->grantPermission('restful get entity:node');
     $role->save();
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
     // Now request a HAL page, we expect that the first request is a cache miss
     // and it serves HTML.
     $this->drupalGet($node_uri, [], $hal_json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     $this->drupalGet($node_uri, [], $hal_json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     // Clear the page cache. After that request a HAL request, followed by an
     // ordinary HTML one.
     \Drupal::cache('render')->deleteAll();
     $this->drupalGet($node_uri, [], $hal_json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     $this->drupalGet($node_uri, [], $hal_json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'application/hal+json');
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
     $this->drupalGet($node_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertEqual($this->drupalGetHeader('Content-Type'), 'text/html; charset=UTF-8');
 }
Example #4
0
 /**
  * Tests rendering form elements without passing through
  * \Drupal::formBuilder()->doBuildForm().
  */
 function testDrupalRenderFormElements()
 {
     // Define a series of form elements.
     $element = array('#type' => 'button', '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'submit'));
     $element = array('#type' => 'textfield', '#title' => $this->randomMachineName(), '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'text'));
     $element = array('#type' => 'password', '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'password'));
     $element = array('#type' => 'textarea', '#title' => $this->randomMachineName(), '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//textarea');
     $element = array('#type' => 'radio', '#title' => $this->randomMachineName(), '#value' => FALSE);
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'radio'));
     $element = array('#type' => 'checkbox', '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'checkbox'));
     $element = array('#type' => 'select', '#title' => $this->randomMachineName(), '#options' => array(0 => $this->randomMachineName(), 1 => $this->randomMachineName()));
     $this->assertRenderedElement($element, '//select');
     $element = array('#type' => 'file', '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'file'));
     $element = array('#type' => 'item', '#title' => $this->randomMachineName(), '#markup' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//div[contains(@class, :class) and contains(., :markup)]/label[contains(., :label)]', array(':class' => 'form-type-item', ':markup' => $element['#markup'], ':label' => $element['#title']));
     $element = array('#type' => 'hidden', '#title' => $this->randomMachineName(), '#value' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//input[@type=:type]', array(':type' => 'hidden'));
     $element = array('#type' => 'link', '#title' => $this->randomMachineName(), '#url' => Url::fromRoute('common_test.destination'), '#options' => array('absolute' => TRUE));
     $this->assertRenderedElement($element, '//a[@href=:href and contains(., :title)]', array(':href' => \Drupal::urlGenerator()->generateFromPath('common-test/destination', ['absolute' => TRUE]), ':title' => $element['#title']));
     $element = array('#type' => 'details', '#open' => TRUE, '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//details/summary[contains(., :title)]', array(':title' => $element['#title']));
     $element = array('#type' => 'details', '#open' => TRUE, '#title' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//details');
     $element['item'] = array('#type' => 'item', '#title' => $this->randomMachineName(), '#markup' => $this->randomMachineName());
     $this->assertRenderedElement($element, '//details/div/div[contains(@class, :class) and contains(., :markup)]', array(':class' => 'form-type-item', ':markup' => $element['item']['#markup']));
 }
 /**
  * Tests system #type 'more_link'.
  */
 function testMoreLink()
 {
     $elements = array(array('name' => "#type 'more_link' anchor tag generation without extra classes", 'value' => array('#type' => 'more_link', '#url' => Url::fromUri('https://www.drupal.org')), 'expected' => '//div[@class="more-link"]/a[@href="https://www.drupal.org" and text()="More"]'), array('name' => "#type 'more_link' anchor tag generation with different link text", 'value' => array('#type' => 'more_link', '#url' => Url::fromUri('https://www.drupal.org'), '#title' => 'More Titles'), 'expected' => '//div[@class="more-link"]/a[@href="https://www.drupal.org" and text()="More Titles"]'), array('name' => "#type 'more_link' anchor tag generation with attributes on wrapper", 'value' => array('#type' => 'more_link', '#url' => Url::fromUri('https://www.drupal.org'), '#theme_wrappers' => array('container' => array('#attributes' => array('title' => 'description', 'class' => array('more-link', 'drupal', 'test'))))), 'expected' => '//div[@title="description" and contains(@class, "more-link") and contains(@class, "drupal") and contains(@class, "test")]/a[@href="https://www.drupal.org" and text()="More"]'), array('name' => "#type 'more_link' anchor tag with a relative path", 'value' => array('#type' => 'more_link', '#url' => Url::fromRoute('router_test.1')), 'expected' => '//div[@class="more-link"]/a[@href="' . Url::fromRoute('router_test.1')->toString() . '" and text()="More"]'), array('name' => "#type 'more_link' anchor tag with a route", 'value' => array('#type' => 'more_link', '#url' => Url::fromRoute('router_test.1')), 'expected' => '//div[@class="more-link"]/a[@href="' . \Drupal::urlGenerator()->generate('router_test.1') . '" and text()="More"]'), array('name' => "#type 'more_link' anchor tag with an absolute path", 'value' => array('#type' => 'more_link', '#url' => Url::fromRoute('system.admin_content'), '#options' => array('absolute' => TRUE)), 'expected' => '//div[@class="more-link"]/a[@href="' . Url::fromRoute('system.admin_content')->setAbsolute()->toString() . '" and text()="More"]'), array('name' => "#type 'more_link' anchor tag to the front page", 'value' => array('#type' => 'more_link', '#url' => Url::fromRoute('<front>')), 'expected' => '//div[@class="more-link"]/a[@href="' . Url::fromRoute('<front>')->toString() . '" and text()="More"]'));
     foreach ($elements as $element) {
         $xml = new \SimpleXMLElement(\Drupal::service('renderer')->renderRoot($element['value']));
         $result = $xml->xpath($element['expected']);
         $this->assertTrue($result, '"' . $element['name'] . '" input rendered correctly by drupal_render().');
     }
 }
Example #6
0
 /**
  * Fetchs the menu item from the database and compares it to expected item.
  *
  * @param int $mlid
  *   Menu item id.
  * @param array $item
  *   Array containing properties to verify.
  */
 function assertMenuLink($mlid, array $expected_item)
 {
     // Retrieve menu link.
     $item = entity_load('menu_link', $mlid);
     $options = $item->options;
     if (!empty($options['query'])) {
         $item['link_path'] .= '?' . \Drupal::urlGenerator()->httpBuildQuery($options['query']);
     }
     if (!empty($options['fragment'])) {
         $item['link_path'] .= '#' . $options['fragment'];
     }
     foreach ($expected_item as $key => $value) {
         $this->assertEqual($item[$key], $value);
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getOptions(Request $request)
 {
     $options = parent::getOptions($request);
     // Append the current path as destination to the query string.
     if ($request->attributes->has(RouteObjectInterface::ROUTE_NAME)) {
         $route_name = $request->attributes->get(RouteObjectInterface::ROUTE_NAME);
         $raw_variables = array();
         if ($request->attributes->has('_raw_variables')) {
             $raw_variables = $request->attributes->get('_raw_variables')->all();
         }
         // @todo Use RouteMatch instead of Request.
         //   https://www.drupal.org/node/2294157
         $options['query']['destination'] = \Drupal::urlGenerator()->generateFromRoute($route_name, $raw_variables);
     }
     return $options;
 }
 /**
  * {@inheritdoc}
  */
 public function getValue()
 {
     if (!isset($this->value)) {
         if (!isset($this->parent)) {
             throw new \InvalidArgumentException('Computed properties require context for computation.');
         }
         $entity = $this->parent->getEntity();
         if ($route_name = $entity->getRouteName()) {
             $path = \Drupal::urlGenerator()->getPathFromRoute($route_name, $entity->getRouteParams());
             $this->value = trim($path, '/');
         } else {
             $this->value = NULL;
         }
     }
     return $this->value;
 }
 protected function doTestBasicTranslation()
 {
     parent::doTestBasicTranslation();
     $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
     foreach ($this->langcodes as $langcode) {
         if ($entity->hasTranslation($langcode)) {
             $language = new Language(array('id' => $langcode));
             // Request the front page in this language and assert that the right
             // translation shows up in the shortcut list with the right path.
             $this->drupalGet('<front>', array('language' => $language));
             $expected_path = \Drupal::urlGenerator()->generateFromRoute('user.page', array(), array('language' => $language));
             $label = $entity->getTranslation($langcode)->label();
             $elements = $this->xpath('//nav[contains(@class, "toolbar-lining")]/ul[@class="toolbar-menu"]/li/a[contains(@href, :href) and normalize-space(text())=:label]', array(':href' => $expected_path, ':label' => $label));
             $this->assertTrue(!empty($elements), format_string('Translated @language shortcut link @label found.', array('@label' => $label, '@language' => $language->getName())));
         }
     }
 }
 /**
  * Tests support for different cache items with different Accept headers.
  */
 function testAcceptHeaderRequests()
 {
     $config = \Drupal::config('system.performance');
     $config->set('cache.page.use_internal', 1);
     $config->set('cache.page.max_age', 300);
     $config->save();
     $url_generator = \Drupal::urlGenerator();
     $url_generator->setContext(new RequestContext());
     $accept_header_cache_uri = $url_generator->getPathFromRoute('system_test.page_cache_accept_header');
     $json_accept_header = array('Accept: application/json');
     $this->drupalGet($accept_header_cache_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'HTML page was not yet cached.');
     $this->drupalGet($accept_header_cache_uri);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'HTML page was cached.');
     $this->assertRaw('<p>oh hai this is html.</p>', 'The correct HTML response was returned.');
     $this->drupalGet($accept_header_cache_uri, array(), $json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Json response was not yet cached.');
     $this->drupalGet($accept_header_cache_uri, array(), $json_accept_header);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Json response was cached.');
     $this->assertRaw('{"content":"oh hai this is json"}', 'The correct Json response was returned.');
 }
    /**
     * @param null $menu_name
     * @return ResourceResponse
     */
    public function get($menu_name = null) {
        $menu_tree = \Drupal::menuTree( );
        $generator = \Drupal::urlGenerator();

        // Load the tree based on this set of parameters.
        $tree = $menu_tree->load($menu_name, new \Drupal\Core\Menu\MenuTreeParameters());

        // Transform the tree using the manipulators you want.
        $manipulators = array(
            // Only show links that are accessible for the current user.
            array('callable' => 'menu.default_tree_manipulators:checkAccess'),
            // Use the default sorting of menu links.
            array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
        );
        $tree = $menu_tree->transform($tree, $manipulators);

        foreach ($tree as $element) {
            /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
            $link = $element->link;
            $link_param = $link->pluginDefinition['route_parameters'];
          // echo "<pre>" . print_r($link->pluginDefinition, true) . "</pre>";
            $path = $generator->getPathFromRoute($link->getRouteName(), $link_param);

            $menu[$link->getRouteName()]['title'] = $link->getTitle();
            $menu[$link->getRouteName()]['url'] = $path;

            if ($element->subtree) {
                $subtree = $menu_tree->build($element->subtree);

                foreach ($subtree['#items'] as $key => $value) {
                    // print_r($value['url']->getRouteParameters());

                    //$path = $generator->getPathFromRoute($key, $value['url']->getRouteParameters());
                    $menu[$key]['title'] = $value['title'];
                    $menu[$key]['url'] = $path;
                }
            }
        }
        return new ResourceResponse($menu);
    }
 /**
  * {@inheritdoc}
  *
  * We override ::render() so that we can add our own content above the table.
  * parent::render() is where EntityListBuilder creates the table using our
  * buildHeader() and buildRow() implementations.
  */
 public function render()
 {
     $build['description'] = array('#markup' => $this->t('customslider implements a Custom Slider model. These Custom Slider are fieldable entities. You can manage the fields on the <a href="@adminlink">Custom Slider admin page</a>.', array('@adminlink' => \Drupal::urlGenerator()->generateFromRoute('customslider.customslider_settings'))));
     $build['table'] = parent::render();
     return $build;
 }
Example #13
0
File: Url.php Project: brstde/gap1
 /**
  * Gets the URL generator.
  *
  * @return \Drupal\Core\Routing\UrlGeneratorInterface
  *   The URL generator.
  */
 protected function urlGenerator()
 {
     if (!$this->urlGenerator) {
         $this->urlGenerator = \Drupal::urlGenerator();
     }
     return $this->urlGenerator;
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     \Drupal::service('router.builder')->rebuild();
     $this->urlGenerator = \Drupal::urlGenerator();
 }
Example #15
0
 /**
  * Tests links.html.twig.
  */
 function testLinks()
 {
     // Turn off the query for the _l() function to compare the active
     // link correctly.
     $original_query = \Drupal::request()->query->all();
     \Drupal::request()->query->replace(array());
     // Verify that empty variables produce no output.
     $variables = array();
     $expected = '';
     $this->assertThemeOutput('links', $variables, $expected, 'Empty %callback generates no output.');
     $variables = array();
     $variables['heading'] = 'Some title';
     $expected = '';
     $this->assertThemeOutput('links', $variables, $expected, 'Empty %callback with heading generates no output.');
     // Verify that a list of links is properly rendered.
     $variables = array();
     $variables['attributes'] = array('id' => 'somelinks');
     $variables['links'] = array('a link' => array('title' => 'A <link>', 'url' => Url::fromUri('base://a/link')), 'plain text' => array('title' => 'Plain "text"'), 'front page' => array('title' => 'Front page', 'url' => Url::fromRoute('<front>')), 'router-test' => array('title' => 'Test route', 'url' => Url::fromRoute('router_test.1')), 'query-test' => array('title' => 'Query test route', 'url' => Url::fromRoute('router_test.1'), 'query' => array('key' => 'value')));
     $expected_links = '';
     $expected_links .= '<ul id="somelinks">';
     $expected_links .= '<li class="a-link"><a href="' . Url::fromUri('base://a/link')->toString() . '">' . String::checkPlain('A <link>') . '</a></li>';
     $expected_links .= '<li class="plain-text">' . String::checkPlain('Plain "text"') . '</li>';
     $expected_links .= '<li class="front-page"><a href="' . _url('<front>') . '">' . String::checkPlain('Front page') . '</a></li>';
     $expected_links .= '<li class="router-test"><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '">' . String::checkPlain('Test route') . '</a></li>';
     $query = array('key' => 'value');
     $expected_links .= '<li class="query-test"><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '">' . String::checkPlain('Query test route') . '</a></li>';
     $expected_links .= '</ul>';
     // Verify that passing a string as heading works.
     $variables['heading'] = 'Links heading';
     $expected_heading = '<h2>Links heading</h2>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Restore the original request's query.
     \Drupal::request()->query->replace($original_query);
     // Verify that passing an array as heading works (core support).
     $variables['heading'] = array('text' => 'Links heading', 'level' => 'h3', 'attributes' => array('class' => array('heading')));
     $expected_heading = '<h3 class="heading">Links heading</h3>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Verify that passing attributes for the heading works.
     $variables['heading'] = array('text' => 'Links heading', 'level' => 'h3', 'attributes' => array('id' => 'heading'));
     $expected_heading = '<h3 id="heading">Links heading</h3>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Verify that passing attributes for the links work.
     $variables['links']['plain text']['attributes'] = array('class' => array('a/class'));
     $expected_links = '';
     $expected_links .= '<ul id="somelinks">';
     $expected_links .= '<li class="a-link"><a href="' . Url::fromUri('base://a/link')->toString() . '">' . String::checkPlain('A <link>') . '</a></li>';
     $expected_links .= '<li class="plain-text"><span class="a/class">' . String::checkPlain('Plain "text"') . '</span></li>';
     $expected_links .= '<li class="front-page"><a href="' . _url('<front>') . '">' . String::checkPlain('Front page') . '</a></li>';
     $expected_links .= '<li class="router-test"><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '">' . String::checkPlain('Test route') . '</a></li>';
     $query = array('key' => 'value');
     $expected_links .= '<li class="query-test"><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '">' . String::checkPlain('Query test route') . '</a></li>';
     $expected_links .= '</ul>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Verify the data- attributes for setting the "active" class on links.
     \Drupal::currentUser()->setAccount(new UserSession(array('uid' => 1)));
     $variables['set_active_class'] = TRUE;
     $expected_links = '';
     $expected_links .= '<ul id="somelinks">';
     $expected_links .= '<li class="a-link"><a href="' . Url::fromUri('base://a/link')->toString() . '">' . String::checkPlain('A <link>') . '</a></li>';
     $expected_links .= '<li class="plain-text"><span class="a/class">' . String::checkPlain('Plain "text"') . '</span></li>';
     $expected_links .= '<li data-drupal-link-system-path="&lt;front&gt;" class="front-page"><a href="' . _url('<front>') . '" data-drupal-link-system-path="&lt;front&gt;">' . String::checkPlain('Front page') . '</a></li>';
     $expected_links .= '<li data-drupal-link-system-path="router_test/test1" class="router-test"><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '" data-drupal-link-system-path="router_test/test1">' . String::checkPlain('Test route') . '</a></li>';
     $query = array('key' => 'value');
     $encoded_query = String::checkPlain(Json::encode($query));
     $expected_links .= '<li data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1" class="query-test"><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '" data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1">' . String::checkPlain('Query test route') . '</a></li>';
     $expected_links .= '</ul>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
 }
Example #16
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     parent::submitForm($form, $form_state);
     /** @var \Drupal\facets\FacetInterface $facet */
     $facet = $this->getEntity();
     $is_new = $facet->isNew();
     if ($is_new) {
         // On facet creation, enable all locked processors by default, using their
         // default settings.
         $stages = $this->getProcessorPluginManager()->getProcessingStages();
         $processors_definitions = $this->getProcessorPluginManager()->getDefinitions();
         foreach ($processors_definitions as $processor_id => $processor) {
             $is_locked = isset($processor['locked']) && $processor['locked'] == TRUE;
             $is_default_enabled = isset($processor['default_enabled']) && $processor['default_enabled'] == TRUE;
             if ($is_locked || $is_default_enabled) {
                 $weights = [];
                 foreach ($stages as $stage_id => $stage) {
                     if (isset($processor['stages'][$stage_id])) {
                         $weights[$stage_id] = $processor['stages'][$stage_id];
                     }
                 }
                 $facet->addProcessor(['processor_id' => $processor_id, 'weights' => $weights, 'settings' => []]);
             }
         }
         // Set a default widget for new facets.
         $facet->setWidget('links');
         $facet->setUrlAlias($form_state->getValue('id'));
         $facet->setWeight(0);
         // Set default empty behaviour.
         $facet->setEmptyBehavior(['behavior' => 'none']);
         $facet->setOnlyVisibleWhenFacetSourceIsVisible(TRUE);
     }
     $facet_source_id = $form_state->getValue('facet_source_id');
     if (!is_null($facet_source_id) && $facet_source_id !== '') {
         /** @var \Drupal\facets\FacetSource\FacetSourcePluginInterface $facet_source */
         $facet_source = $this->getFacetSourcePluginManager()->createInstance($facet_source_id, ['facet' => $this->getEntity()]);
         $facet_source->submitConfigurationForm($form, $form_state);
     }
     $facet->save();
     // Ensure that the caching of the view display is disabled, so the search
     // correctly returns the facets. Only apply this when the facet source is
     // actually a view by exploding on :.
     list($type, ) = explode(':', $facet_source_id);
     if ($type === 'search_api_views') {
         list(, $view_id, $display) = explode(':', $facet_source_id);
     }
     if (isset($view_id)) {
         $view = Views::getView($view_id);
         $view->setDisplay($display);
         $view->display_handler->overrideOption('cache', ['type' => 'none']);
         $view->save();
         $display_plugin = $view->getDisplay()->getPluginId();
     }
     if ($is_new) {
         if (\Drupal::moduleHandler()->moduleExists('block')) {
             $message = $this->t('Facet %name has been created. Go to the <a href=":block_overview">Block overview page</a> to place the new block in the desired region.', ['%name' => $facet->getName(), ':block_overview' => \Drupal::urlGenerator()->generateFromRoute('block.admin_display')]);
             drupal_set_message($message);
             $form_state->setRedirect('entity.facets_facet.edit_form', ['facets_facet' => $facet->id()]);
         }
         if (isset($view_id) && $display_plugin === 'block') {
             $facet->setOnlyVisibleWhenFacetSourceIsVisible(FALSE);
         }
     } else {
         drupal_set_message(t('Facet %name has been updated.', ['%name' => $facet->getName()]));
     }
     // Clear Drupal cache for blocks to reflect recent changes.
     \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
     return $facet;
 }
Example #17
0
 /**
  * Tests rewriting the output to a link.
  */
 public function testAlterUrl()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = \Drupal::service('renderer');
     $view = Views::getView('test_view');
     $view->setDisplay();
     $view->initHandlers();
     $this->executeView($view);
     $row = $view->result[0];
     $id_field = $view->field['id'];
     // Setup the general settings required to build a link.
     $id_field->options['alter']['make_link'] = TRUE;
     $id_field->options['alter']['path'] = $path = $this->randomMachineName();
     // Tests that the suffix/prefix appears on the output.
     $id_field->options['alter']['prefix'] = $prefix = $this->randomMachineName();
     $id_field->options['alter']['suffix'] = $suffix = $this->randomMachineName();
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, $prefix);
     $this->assertSubString($output, $suffix);
     unset($id_field->options['alter']['prefix']);
     unset($id_field->options['alter']['suffix']);
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, $path, 'Make sure that the path is part of the output');
     // Some generic test code adapted from the UrlTest class, which tests
     // mostly the different options for the path.
     foreach (array(FALSE, TRUE) as $absolute) {
         $alter =& $id_field->options['alter'];
         $alter['path'] = 'node/123';
         $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['absolute' => $absolute]);
         $alter['absolute'] = $absolute;
         $result = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
             return $id_field->theme($row);
         });
         $this->assertSubString($result, $expected_result);
         $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['fragment' => 'foo', 'absolute' => $absolute]);
         $alter['path'] = 'node/123#foo';
         $result = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
             return $id_field->theme($row);
         });
         $this->assertSubString($result, $expected_result);
         $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'absolute' => $absolute]);
         $alter['path'] = 'node/123?foo';
         $result = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
             return $id_field->theme($row);
         });
         $this->assertSubString($result, $expected_result);
         $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => 'bar', 'bar' => 'baz'], 'absolute' => $absolute]);
         $alter['path'] = 'node/123?foo=bar&bar=baz';
         $result = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
             return $id_field->theme($row);
         });
         $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));
         // @todo The route-based URL generator strips out NULL attributes.
         // $expected_result = \Drupal::url('entity.node.canonical', ['node' => '123'], ['query' => ['foo' => NULL], 'fragment' => 'bar', 'absolute' => $absolute]);
         $expected_result = \Drupal::urlGenerator()->generateFromPath('node/123', array('query' => array('foo' => NULL), 'fragment' => 'bar', 'absolute' => $absolute));
         $alter['path'] = 'node/123?foo#bar';
         $result = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
             return $id_field->theme($row);
         });
         $this->assertSubString(Html::decodeEntities($result), Html::decodeEntities($expected_result));
         $expected_result = \Drupal::url('<front>', [], ['absolute' => $absolute]);
         $alter['path'] = '<front>';
         $result = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
             return $id_field->theme($row);
         });
         $this->assertSubString($result, $expected_result);
     }
     // Tests the replace spaces with dashes feature.
     $id_field->options['alter']['replace_spaces'] = TRUE;
     $id_field->options['alter']['path'] = $path = $this->randomMachineName() . ' ' . $this->randomMachineName();
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, str_replace(' ', '-', $path));
     $id_field->options['alter']['replace_spaces'] = FALSE;
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     // The url has a space in it, so to check we have to decode the url output.
     $this->assertSubString(urldecode($output), $path);
     // Tests the external flag.
     // Switch on the external flag should output an external url as well.
     $id_field->options['alter']['external'] = TRUE;
     $id_field->options['alter']['path'] = $path = 'www.drupal.org';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, 'http://www.drupal.org');
     // Setup a not external url, which shouldn't lead to an external url.
     $id_field->options['alter']['external'] = FALSE;
     $id_field->options['alter']['path'] = $path = 'www.drupal.org';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertNotSubString($output, 'http://www.drupal.org');
     // Tests the transforming of the case setting.
     $id_field->options['alter']['path'] = $path = $this->randomMachineName();
     $id_field->options['alter']['path_case'] = 'none';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, $path);
     // Switch to uppercase and lowercase.
     $id_field->options['alter']['path_case'] = 'upper';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, strtoupper($path));
     $id_field->options['alter']['path_case'] = 'lower';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, strtolower($path));
     // Switch to ucfirst and ucwords.
     $id_field->options['alter']['path_case'] = 'ucfirst';
     $id_field->options['alter']['path'] = 'drupal has a great community';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, UrlHelper::encodePath('Drupal has a great community'));
     $id_field->options['alter']['path_case'] = 'ucwords';
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $this->assertSubString($output, UrlHelper::encodePath('Drupal Has A Great Community'));
     unset($id_field->options['alter']['path_case']);
     // Tests the linkclass setting and see whether it actually exists in the
     // output.
     $id_field->options['alter']['link_class'] = $class = $this->randomMachineName();
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $elements = $this->xpathContent($output, '//a[contains(@class, :class)]', array(':class' => $class));
     $this->assertTrue($elements);
     // @fixme link_class, alt, rel cannot be unset, which should be fixed.
     $id_field->options['alter']['link_class'] = '';
     // Tests the alt setting.
     $id_field->options['alter']['alt'] = $rel = $this->randomMachineName();
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $elements = $this->xpathContent($output, '//a[contains(@title, :alt)]', array(':alt' => $rel));
     $this->assertTrue($elements);
     $id_field->options['alter']['alt'] = '';
     // Tests the rel setting.
     $id_field->options['alter']['rel'] = $rel = $this->randomMachineName();
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $elements = $this->xpathContent($output, '//a[contains(@rel, :rel)]', array(':rel' => $rel));
     $this->assertTrue($elements);
     $id_field->options['alter']['rel'] = '';
     // Tests the target setting.
     $id_field->options['alter']['target'] = $target = $this->randomMachineName();
     $output = $renderer->executeInRenderContext(new RenderContext(), function () use($id_field, $row) {
         return $id_field->theme($row);
     });
     $elements = $this->xpathContent($output, '//a[contains(@target, :target)]', array(':target' => $target));
     $this->assertTrue($elements);
     unset($id_field->options['alter']['target']);
 }
Example #18
0
 /**
  * Tests page title is set correctly on user account tabs.
  */
 function testAccountPageTitles()
 {
     // Default page titles are suffixed with the site name - Drupal.
     $title_suffix = ' | Drupal';
     $this->drupalGet('user');
     $this->assertTitle('Log in' . $title_suffix, "Page title of /user is 'Log in'");
     $this->drupalGet('user/login');
     $this->assertTitle('Log in' . $title_suffix, "Page title of /user/login is 'Log in'");
     $this->drupalGet('user/register');
     $this->assertTitle('Create new account' . $title_suffix, "Page title of /user/register is 'Create new account' for anonymous users.");
     $this->drupalGet('user/password');
     $this->assertTitle('Reset your password' . $title_suffix, "Page title of /user/register is 'Reset your password' for anonymous users.");
     // Check the page title for registered users is "My Account" in menus.
     $this->drupalLogin($this->drupalCreateUser());
     // After login, the client is redirected to /user.
     $this->assertLink(t('My account'), 0, "Page title of /user is 'My Account' in menus for registered users");
     $this->assertLinkByHref(\Drupal::urlGenerator()->generate('user.page'), 0);
 }
Example #19
0
 /**
  * Tests links.html.twig using links with indexed keys.
  */
 function testIndexedKeyedLinks()
 {
     // Turn off the query for the
     // \Drupal\Core\Utility\LinkGeneratorInterface::generate() method to compare
     // the active link correctly.
     $original_query = \Drupal::request()->query->all();
     \Drupal::request()->query->replace([]);
     // Verify that empty variables produce no output.
     $variables = [];
     $expected = '';
     $this->assertThemeOutput('links', $variables, $expected, 'Empty %callback generates no output.');
     $variables = [];
     $variables['heading'] = 'Some title';
     $expected = '';
     $this->assertThemeOutput('links', $variables, $expected, 'Empty %callback with heading generates no output.');
     // Verify that a list of links is properly rendered.
     $variables = [];
     $variables['attributes'] = ['id' => 'somelinks'];
     $variables['links'] = array(array('title' => 'A <link>', 'url' => Url::fromUri('base:a/link')), array('title' => 'Plain "text"'), array('title' => SafeMarkup::format('<span class="unescaped">@text</span>', array('@text' => 'potentially unsafe text that <should> be escaped'))), array('title' => 'Front page', 'url' => Url::fromRoute('<front>')), array('title' => 'Test route', 'url' => Url::fromRoute('router_test.1')), array('title' => 'Query test route', 'url' => Url::fromRoute('router_test.1'), 'query' => array('key' => 'value')));
     $expected_links = '';
     $expected_links .= '<ul id="somelinks">';
     $expected_links .= '<li><a href="' . Url::fromUri('base:a/link')->toString() . '">' . Html::escape('A <link>') . '</a></li>';
     $expected_links .= '<li>' . Html::escape('Plain "text"') . '</li>';
     $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
     $expected_links .= '<li><a href="' . Url::fromRoute('<front>')->toString() . '">' . Html::escape('Front page') . '</a></li>';
     $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '">' . Html::escape('Test route') . '</a></li>';
     $query = ['key' => 'value'];
     $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '">' . Html::escape('Query test route') . '</a></li>';
     $expected_links .= '</ul>';
     // Verify that passing a string as heading works.
     $variables['heading'] = 'Links heading';
     $expected_heading = '<h2>Links heading</h2>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Restore the original request's query.
     \Drupal::request()->query->replace($original_query);
     // Verify that passing an array as heading works (core support).
     $variables['heading'] = ['text' => 'Links heading', 'level' => 'h3', 'attributes' => ['class' => ['heading']]];
     $expected_heading = '<h3 class="heading">Links heading</h3>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Verify that passing attributes for the heading works.
     $variables['heading'] = ['text' => 'Links heading', 'level' => 'h3', 'attributes' => ['id' => 'heading']];
     $expected_heading = '<h3 id="heading">Links heading</h3>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Verify that passing attributes for the links work.
     $variables['links'][1]['attributes'] = ['class' => ['a/class']];
     $expected_links = '';
     $expected_links .= '<ul id="somelinks">';
     $expected_links .= '<li><a href="' . Url::fromUri('base:a/link')->toString() . '">' . Html::escape('A <link>') . '</a></li>';
     $expected_links .= '<li><span class="a/class">' . Html::escape('Plain "text"') . '</span></li>';
     $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
     $expected_links .= '<li><a href="' . Url::fromRoute('<front>')->toString() . '">' . Html::escape('Front page') . '</a></li>';
     $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '">' . Html::escape('Test route') . '</a></li>';
     $query = ['key' => 'value'];
     $expected_links .= '<li><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '">' . Html::escape('Query test route') . '</a></li>';
     $expected_links .= '</ul>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
     // Verify the data- attributes for setting the "active" class on links.
     \Drupal::currentUser()->setAccount(new UserSession(array('uid' => 1)));
     $variables['set_active_class'] = TRUE;
     $expected_links = '';
     $expected_links .= '<ul id="somelinks">';
     $expected_links .= '<li><a href="' . Url::fromUri('base:a/link')->toString() . '">' . Html::escape('A <link>') . '</a></li>';
     $expected_links .= '<li><span class="a/class">' . Html::escape('Plain "text"') . '</span></li>';
     $expected_links .= '<li><span class="unescaped">' . Html::escape('potentially unsafe text that <should> be escaped') . '</span></li>';
     $expected_links .= '<li data-drupal-link-system-path="&lt;front&gt;"><a href="' . Url::fromRoute('<front>')->toString() . '" data-drupal-link-system-path="&lt;front&gt;">' . Html::escape('Front page') . '</a></li>';
     $expected_links .= '<li data-drupal-link-system-path="router_test/test1"><a href="' . \Drupal::urlGenerator()->generate('router_test.1') . '" data-drupal-link-system-path="router_test/test1">' . Html::escape('Test route') . '</a></li>';
     $query = ['key' => 'value'];
     $encoded_query = Html::escape(Json::encode($query));
     $expected_links .= '<li data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1"><a href="' . \Drupal::urlGenerator()->generate('router_test.1', $query) . '" data-drupal-link-query="' . $encoded_query . '" data-drupal-link-system-path="router_test/test1">' . Html::escape('Query test route') . '</a></li>';
     $expected_links .= '</ul>';
     $expected = $expected_heading . $expected_links;
     $this->assertThemeOutput('links', $variables, $expected);
 }
 /**
  * Tests the toArray() method.
  *
  * @param \Drupal\Core\Url[] $urls
  *   An array of Url objects.
  *
  * @depends testUrlFromRequest
  *
  * @covers ::toArray
  */
 public function testToArray($urls)
 {
     foreach ($urls as $index => $url) {
         $expected = Url::fromRoute($this->map[$index][0], $this->map[$index][1], $this->map[$index][2]);
         $expected->setUrlGenerator(\Drupal::urlGenerator());
         $this->assertEquals($expected, $url);
     }
 }
 /**
  * #post_render_cache callback; attaches "X new comments" link metadata.
  *
  * @param array $element
  *   A render array with the following keys:
  *   - #markup
  *   - #attached
  * @param array $context
  *   An array with the following keys:
  *   - entity_type: an entity type
  *   - entity_id: an entity ID
  *   - field_name: a comment field name
  *
  * @return array $element
  *   The updated $element.
  */
 public static function attachNewCommentsLinkMetadata(array $element, array $context)
 {
     // Build "X new comments" link metadata.
     $new = \Drupal::service('comment.manager')->getCountNewComments(entity_load($context['entity_type'], $context['entity_id']));
     // Early-return if there are zero new comments for the current user.
     if ($new === 0) {
         return $element;
     }
     $entity = \Drupal::entityManager()->getStorage($context['entity_type'])->load($context['entity_id']);
     $field_name = $context['field_name'];
     $page_number = \Drupal::entityManager()->getStorage('comment')->getNewCommentPageNumber($entity->{$field_name}->comment_count, $new, $entity);
     $query = $page_number ? array('page' => $page_number) : NULL;
     // Attach metadata.
     $element['#attached']['js'][] = array('type' => 'setting', 'data' => array('comment' => array('newCommentsLinks' => array($context['entity_type'] => array($context['field_name'] => array($context['entity_id'] => array('new_comment_count' => (int) $new, 'first_new_comment_link' => \Drupal::urlGenerator()->generateFromPath('node/' . $entity->id(), array('query' => $query, 'fragment' => 'new')))))))));
     return $element;
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function preSave(EntityStorageInterface $storage)
 {
     parent::preSave($storage);
     // This is the easiest way to handle the unique internal path '<front>',
     // since a path marked as external does not need to match a route.
     $this->external = UrlHelper::isExternal($this->link_path) || $this->link_path == '<front>' ? 1 : 0;
     // Try to find a parent link. If found, assign it and derive its menu.
     $parent = $this->findParent($storage);
     if ($parent) {
         $this->plid = $parent->id();
         $this->menu_name = $parent->menu_name;
     } else {
         $this->plid = 0;
     }
     // Directly fill parents for top-level links.
     if ($this->plid == 0) {
         $this->p1 = $this->id();
         for ($i = 2; $i <= MENU_MAX_DEPTH; $i++) {
             $parent_property = "p{$i}";
             $this->{$parent_property} = 0;
         }
         $this->depth = 1;
     } else {
         if ($this->has_children && $this->original) {
             $limit = MENU_MAX_DEPTH - $storage->findChildrenRelativeDepth($this->original) - 1;
         } else {
             $limit = MENU_MAX_DEPTH - 1;
         }
         if ($parent->depth > $limit) {
             return FALSE;
         }
         $this->depth = $parent->depth + 1;
         $this->setParents($parent);
     }
     // Need to check both plid and menu_name, since plid can be 0 in any menu.
     if (isset($this->original) && ($this->plid != $this->original->plid || $this->menu_name != $this->original->menu_name)) {
         $storage->moveChildren($this);
     }
     // Find the route_name.
     if (!$this->external && !isset($this->route_name)) {
         $url = Url::createFromPath($this->link_path);
         $this->route_name = $url->getRouteName();
         $this->route_parameters = $url->getRouteParameters();
     } elseif (empty($this->link_path)) {
         $this->link_path = \Drupal::urlGenerator()->getPathFromRoute($this->route_name, $this->route_parameters);
     }
 }
Example #23
0
 public static function getLayoutPageVariantClientData(LayoutPageVariantInterface $page_variant)
 {
     $page = $page_variant->getPage();
     return array('layout' => array('id' => $page->id(), 'pageId' => $page->id(), 'variantId' => $page_variant->id(), 'layoutData' => self::getGroupedBlockArrays($page_variant), 'locked' => FALSE, 'webserviceURL' => \Drupal::urlGenerator()->generateFromRoute('layout.page_variant_layout_rest', array('page' => $page->id(), 'page_variant_id' => $page_variant->id()))));
 }
Example #24
0
 /**
  * Tests the urlGenerator() method.
  *
  * @covers ::urlGenerator
  */
 public function testUrlGenerator()
 {
     $this->setMockContainerService('url_generator');
     $this->assertNotNull(\Drupal::urlGenerator());
 }
Example #25
0
 /**
  * {@inheritdoc}
  *
  * We override ::render() so that we can add our own content above the table.
  * parent::render() is where EntityListBuilder creates the table using our
  * buildHeader() and buildRow() implementations.
  */
 public function render()
 {
     $build['description'] = array('#markup' => $this->t('Magic Cards implements a Card Base model. These card bases are fieldable entities. You can manage the fields on the <a href="@adminlink">Card Bases admin page</a>.', array('@adminlink' => \Drupal::urlGenerator()->generateFromRoute('magic_cards.card_base_settings'))));
     $build['table'] = parent::render();
     return $build;
 }
 /**
  * {@inheritdoc}
  *
  * We override ::render() so that we can add our own content above the table.
  * parent::render() is where EntityListBuilder creates the table using our
  * buildHeader() and buildRow() implementations.
  */
 public function render()
 {
     $build['description'] = array('#markup' => $this->t('Content Entity Example implements a Reservation model. These reservations are not fieldable entities. You can manage the fields on the <a href="@adminlink">Reservation admin page</a>.', array('@adminlink' => \Drupal::urlGenerator()->generateFromRoute('entity.reservation.list'))));
     $build['table'] = parent::render();
     return $build;
 }
 /**
  * Adds autocomplete functionality to elements.
  *
  * This sets up autocomplete functionality for elements with an
  * #autocomplete_route_name property, using the #autocomplete_route_parameters
  * property if present.
  *
  * For example, suppose your autocomplete route name is
  * 'mymodule.autocomplete' and its path is
  * '/mymodule/autocomplete/{a}/{b}'. In a form array, you would create a text
  * field with properties:
  * @code
  * '#autocomplete_route_name' => 'mymodule.autocomplete',
  * '#autocomplete_route_parameters' => array('a' => $some_key, 'b' => $some_id),
  * @endcode
  * If the user types "keywords" in that field, the full path called would be:
  * 'mymodule_autocomplete/$some_key/$some_id?q=keywords'
  *
  * @param array $element
  *   The form element to process. Properties used:
  *   - #autocomplete_route_name: A route to be used as callback URL by the
  *     autocomplete JavaScript library.
  *   - #autocomplete_route_parameters: The parameters to be used in
  *     conjunction with the route name.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  * @param array $complete_form
  *   The complete form structure.
  *
  * @return array
  *   The form element.
  */
 public static function processAutocomplete(&$element, FormStateInterface $form_state, &$complete_form)
 {
     $access = FALSE;
     if (!empty($element['#autocomplete_route_name'])) {
         $parameters = isset($element['#autocomplete_route_parameters']) ? $element['#autocomplete_route_parameters'] : array();
         $path = \Drupal::urlGenerator()->generate($element['#autocomplete_route_name'], $parameters);
         $access = \Drupal::service('access_manager')->checkNamedRoute($element['#autocomplete_route_name'], $parameters, \Drupal::currentUser());
     }
     if ($access) {
         $element['#attributes']['class'][] = 'form-autocomplete';
         $element['#attached']['library'][] = 'core/drupal.autocomplete';
         // Provide a data attribute for the JavaScript behavior to bind to.
         $element['#attributes']['data-autocomplete-path'] = $path;
     }
     return $element;
 }
 /**
  * Tests that the translation overview shows the correct values.
  */
 protected function doTestTranslationOverview()
 {
     $entity = entity_load($this->entityTypeId, $this->entityId, TRUE);
     $this->drupalGet($entity->getSystemPath('drupal:content-translation-overview'));
     foreach ($this->langcodes as $langcode) {
         if ($entity->hasTranslation($langcode)) {
             $language = new Language(array('id' => $langcode));
             $view_path = \Drupal::urlGenerator()->generateFromPath($entity->getSystemPath(), array('language' => $language));
             $elements = $this->xpath('//table//a[@href=:href]', array(':href' => $view_path));
             $this->assertEqual((string) $elements[0], $entity->getTranslation($langcode)->label(), format_string('Label correctly shown for %language translation.', array('%language' => $langcode)));
             $edit_path = \Drupal::urlGenerator()->generateFromPath($entity->getSystemPath('edit-form'), array('language' => $language));
             $elements = $this->xpath('//table//ul[@class="dropbutton"]/li/a[@href=:href]', array(':href' => $edit_path));
             $this->assertEqual((string) $elements[0], t('Edit'), format_string('Edit link correct for %language translation.', array('%language' => $langcode)));
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->urlGenerator = \Drupal::urlGenerator();
 }
Example #30
0
// Updating from a site schema version prior to 8000 should block the update
// process. Ensure that the site is not attempting to update a database
// created in a previous version of Drupal.
if (db_table_exists('system')) {
    $system_schema = db_query('SELECT schema_version FROM {system} WHERE name = :system', array(':system' => 'system'))->fetchField();
    if ($system_schema < \Drupal::CORE_MINIMUM_SCHEMA_VERSION) {
        print 'Your system schema version is ' . $system_schema . '. Updating directly from a schema version prior to 8000 is not supported. You must <a href="https://drupal.org/node/2179269">migrate your site to Drupal 8</a> first.';
        exit;
    }
}
$kernel->prepareLegacyRequest($request);
// Determine if the current user has access to run update.php.
\Drupal::service('session_manager')->startLazy();
// Ensure that URLs generated for the home and admin pages don't have 'update.php'
// in them.
$generator = \Drupal::urlGenerator();
$generator->setBasePath(str_replace('/core', '', $request->getBasePath()) . '/');
$generator->setScriptPath('');
// There can be conflicting 'op' parameters because both update and batch use
// this parameter name. We need the 'op' coming from a POST request to trump
// that coming from a GET request.
$op = $request->request->get('op');
if (is_null($op)) {
    $op = $request->query->get('op');
}
// Only allow the requirements check to proceed if the current user has access
// to run updates (since it may expose sensitive information about the site's
// configuration).
if (is_null($op) && update_access_allowed()) {
    require_once __DIR__ . '/includes/install.inc';
    require_once DRUPAL_ROOT . '/core/modules/system/system.install';