createFromRequest example

// Uncacheable because conversion of the parameter may not have been       // possible due to dynamic circumstances.       $result = AccessResult::forbidden()->setCacheMaxAge(0);
      return $return_as_object ? $result : $result->isAllowed();
    }
  }

  /** * {@inheritdoc} */
  public function checkRequest(Request $request, AccountInterface $account = NULL, $return_as_object = FALSE) {
    $route_match = RouteMatch::createFromRequest($request);
    return $this->check($route_match$account$request$return_as_object);
  }

  /** * {@inheritdoc} */
  public function check(RouteMatchInterface $route_match, AccountInterface $account = NULL, Request $request = NULL, $return_as_object = FALSE) {
    if (!isset($account)) {
      $account = $this->currentUser;
    }
    $route = $route_match->getRouteObject();
    


  /** * @covers ::applies * @dataProvider providerTestApplies */
  public function testApplies($request_data$expected) {
    $request = new Request();
    foreach ($request_data as $key => $data) {
      $request->query->set($key$data);
    }
    $route_match = RouteMatch::createFromRequest($request);
    $this->requestStack->push($request);

    $result = $this->negotiator->applies($route_match);
    $this->assertSame($expected$result);
  }

  public function providerTestApplies() {
    $data = [];
    $data['empty'] = [[], FALSE];
    $data['no_theme'] = [['ajax_page_state' => ['theme' => '', 'theme_token' => '']], FALSE];
    $data['valid_theme_empty_theme_token'] = [['ajax_page_state' => ['theme' => 'claro', 'theme_token' => '']], TRUE];
    
/** * Defines a kernel used for running Functional tests and run-tests.sh. * * @internal */
class TestRunnerKernel extends DrupalKernel {

  /** * {@inheritdoc} */
  public static function createFromRequest(Request $request$class_loader$environment = 'test_runner', $allow_dumping = TRUE, $app_root = NULL) {
    return parent::createFromRequest($request$class_loader$environment$allow_dumping$app_root);
  }

  /** * {@inheritdoc} */
  public function __construct($environment$class_loader$allow_dumping = FALSE, $app_root = NULL) {
    // Force $allow_dumping to FALSE, because the test runner kernel should     // always have to rebuild its container, and potentially avoid isolation     // issues against the tests.     parent::__construct($environment$class_loader, FALSE, $app_root);

    
/** * {@inheritdoc} */
  public function supports(Request $request, ArgumentMetadata $argument): bool {
    return $argument->getType() == RouteMatchInterface::class || is_subclass_of($argument->getType(), RouteMatchInterface::class);
  }

  /** * {@inheritdoc} */
  public function resolve(Request $request, ArgumentMetadata $argument): array {
    return $argument->getType() === RouteMatchInterface::class || is_subclass_of($argument->getType(), RouteMatchInterface::class) ? [RouteMatch::createFromRequest($request)] : [];
  }

}

  protected function defaultFilter(Request $request$provider_id) {
    $route = RouteMatch::createFromRequest($request)->getRouteObject();
    $has_auth_option = isset($route) && $route->hasOption('_auth');

    if ($has_auth_option) {
      return in_array($provider_id$route->getOption('_auth'));
    }
    else {
      return $this->authCollector->isGlobal($provider_id);
    }
  }

}
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;

if (PHP_SAPI !== 'cli') {
  return;
}

// Bootstrap. $autoloader = require __DIR__ . '/../../autoload.php';
$request = Request::createFromGlobals();
Settings::initialize(dirname(__DIR__, 2), DrupalKernel::findSitePath($request)$autoloader);
DrupalKernel::createFromRequest($request$autoloader, 'prod')->boot();

// Run the database dump command. $application = new DbToolsApplication();
$application->run();

  protected function setUp(): void {
    parent::setUpAppRoot();
    $this->zlibInstalled = function_exists('gzopen');

    $request = Request::createFromGlobals();

    // Boot up Drupal into a state where calling the database API is possible.     // This is used to initialize the database system, so we can load the dump     // files.     $autoloader = require $this->root . '/autoload.php';
    $kernel = TestRunnerKernel::createFromRequest($request$autoloader);
    $kernel->loadLegacyIncludes();

    // Set the update URL. This must be set here rather than in     // self::__construct() or the old URL generator will leak additional test     // sites. Additionally, we need to prevent the path alias processor from     // running because we might not have a working alias system before running     // the updates.     $this->updateUrl = Url::fromRoute('system.db_update', []['path_processing' => FALSE]);

    $this->setupBaseUrl();

    
    $hash = $this->iFrameUrlHelper->getHash($url$max_width$max_height);
    if (!hash_equals($hash$request->query->get('hash', ''))) {
      throw new BadRequestHttpException('This resource is not available');
    }

    // Return a response instead of a render array so that the frame content     // will not have all the blocks and page elements normally rendered by     // Drupal.     $response = new HtmlResponse('', HtmlResponse::HTTP_OK, [
      'Content-Type' => 'text/html; charset=UTF-8',
    ]);
    $response->addCacheableDependency(Url::createFromRequest($request));

    try {
      $resource_url = $this->urlResolver->getResourceUrl($url$max_width$max_height);
      $resource = $this->resourceFetcher->fetchResource($resource_url);

      $placeholder_token = Crypt::randomBytesBase64(55);

      // Render the content in a new render context so that the cacheability       // metadata of the rendered HTML will be captured correctly.       $element = [
        '#theme' => 'media_oembed_iframe',
        
$this->eventDispatcher = $event_dispatcher;
  }

  /** * Returns the site maintenance page if the site is offline. * * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event * The event to process. */
  public function onKernelRequestMaintenance(RequestEvent $event) {
    $request = $event->getRequest();
    $route_match = RouteMatch::createFromRequest($request);
    if ($this->maintenanceMode->applies($route_match)) {
      // Don't cache maintenance mode pages.       \Drupal::service('page_cache_kill_switch')->trigger();

      if (!$this->maintenanceMode->exempt($this->account)) {
        // When the account is not exempt, other subscribers handle request.         $this->eventDispatcher->dispatch($event, MaintenanceModeEvents::MAINTENANCE_MODE_REQUEST);
      }
      else {
        // Display a message if the logged-in user has access to the site in         // maintenance mode. Don't show maintenance message:

  protected function getRouteMatch(Request $request) {
    if (isset($this->routeMatches[$request])) {
      $route_match = $this->routeMatches[$request];
    }
    else {
      $route_match = RouteMatch::createFromRequest($request);

      // Since getRouteMatch() might be invoked both before and after routing       // is completed, only statically cache the route match after there's a       // matched route.       if ($route_match->getRouteObject()) {
        $this->routeMatches[$request] = $route_match;
      }
    }
    return $route_match;
  }

  
'keys' => ['view', 'test_page_view', 'display', 'default'],
      ],
    ] + $this->defaultRenderArray;

    $request = new Request();
    $request->attributes->set('view_id', 'test_page_view');
    $request->attributes->set('display_id', 'default');
    $options = [
      '_view_display_plugin_class' => '\Drupal\views\Plugin\views\display\Page',
    ];
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/test', ['view_id' => 'test_page_view', 'display_id' => 'default'][]$options));
    $route_match = RouteMatch::createFromRequest($request);

    $output = $this->pageController->handle($route_match->getParameter('view_id')$route_match->getParameter('display_id')$route_match);
    $this->assertIsArray($output);
    $this->assertEquals($build$output);
  }

  /** * Tests the page controller with arguments on a non overridden page view. */
  public function testHandleWithArgumentsWithoutOverridden() {
    $request = new Request();
    
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;

if (PHP_SAPI !== 'cli') {
  return;
}

// Bootstrap. $autoloader = require __DIR__ . '/../../autoload.php';
$request = Request::createFromGlobals();
Settings::initialize(dirname(__DIR__, 2), DrupalKernel::findSitePath($request)$autoloader);
DrupalKernel::createFromRequest($request$autoloader, 'prod')->boot();

// Run the database dump command. $application = new GenerateProxyClassApplication(new ProxyBuilder());
$application->run();


  /** * Redirects users when access is denied. * * @param \Symfony\Component\HttpKernel\Event\ExceptionEvent $event * The event to process. */
  public function onException(ExceptionEvent $event) {
    $exception = $event->getThrowable();
    if ($exception instanceof AccessDeniedHttpException) {
      $route_name = RouteMatch::createFromRequest($event->getRequest())->getRouteName();
      $redirect_url = NULL;
      if ($this->account->isAuthenticated()) {
        switch ($route_name) {
          case 'user.login';
            // Redirect an authenticated user to the profile page.             $redirect_url = Url::fromRoute('entity.user.canonical', ['user' => $this->account->id()]['absolute' => TRUE]);
            break;

          case 'user.register';
            // Redirect an authenticated user to the profile form.             $redirect_url = Url::fromRoute('entity.user.edit_form', ['user' => $this->account->id()]['absolute' => TRUE]);
            
return new RouteMatch($name$route$parameters$raw_parameters);
  }

  /** * @covers ::createFromRequest * @covers ::__construct */
  public function testRouteMatchFromRequest() {
    $request = new Request();

    // A request that hasn't been routed yet.     $route_match = RouteMatch::createFromRequest($request);
    $this->assertNull($route_match->getRouteName());
    $this->assertNull($route_match->getRouteObject());
    $this->assertSame([]$route_match->getParameters()->all());
    $this->assertNull($route_match->getParameter('foo'));
    $this->assertSame([]$route_match->getRawParameters()->all());
    $this->assertNull($route_match->getRawParameter('foo'));

    // A routed request without parameter upcasting.     $route = new Route('/test-route/{foo}');
    $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'test_route');
    $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, $route);
    
protected static $modules = [
    'system',
  ];

  /** * Test that the negotiator applies to the batch route. */
  public function testApplies() {
    $request = Request::create('/batch');
    // Use the router to enhance the object so that a RouteMatch can be created.     $this->container->get('router')->matchRequest($request);
    $routeMatch = RouteMatch::createFromRequest($request);
    // The negotiator under test.     $negotiator = $this->container->get('theme.negotiator.system.batch');

    $this->assertTrue($negotiator->applies($routeMatch));
  }

}
Home | Imprint | This part of the site doesn't use cookies.