setRequest example

$render_cache = \Drupal::service('render_cache');

    $build = $view->buildRenderable();
    $original = $build;

    // Ensure the current request is a GET request so that render caching is     // active for direct rendering of views, just like for actual requests.     /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
    $request_stack = \Drupal::service('request_stack');
    $request = Request::createFromGlobals();
    $request->server->set('REQUEST_TIME', REQUEST_TIME);
    $view->setRequest($request);
    $request_stack->push($request);
    $renderer->renderRoot($build);

    // Check render array cache tags.     sort($expected_render_array_cache_tags);
    $this->assertEqualsCanonicalizing($expected_render_array_cache_tags$build['#cache']['tags']);

    if ($views_caching_is_enabled) {
      // Check Views render cache item cache tags.       /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
      $cache_plugin = $view->display_handler->getPlugin('cache');

      
/** * Instantiates a ViewExecutable class. * * @param \Drupal\views\ViewEntityInterface $view * A view entity instance. * * @return \Drupal\views\ViewExecutable * A ViewExecutable instance. */
  public function get(ViewEntityInterface $view) {
    $view_executable = new ViewExecutable($view$this->user, $this->viewsData, $this->routeProvider);
    $view_executable->setRequest($this->requestStack->getCurrentRequest());
    return $view_executable;
  }

}
public function testTable() {
    $view = Views::getView('test_table');

    $view->setDisplay('default');
    $view->initStyle();
    $view->initHandlers();
    $view->initQuery();
    $style_plugin = $view->style_plugin;

    // Test the buildSort() method.     $request = new Request();
    $view->setRequest($request);

    $style_plugin->options['override'] = FALSE;

    $style_plugin->options['default'] = '';
    $this->assertTrue($style_plugin->buildSort(), 'If no order and no default order is specified, the normal sort should be used.');

    $style_plugin->options['default'] = 'id';
    $this->assertTrue($style_plugin->buildSort(), 'If no order but a default order is specified, the normal sort should be used.');

    $request->attributes->set('order', $this->randomMachineName());
    $this->assertTrue($style_plugin->buildSort(), 'If no valid field is chosen for order, the normal sort should be used.');

    
        // instance get the right one.         Services::injectMock('request', $request);

        // Make sure filters are reset between tests         Services::injectMock('filters', Services::filters(null, false));

        // Make sure validation is reset between tests         Services::injectMock('validation', Services::validation(null, false));

        $response = $this->app
            ->setContext('web')
            ->setRequest($request)
            ->run($routes, true);

        // Reset directory if it has been set         Services::router()->setDirectory(null);

        return new TestResponse($response);
    }

    /** * Performs a GET request. * * @param string $path URI path relative to baseURL. May include query. * * @return TestResponse * * @throws RedirectException * @throws Exception */
public function dispatch($url = null, $followRedirects = false)
    {
        $request = $this->Request();
        if ($url !== null) {
            $request->setRequestUri($url);
        }
        $request->setPathInfo(null);

        $response = $this->Response();

        $front = $this->Front()
                ->setRequest($request)
                ->setResponse($response);

        $front->dispatch();

        if ($followRedirects && $this->Response()->getStatusCode() === Response::HTTP_FOUND) {
            $link = parse_url($this->Response()->getHeader('Location'), PHP_URL_PATH);
            if ($link === false) {
                throw new RuntimeException('Could not redirect as the "Location" header is not set');
            }
            $this->resetResponse();
            $cookies = $this->Response()->getCookies();
            

    $view->execute();
    $this->assertIdenticalResultset($view$expected[$column => $column]);

    // Test click sorting.     $view = Views::getView($view_id);
    $view->removeHandler('default', 'sort', 'moderation_state');
    $request = new Request([
      'order' => 'moderation_state',
      'sort' => strtolower($order),
    ]);
    $view->setRequest($request);
    $view->execute();
    $this->assertIdenticalResultset($view$expected[$column => $column]);
  }

}
      $this->storage = \Drupal::entityTypeManager()->getStorage('view')
        ->load($this->serializationData['storage']);
      $this->storage->set('executable', $this);

      // Attach all necessary services.       $this->user = \Drupal::currentUser();
      $this->viewsData = \Drupal::service('views.views_data');
      $this->routeProvider = \Drupal::service('router.route_provider');

      // Restore the state of this executable.       if ($request = \Drupal::request()) {
        $this->setRequest($request);
      }
      $this->setDisplay($this->serializationData['current_display']);
      $this->setArguments($this->serializationData['args']);
      $this->setCurrentPage($this->serializationData['current_page']);
      $this->setExposedInput($this->serializationData['exposed_input']);
      $this->exposed_data = $this->serializationData['exposed_data'];
      $this->exposed_raw_input = $this->serializationData['exposed_raw_input'];
      $this->dom_id = $this->serializationData['dom_id'];

      $this->initHandlers();

      
protected function buildMediaLibraryView(MediaLibraryState $state) {
    // @todo Make the view configurable in     // https://www.drupal.org/project/drupal/issues/2971209     $view = $this->entityTypeManager->getStorage('view')->load('media_library');
    $view_executable = $this->viewsExecutableFactory->get($view);
    $display_id = $state->get('views_display_id', 'widget');

    // Make sure the state parameters are set in the request so the view can     // pass the parameters along in the pager, filters etc.     $view_request = $view_executable->getRequest();
    $view_request->query->add($state->all());
    $view_executable->setRequest($view_request);

    $args = [$state->getSelectedTypeId()];

    $view_executable->setDisplay($display_id);
    $view_executable->preExecute($args);
    $view_executable->execute($display_id);

    return $view_executable->buildRenderable($display_id$args, FALSE);
  }

}
public function execute(string $method, ...$params)
    {
        if (method_exists($this->controller, $method) || ! is_callable([$this->controller, $method])) {
            throw new InvalidArgumentException('Method does not exist or is not callable in controller: ' . $method);
        }

        // The URL helper is always loaded by the system         // so ensure it's available.         helper('url');

        $result = (new ControllerResponse())
            ->setRequest($this->request)
            ->setResponse($this->response);

        $response = null;

        try {
            ob_start();

            $response = $this->controller->{$method}(...$params);
        } catch (Throwable $e) {
            $code = $e->getCode();

            
new BasicAuthResolver(
                $this->get(ModelManager::class)
            )
        );

        $adapter->setDigestResolver(
            new StaticResolver(
                $this->get(ModelManager::class)
            )
        );

        $adapter->setRequest($this->request);
        $adapter->setResponse($this->response);

        $resource = Shopware_Components_Auth::getInstance();
        $storage = new Zend_Auth_Storage_NonPersistent();
        $resource->setBaseAdapter($adapter);
        $resource->addAdapter($adapter);
        $resource->setStorage($storage);

        return $resource;
    }
}
if (strpos($handler, '$') !== false && strpos($routeKey, '(') !== false) {
                    // Checks dynamic controller                     if (strpos($controller, '$') !== false) {
                        throw RouterException::forDynamicController($handler);
                    }

                    // Using back-references                     $handler = preg_replace('#^' . $routeKey . '$#u', $handler$uri);
                }

                $this->setRequest(explode('/', $handler));

                $this->setMatchedRoute($matchedKey$handler);

                return true;
            }
        }

        return false;
    }

    /** * Checks Auto Routes. * * Attempts to match a URI path against Controllers and directories * found in APPPATH/Controllers, to find a matching route. * * @return void */

  protected function initViewWithRequest($request_url$view_name = 'taxonomy_default_argument_test') {
    $view = Views::getView($view_name);

    $request = Request::create($request_url);
    $request->server->set('SCRIPT_NAME', $GLOBALS['base_path'] . 'index.php');
    $request->server->set('SCRIPT_FILENAME', 'index.php');

    $response = $this->container->get('http_kernel')
      ->handle($request, HttpKernelInterface::SUB_REQUEST);

    $view->setRequest($request);
    $view->setResponse($response);
    $view->initHandlers();

    return $view;
  }

  /** * Tests the relationship. */
  public function testNodePath() {
    $view = $this->initViewWithRequest($this->nodes[0]->toUrl()->toString());

    
/** * Tests the getArgument() method. * * @covers ::getArgument * @dataProvider providerGetArgument */
  public function testGetArgument($options, Request $request$expected) {
    $view = $this->getMockBuilder('Drupal\views\ViewExecutable')
      ->disableOriginalConstructor()
      ->onlyMethods([])
      ->getMock();
    $view->setRequest($request);
    $display_plugin = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
      ->disableOriginalConstructor()
      ->getMock();

    $raw = new QueryParameter([], 'query_parameter', []);
    $raw->init($view$display_plugin$options);
    $this->assertEquals($expected$raw->getArgument());
  }

  /** * Provides data for testGetArgument(). * * @return array * An array of test data, with the following entries: * - first entry: the options for the plugin. * - second entry: the request object to test with. * - third entry: the expected default argument value. */
$eventArgs
        );

        if (!$this->router) {
            $this->setRouter(Router::class);
        }
        if (!$this->dispatcher) {
            $this->setDispatcher('Enlight_Controller_Dispatcher_Default');
        }

        if (!$this->request) {
            $this->setRequest('Enlight_Controller_Request_RequestHttp');
        }
        if (!$this->response) {
            $this->setResponse('Enlight_Controller_Response_ResponseHttp');
        }

        if ($this->request instanceof SymfonyRequest) {
            $this->requestStack->push($this->request);
        }

        $eventArgs->set('request', $this->Request());
        $eventArgs->set('response', $this->Response());

        
$routes->setHTTPVerb($method);

        // Make sure any other classes that might call the request         // instance get the right one.         Services::injectMock('request', $request);

        // Make sure filters are reset between tests         Services::injectMock('filters', Services::filters(null, false));

        $response = $this->app
            ->setContext('web')
            ->setRequest($request)
            ->run($routes, true);

        $output = \ob_get_contents();
        if (empty($response->getBody()) && ! empty($output)) {
            $response->setBody($output);
        }

        // Reset directory if it has been set         Services::router()->setDirectory(null);

        // Ensure the output buffer is identical so no tests are risky
Home | Imprint | This part of the site doesn't use cookies.