/**
  * Tests the output process.
  */
 public function testProcessOutbound()
 {
     $expected_cacheability = (new BubbleableMetadata())->addCacheContexts(['route'])->setCacheMaxAge(Cache::PERMANENT);
     $request_stack = \Drupal::requestStack();
     /** @var \Symfony\Component\Routing\RequestContext $request_context */
     $request_context = \Drupal::service('router.request_context');
     // Test request with subdir on homepage.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request with subdir on other page.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/node/add');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request without subdir on the homepage.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request without subdir on other page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/node/add');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request without a found route. This happens for example on an
     // not found exception page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/invalid-path', 'GET', [], [], [], $server);
     $request_stack->push($request);
     $request_context->fromRequest($request);
     // In case we have no routing, the current route should point to the front,
     // and the cacheability does not depend on the 'route' cache context, since
     // no route was involved at all: this is fallback behavior.
     $url = GeneratedUrl::createFromObject((new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT))->setGeneratedUrl('/');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
 }
 /**
  * Tests bubbleable metadata of menu links' outbound route/path processing.
  */
 public function testOutboundPathAndRouteProcessing()
 {
     \Drupal::service('router.builder')->rebuild();
     $request_stack = \Drupal::requestStack();
     /** @var \Symfony\Component\Routing\RequestContext $request_context */
     $request_context = \Drupal::service('router.request_context');
     $request = Request::create('/');
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $menu_tree = \Drupal::menuTree();
     $renderer = \Drupal::service('renderer');
     $default_menu_cacheability = (new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT)->setCacheTags(['config:system.menu.tools'])->setCacheContexts(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions']);
     User::create(['uid' => 1, 'name' => $this->randomString()])->save();
     User::create(['uid' => 2, 'name' => $this->randomString()])->save();
     // Five test cases, four asserting one outbound path/route processor, and
     // together covering one of each:
     // - no cacheability metadata,
     // - a cache context,
     // - a cache tag,
     // - a cache max-age.
     // Plus an additional test case to verify that multiple links adding
     // cacheability metadata of the same type is working (two links with cache
     // tags).
     $test_cases = [['uri' => 'route:<current>', 'cacheability' => (new BubbleableMetadata())->setCacheContexts(['route'])], ['uri' => 'route:outbound_processing_test.route.csrf', 'cacheability' => (new BubbleableMetadata())->setCacheContexts(['session'])->setAttachments(['placeholders' => []])], ['uri' => 'internal:/', 'cacheability' => new BubbleableMetadata()], ['uri' => 'internal:/user/1', 'cacheability' => (new BubbleableMetadata())->setCacheTags(User::load(1)->getCacheTags())], ['uri' => 'internal:/user/2', 'cacheability' => (new BubbleableMetadata())->setCacheTags(User::load(2)->getCacheTags())]];
     // Test each expectation individually.
     foreach ($test_cases as $expectation) {
         $menu_link_content = MenuLinkContent::create(['link' => ['uri' => $expectation['uri']], 'menu_name' => 'tools']);
         $menu_link_content->save();
         $tree = $menu_tree->load('tools', new MenuTreeParameters());
         $build = $menu_tree->build($tree);
         $renderer->renderRoot($build);
         $expected_cacheability = $default_menu_cacheability->merge($expectation['cacheability']);
         $this->assertEqual($expected_cacheability, BubbleableMetadata::createFromRenderArray($build));
         $menu_link_content->delete();
     }
     // Now test them all together in one menu: the rendered menu's cacheability
     // metadata should be the combination of the cacheability of all links, and
     // thus of all tested outbound path & route processors.
     $expected_cacheability = new BubbleableMetadata();
     foreach ($test_cases as $expectation) {
         $menu_link_content = MenuLinkContent::create(['link' => ['uri' => $expectation['uri']], 'menu_name' => 'tools']);
         $menu_link_content->save();
         $expected_cacheability = $expected_cacheability->merge($expectation['cacheability']);
     }
     $tree = $menu_tree->load('tools', new MenuTreeParameters());
     $build = $menu_tree->build($tree);
     $renderer->renderRoot($build);
     $expected_cacheability = $expected_cacheability->merge($default_menu_cacheability);
     $this->assertEqual($expected_cacheability, BubbleableMetadata::createFromRenderArray($build));
 }
Example #3
0
 /**
  * Tests the output process.
  */
 public function testProcessOutbound()
 {
     $expected_cacheability = (new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT);
     $request_stack = \Drupal::requestStack();
     /** @var \Symfony\Component\Routing\RequestContext $request_context */
     $request_context = \Drupal::service('router.request_context');
     // Test request with subdir on homepage.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], [], TRUE, TRUE));
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('#test-fragment');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], ['fragment' => 'test-fragment'], TRUE));
     // Test request with subdir on other page.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], [], TRUE, TRUE));
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('#test-fragment');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], ['fragment' => 'test-fragment'], TRUE));
     // Test request without subdir on the homepage.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], [], TRUE, TRUE));
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('#test-fragment');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], ['fragment' => 'test-fragment'], TRUE));
     // Test request without subdir on other page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], [], TRUE, TRUE));
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('#test-fragment');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<none>', [], ['fragment' => 'test-fragment'], TRUE));
 }
 /**
  * Tests the output process.
  */
 public function testProcessOutbound()
 {
     $request_stack = \Drupal::requestStack();
     /** @var \Symfony\Component\Routing\RequestContext $request_context */
     $request_context = \Drupal::service('router.request_context');
     // Test request with subdir on homepage.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('/subdir/', \Drupal::url('<current>'));
     // Test request with subdir on other page.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('/subdir/node/add', \Drupal::url('<current>'));
     // Test request without subdir on the homepage.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('/', \Drupal::url('<current>'));
     // Test request without subdir on other page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('/node/add', \Drupal::url('<current>'));
     // Test request without a found route. This happens for example on an
     // not found exception page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/invalid-path', 'GET', [], [], [], $server);
     $request_stack->push($request);
     $request_context->fromRequest($request);
     // In case we have no routing, the current route should point to the front.
     $this->assertEqual('/', \Drupal::url('<current>'));
 }
Example #5
0
 /**
  * Tests the output process.
  */
 public function testProcessOutbound()
 {
     $request_stack = \Drupal::requestStack();
     /** @var \Symfony\Component\Routing\RequestContext $request_context */
     $request_context = \Drupal::service('router.request_context');
     // Test request with subdir on homepage.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('', \Drupal::url('<none>'));
     $this->assertEqual('#test-fragment', \Drupal::url('<none>', [], ['fragment' => 'test-fragment']));
     // Test request with subdir on other page.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('', \Drupal::url('<none>'));
     $this->assertEqual('#test-fragment', \Drupal::url('<none>', [], ['fragment' => 'test-fragment']));
     // Test request without subdir on the homepage.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('', \Drupal::url('<none>'));
     $this->assertEqual('#test-fragment', \Drupal::url('<none>', [], ['fragment' => 'test-fragment']));
     // Test request without subdir on other page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $this->assertEqual('', \Drupal::url('<none>'));
     $this->assertEqual('#test-fragment', \Drupal::url('<none>', [], ['fragment' => 'test-fragment']));
 }
 /**
  * {@inheritDoc}
  */
 protected function write(array $record)
 {
     // Pre-bootstrap errors
     if (!function_exists('module_implements')) {
         return;
     }
     $request = \Drupal::requestStack()->getCurrentRequest();
     // Remove unwanted stuff from the context, do not attempt to serialize
     // potential PDO instances of stuff like that may lie into unserialized
     // exceptions in there
     $message = empty($record['formatted']) ? $record['message'] : $record['formatted'];
     foreach ($record['context'] as $key => $value) {
         // @todo temporary avoir Array to string conversion warnings
         if (!is_array($value)) {
             $record['context'][$key] = (string) $value;
         }
     }
     // If you are dblogging stuff, using <br/> tags is advised for readability
     $message = nl2br($message);
     $entry = ['severity' => self::monologToDrupal($record['level']), 'type' => 'monolog', 'message' => $message, 'variables' => $record['context'], 'link' => '', 'user' => null, 'uid' => \Drupal::currentUser()->id(), 'request_uri' => $request->getRequestUri(), 'referer' => $request->headers->get('referer'), 'ip' => $request->getClientIp(), 'timestamp' => $record['datetime']->getTimestamp()];
     foreach (module_implements('watchdog') as $module) {
         module_invoke($module, 'watchdog', $entry);
     }
 }
Example #7
0
 public function renderPreview($display_id, $args = array())
 {
     // Save the current path so it can be restored before returning from this function.
     $request_stack = \Drupal::requestStack();
     $current_request = $request_stack->getCurrentRequest();
     $executable = $this->getExecutable();
     // Determine where the query and performance statistics should be output.
     $config = \Drupal::config('views.settings');
     $show_query = $config->get('ui.show.sql_query.enabled');
     $show_info = $config->get('ui.show.preview_information');
     $show_location = $config->get('ui.show.sql_query.where');
     $show_stats = $config->get('ui.show.performance_statistics');
     if ($show_stats) {
         $show_stats = $config->get('ui.show.sql_query.where');
     }
     $combined = $show_query && $show_stats;
     $rows = array('query' => array(), 'statistics' => array());
     $errors = $executable->validate();
     $executable->destroy();
     if (empty($errors)) {
         $this->ajax = TRUE;
         $executable->live_preview = TRUE;
         // AJAX happens via HTTP POST but everything expects exposed data to
         // be in GET. Copy stuff but remove ajax-framework specific keys.
         // If we're clicking on links in a preview, though, we could actually
         // have some input in the query parameters, so we merge request() and
         // query() to ensure we get it all.
         $exposed_input = array_merge(\Drupal::request()->request->all(), \Drupal::request()->query->all());
         foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER, 'ajax_page_state', 'form_id', 'form_build_id', 'form_token') as $key) {
             if (isset($exposed_input[$key])) {
                 unset($exposed_input[$key]);
             }
         }
         $executable->setExposedInput($exposed_input);
         if (!$executable->setDisplay($display_id)) {
             return ['#markup' => t('Invalid display id @display', array('@display' => $display_id))];
         }
         $executable->setArguments($args);
         // Store the current view URL for later use:
         if ($executable->hasUrl() && $executable->display_handler->getOption('path')) {
             $path = $executable->getUrl();
         }
         // Make view links come back to preview.
         // Also override the current path so we get the pager, and make sure the
         // Request object gets all of the proper values from $_SERVER.
         $request = Request::createFromGlobals();
         $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'entity.view.preview_form');
         $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, \Drupal::service('router.route_provider')->getRouteByName('entity.view.preview_form'));
         $request->attributes->set('view', $this->storage);
         $request->attributes->set('display_id', $display_id);
         $raw_parameters = new ParameterBag();
         $raw_parameters->set('view', $this->id());
         $raw_parameters->set('display_id', $display_id);
         $request->attributes->set('_raw_variables', $raw_parameters);
         foreach ($args as $key => $arg) {
             $request->attributes->set('arg_' . $key, $arg);
         }
         $request_stack->push($request);
         // Suppress contextual links of entities within the result set during a
         // Preview.
         // @todo We'll want to add contextual links specific to editing the View, so
         //   the suppression may need to be moved deeper into the Preview pipeline.
         views_ui_contextual_links_suppress_push();
         $show_additional_queries = $config->get('ui.show.additional_queries');
         Timer::start('entity.view.preview_form');
         if ($show_additional_queries) {
             $this->startQueryCapture();
         }
         // Execute/get the view preview.
         $preview = $executable->preview($display_id, $args);
         if ($show_additional_queries) {
             $this->endQueryCapture();
         }
         $this->render_time = Timer::stop('entity.view.preview_form');
         views_ui_contextual_links_suppress_pop();
         // Prepare the query information and statistics to show either above or
         // below the view preview.
         if ($show_info || $show_query || $show_stats) {
             // Get information from the preview for display.
             if (!empty($executable->build_info['query'])) {
                 if ($show_query) {
                     $query_string = $executable->build_info['query'];
                     // Only the sql default class has a method getArguments.
                     $quoted = array();
                     if ($executable->query instanceof Sql) {
                         $quoted = $query_string->getArguments();
                         $connection = Database::getConnection();
                         foreach ($quoted as $key => $val) {
                             if (is_array($val)) {
                                 $quoted[$key] = implode(', ', array_map(array($connection, 'quote'), $val));
                             } else {
                                 $quoted[$key] = $connection->quote($val);
                             }
                         }
                     }
                     $rows['query'][] = array(array('data' => array('#type' => 'inline_template', '#template' => "<strong>{% trans 'Query' %}</strong>")), array('data' => array('#type' => 'inline_template', '#template' => '<pre>{{ query }}</pre>', '#context' => array('query' => strtr($query_string, $quoted)))));
                     if (!empty($this->additionalQueries)) {
                         $queries[] = array('#prefix' => '<strong>', '#markup' => t('These queries were run during view rendering:'), '#suffix' => '</strong>');
                         foreach ($this->additionalQueries as $query) {
                             $query_string = strtr($query['query'], $query['args']);
                             $queries[] = array('#prefix' => "\n", '#markup' => t('[@time ms] @query', array('@time' => round($query['time'] * 100000, 1) / 100000.0, '@query' => $query_string)));
                         }
                         $rows['query'][] = array(array('data' => array('#type' => 'inline_template', '#template' => "<strong>{% trans 'Other queries' %}</strong>")), array('data' => array('#prefix' => '<pre>', 'queries' => $queries, '#suffix' => '</pre>')));
                     }
                 }
                 if ($show_info) {
                     $rows['query'][] = array(array('data' => array('#type' => 'inline_template', '#template' => "<strong>{% trans 'Title' %}</strong>")), Xss::filterAdmin($executable->getTitle()));
                     if (isset($path)) {
                         // @todo Views should expect and store a leading /. See:
                         //   https://www.drupal.org/node/2423913
                         $path = \Drupal::l($path->toString(), $path);
                     } else {
                         $path = t('This display has no path.');
                     }
                     $rows['query'][] = array(array('data' => array('#prefix' => '<strong>', '#markup' => t('Path'), '#suffix' => '</strong>')), array('data' => array('#markup' => $path)));
                 }
                 if ($show_stats) {
                     $rows['statistics'][] = array(array('data' => array('#type' => 'inline_template', '#template' => "<strong>{% trans 'Query build time' %}</strong>")), t('@time ms', array('@time' => intval($executable->build_time * 100000) / 100)));
                     $rows['statistics'][] = array(array('data' => array('#type' => 'inline_template', '#template' => "<strong>{% trans 'Query execute time' %}</strong>")), t('@time ms', array('@time' => intval($executable->execute_time * 100000) / 100)));
                     $rows['statistics'][] = array(array('data' => array('#type' => 'inline_template', '#template' => "<strong>{% trans 'View render time' %}</strong>")), t('@time ms', array('@time' => intval($executable->render_time * 100000) / 100)));
                 }
                 \Drupal::moduleHandler()->alter('views_preview_info', $rows, $executable);
             } else {
                 // No query was run. Display that information in place of either the
                 // query or the performance statistics, whichever comes first.
                 if ($combined || $show_location === 'above') {
                     $rows['query'][] = array(array('data' => array('#prefix' => '<strong>', '#markup' => t('Query'), '#suffix' => '</strong>')), array('data' => array('#markup' => t('No query was run'))));
                 } else {
                     $rows['statistics'][] = array(array('data' => array('#prefix' => '<strong>', '#markup' => t('Query'), '#suffix' => '</strong>')), array('data' => array('#markup' => t('No query was run'))));
                 }
             }
         }
     } else {
         foreach ($errors as $display_errors) {
             foreach ($display_errors as $error) {
                 drupal_set_message($error, 'error');
             }
         }
         $preview = t('Unable to preview due to validation errors.');
     }
     // Assemble the preview, the query info, and the query statistics in the
     // requested order.
     $table = array('#type' => 'table', '#prefix' => '<div class="views-query-info">', '#suffix' => '</div>');
     if ($show_location === 'above' || $show_location === 'below') {
         if ($combined) {
             $table['#rows'] = array_merge($rows['query'], $rows['statistics']);
         } else {
             $table['#rows'] = $rows['query'];
         }
     } elseif ($show_stats === 'above' || $show_stats === 'below') {
         $table['#rows'] = $rows['statistics'];
     }
     if ($show_location === 'above' || $show_stats === 'above') {
         $output = ['table' => $table, 'preview' => $preview];
     } elseif ($show_location === 'below' || $show_stats === 'below') {
         $output = ['preview' => $preview, 'table' => $table];
     }
     // Ensure that we just remove an additional request we pushed earlier.
     // This could happen if $errors was not empty.
     if ($request_stack->getCurrentRequest() != $current_request) {
         $request_stack->pop();
     }
     return $output;
 }
Example #8
0
 /**
  * Ensure page-front template suggestion is added when on front page.
  */
 function testFrontPageThemeSuggestion()
 {
     // Set the current route to user.login because theme_get_suggestions() will
     // query it to see if we are on the front page.
     $request = Request::create('/user/login');
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'user.login');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/user/login'));
     \Drupal::requestStack()->push($request);
     $this->config('system.site')->set('page.front', 'user/login')->save();
     $suggestions = theme_get_suggestions(array('user', 'login'), 'page');
     // Set it back to not annoy the batch runner.
     \Drupal::requestStack()->pop();
     $this->assertTrue(in_array('page__front', $suggestions), 'Front page template was suggested.');
 }
Example #9
0
 /**
  * {@inheritdoc}
  */
 public function isRenderedInCurrentRequest()
 {
     $request = \Drupal::requestStack()->getMasterRequest();
     $explode = explode('.', $request->get('_route'));
     $prefix = isset($explode[0]) ? $explode[0] : '';
     $id = isset($explode[2]) ? $explode[2] : '';
     if (!empty($prefix) && !empty($id)) {
         if ($prefix . ':' . $id == 'search_api_page:' . $request->get('search_api_page_name')) {
             return TRUE;
         }
     }
     return FALSE;
 }
 /**
  * {@inheritdoc}
  */
 public function isRenderedInCurrentRequest()
 {
     $request = \Drupal::requestStack()->getMasterRequest();
     $search_page = $request->attributes->get('entity');
     if ($search_page instanceof SearchPageInterface) {
         $facet_source_id = 'core_node_search:' . $search_page->id();
         if ($facet_source_id == $this->getPluginId()) {
             return TRUE;
         }
     }
     return FALSE;
 }
Example #11
0
 /**
  * Tests the testRequestStack() method.
  *
  * @covers ::requestStack
  */
 public function testRequestStack()
 {
     $request_stack = new RequestStack();
     $this->setMockContainerService('request_stack', $request_stack);
     $this->assertSame($request_stack, \Drupal::requestStack());
 }
 /**
  * Override the redirect set by \Drupal\comment\CommentForm::save().
  *
  * Drupal needs to redirect the form back to itself so that processing
  * completes and the new comments appears in the markup returned by the
  * ajax response. If we merely unset the redirect to the node page, the new
  * comment will not appear until the next page refresh.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   The current state of the form.
  */
 public static function save(array $form, FormStateInterface $form_state)
 {
     // Code adapted from FormSubmitter::redirectForm().
     $request = \Drupal::requestStack()->getCurrentRequest();
     $form_state->setRedirect('<current>', [], ['query' => $request->query->all(), 'absolute' => TRUE]);
 }
 /**
  * {@inheritdoc}
  */
 public function isRenderedInCurrentRequest()
 {
     $request = \Drupal::requestStack()->getMasterRequest();
     if ($request->get('_route') === str_replace(':', '.', $this->getPluginId())) {
         return TRUE;
     }
     return FALSE;
 }
Example #14
0
 /**
  * Tests TimestampAgoFormatter.
  */
 public function testTimestampAgoFormatter()
 {
     $data = [];
     foreach (array(1, 2, 3, 4, 5, 6) as $granularity) {
         $data[] = ['future_format' => '@interval hence', 'past_format' => '@interval ago', 'granularity' => $granularity];
     }
     foreach ($data as $settings) {
         $future_format = $settings['future_format'];
         $past_format = $settings['past_format'];
         $granularity = $settings['granularity'];
         $request_time = \Drupal::requestStack()->getCurrentRequest()->server->get('REQUEST_TIME');
         // Test a timestamp in the past
         $value = $request_time - 87654321;
         $expected = SafeMarkup::format($past_format, ['@interval' => \Drupal::service('date.formatter')->formatTimeDiffSince($value, ['granularity' => $granularity])]);
         $component = $this->display->getComponent($this->fieldName);
         $component['type'] = 'timestamp_ago';
         $component['settings'] = $settings;
         $this->display->setComponent($this->fieldName, $component);
         $entity = EntityTest::create([]);
         $entity->{$this->fieldName}->value = $value;
         $this->renderEntityFields($entity, $this->display);
         $this->assertRaw($expected);
         // Test a timestamp in the future
         $value = $request_time + 87654321;
         $expected = SafeMarkup::format($future_format, ['@interval' => \Drupal::service('date.formatter')->formatTimeDiffUntil($value, ['granularity' => $granularity])]);
         $component = $this->display->getComponent($this->fieldName);
         $component['type'] = 'timestamp_ago';
         $component['settings'] = $settings;
         $this->display->setComponent($this->fieldName, $component);
         $entity = EntityTest::create([]);
         $entity->{$this->fieldName}->value = $value;
         $this->renderEntityFields($entity, $this->display);
         $this->assertRaw($expected);
     }
 }
 /**
  * Form API callback: Processes a crop_image field element.
  *
  * Expands the image_image type to include the alt and title fields.
  *
  * This method is assigned as a #process callback in formElement() method.
  */
 public static function process($element, FormStateInterface $form_state, $form)
 {
     $item = $element['#value'];
     $item['fids'] = $element['fids']['#value'];
     $edit = FALSE;
     $route_params = \Drupal::requestStack()->getCurrentRequest()->attributes->get('_route_params');
     if (isset($route_params['_entity_form']) && preg_match('/.edit/', $route_params['_entity_form'])) {
         $edit = TRUE;
     }
     $element['#theme'] = 'image_widget';
     $element['#attached']['library'][] = 'image/form';
     $element['#attached']['library'][] = 'image_widget_crop/drupal.image_widget_crop.admin';
     $element['#attached']['library'][] = 'image_widget_crop/drupal.image_widget_crop.upload.admin';
     // Add the image preview.
     if (!empty($element['#files']) && $element['#preview_image_style']) {
         $file = reset($element['#files']);
         $variables = array('style_name' => $element['#preview_image_style'], 'uri' => $file->getFileUri(), 'file_id' => $file->id());
         /** @var \Drupal\image_widget_crop\ImageWidgetCrop $ImageWidgetCrop */
         $ImageWidgetCrop = new ImageWidgetCrop();
         // Determine image dimensions.
         if (isset($element['#value']['width']) && isset($element['#value']['height'])) {
             $variables['width'] = $element['#value']['width'];
             $variables['height'] = $element['#value']['height'];
         } else {
             $image = \Drupal::service('image.factory')->get($file->getFileUri());
             if ($image->isValid()) {
                 $variables['width'] = $image->getWidth();
                 $variables['height'] = $image->getHeight();
             } else {
                 $variables['width'] = $variables['height'] = NULL;
             }
         }
         $element['crop_preview_wrapper'] = ['#type' => 'container', '#prefix' => '<ul>', '#suffix' => '</ul>', '#attributes' => ['class' => ['preview-wrapper-crop']], '#weight' => 100];
         $image_styles = \Drupal::service('entity.manager')->getStorage('image_style')->loadByProperties(['status' => TRUE]);
         if ($image_styles) {
             /** @var \Drupal\image\Entity\ImageStyle $image_style */
             foreach ($image_styles as $image_style) {
                 if (in_array($image_style->getName(), $element['#crop_list'])) {
                     // Get the ratio of image by ImageStyle.
                     $ratio = $ImageWidgetCrop->getSizeRatio($image_style);
                     // Generation of html List with image & crop informations.
                     // @todo Create new elements for styling the crop container & lists.
                     $element['crop_preview_wrapper'][$image_style->getName()] = ['#type' => 'container', '#prefix' => "<li data-ratio={$ratio}>", '#suffix' => '</li>', '#attributes' => ['class' => ['crop-preview-wrapper-list']], '#weight' => -10];
                     $element['crop_preview_wrapper'][$image_style->getName()]['title'] = ['#prefix' => '<p>', '#suffix' => '</p>', '#markup' => t('@style_label - ( <b>real ratio</b> @ratio )', ['@style_label' => $image_style->label(), '@ratio' => $ratio])];
                     $element['crop_preview_wrapper'][$image_style->getName()]['image'] = ['#theme' => 'image_style', '#style_name' => $element['#crop_preview_image_style'], '#uri' => $variables['uri']];
                     // GET CROP LIBRARIE VALUES.
                     $crop_elements = ['x1' => ['label' => t('crop x1'), 'value' => NULL], 'x2' => ['label' => t('crop x2'), 'value' => NULL], 'y1' => ['label' => t('crop y1'), 'value' => NULL], 'y2' => ['label' => t('crop y2'), 'value' => NULL], 'crop-w' => ['label' => t('crop size width'), 'value' => NULL], 'crop-h' => ['label' => t('crop size height'), 'value' => NULL], 'thumb-w' => ['label' => t('Thumbnail Width'), 'value' => NULL], 'thumb-h' => ['label' => t('Thumbnail Height'), 'value' => NULL]];
                     if ($edit) {
                         $crop = \Drupal::service('entity.manager')->getStorage('crop')->loadByProperties(['type' => $ImageWidgetCrop->getCropType($image_style), 'uri' => $variables['uri'], 'image_style' => $image_style->getName()]);
                         // Only if the crop already exist pre-populate,
                         // all cordinates values.
                         if (!empty($crop)) {
                             /** @var \Drupal\crop\Entity\Crop $crop_entity */
                             foreach ($crop as $crop_id => $crop_entity) {
                                 $crop_properties = ['anchor' => $crop_entity->position(), 'size' => $crop_entity->size()];
                             }
                             // If the current crop have a position & sizes,
                             // calculate properties to apply crop selection into preview.
                             if (isset($crop_properties)) {
                                 $values = static::getThumbnailCropProperties($variables['uri'], $crop_properties);
                             }
                             if (!empty($values)) {
                                 // Populate form crop value with values store into crop API.
                                 foreach ($crop_elements as $properties => $value) {
                                     $crop_elements[$properties]['value'] = $values[$properties];
                                 }
                             }
                         }
                     }
                     // Generate all cordinates elements into the form when,
                     // process is active.
                     foreach ($crop_elements as $crop_elements_name => $crop_elements_value) {
                         $element['crop_preview_wrapper'][$image_style->getName()][$crop_elements_name] = ['#type' => 'textfield', '#title' => $crop_elements_value['label'], '#attributes' => ['class' => ["crop-{$crop_elements_name}"]], '#default_value' => !empty($edit) ? $crop_elements_value['value'] : NULL];
                     }
                     // Stock Original File Values.
                     $element['file-uri'] = ['#type' => 'value', '#value' => $variables['uri']];
                     $element['file-id'] = ['#type' => 'value', '#value' => $variables['file_id']];
                 }
             }
         }
     }
     return parent::process($element, $form_state, $form);
 }
Example #16
0
 /**
  * Sets up a request on the request stack with a specified format.
  *
  * @param string $format
  *   The new request format.
  */
 protected function addRequestWithFormat($format)
 {
     $request = \Drupal::request();
     $request = clone $request;
     $request->setRequestFormat($format);
     \Drupal::requestStack()->push($request);
 }
 public function test25()
 {
     return ['#cache' => ['url'], '#markup' => \Drupal::requestStack()->getCurrentRequest()->getUri()];
 }
Example #18
0
 /**
  * {@inheritdoc}
  */
 public function isRenderedInCurrentRequest()
 {
     $display = View::load($this->pluginDefinition['view_id'])->getDisplay($this->pluginDefinition['view_display']);
     switch ($display['display_plugin']) {
         case 'page':
             $request = \Drupal::requestStack()->getMasterRequest();
             if ($request->attributes->get('_controller') === 'Drupal\\views\\Routing\\ViewPageController::handle') {
                 list(, $search_api_view_id, $search_api_view_display) = explode(':', $this->getPluginId());
                 if ($request->attributes->get('view_id') == $search_api_view_id && $request->attributes->get('display_id') == $search_api_view_display) {
                     return TRUE;
                 }
             }
             return FALSE;
         case 'block':
             // There is no way to know if a block is embedded on a page, because
             // blocks can be rendered in isolation (see big_pipe, esi, ...). To be
             // sure we're not disclosing information we're not sure about, we always
             // return false.
             return FALSE;
     }
     return FALSE;
 }