getRequirement example


  public function filter(RouteCollection $collection, Request $request) {
    // Generates a list of Symfony formats matching the acceptable MIME types.     // @todo replace by proper content negotiation library.     $acceptable_mime_types = $request->getAcceptableContentTypes();
    $acceptable_formats = array_filter(array_map([$request, 'getFormat']$acceptable_mime_types));
    $primary_format = $request->getRequestFormat();

    foreach ($collection as $name => $route) {
      // _format could be a |-delimited list of supported formats.       $supported_formats = array_filter(explode('|', $route->getRequirement('_format') ?? ''));

      if (empty($supported_formats)) {
        // No format restriction on the route, so it always matches. Move it to         // the end of the collection by re-adding it.         $collection->add($name$route);
      }
      elseif (in_array($primary_format$supported_formats)) {
        // Perfect match, which will get a higher priority by leaving the route         // on top of the list.       }
      // The route partially matches if it doesn't care about format, if it

  public function __construct(ModuleHandlerInterface $module_handler) {
    $this->moduleHandler = $module_handler;
  }

  /** * {@inheritdoc} */
  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection as $name => $route) {
      if ($route->hasRequirement('_module_dependencies')) {
        $modules = $route->getRequirement('_module_dependencies');

        $explode_and = $this->explodeString($modules, '+');
        if (count($explode_and) > 1) {
          foreach ($explode_and as $module) {
            // If any moduleExists() call returns FALSE, remove the route and             // move on to the next.             if (!$this->moduleHandler->moduleExists($module)) {
              $collection->remove($name);
              continue 2;
            }
          }
        }

  public function access(Route $route, AccountInterface $account) {
    // Requirements just allow strings, so this might be a comma separated list.     $rid_string = $route->getRequirement('_role');

    $explode_and = array_filter(array_map('trim', explode(',', $rid_string)));
    if (count($explode_and) > 1) {
      $diff = array_diff($explode_and$account->getRoles());
      if (empty($diff)) {
        return AccessResult::allowed()->addCacheContexts(['user.roles']);
      }
    }
    else {
      $explode_or = array_filter(array_map('trim', explode('+', $rid_string)));
      $intersection = array_intersect($explode_or$account->getRoles());
      
/** * Checks access to the route based on the _access parameter. * * @param \Symfony\Component\Routing\Route $route * The route to check against. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */
  public function access(Route $route) {
    if ($route->getRequirement('_access') === 'TRUE') {
      return AccessResult::allowed();
    }
    elseif ($route->getRequirement('_access') === 'FALSE') {
      return AccessResult::forbidden();
    }
    else {
      return AccessResult::neutral();
    }
  }

}
/** * Determines whether the given route is an HTML route. * * @param \Symfony\Component\Routing\Route $route * The route to analyze. * * @return bool * TRUE if HTML is a valid format for this route. */
  protected static function isHtmlRoute(Route $route) {
    // If a route has no explicit format, then HTML is valid.     $format = $route->hasRequirement('_format') ? explode('|', $route->getRequirement('_format')) : ['html'];
    return in_array('html', $format, TRUE);
  }

}
$field_storage_definition = $prophet->prophesize(FieldStorageDefinitionInterface::class);
    $field_storage_definition->getType()->willReturn('integer');
    $route->setRequirement('the_entity_type_id', '\d+');
    $data['add_form_bundle_entity_id_key_type_integer'] = [clone $route$entity_type6->reveal()$bundle_entity_type->reveal()$field_storage_definition->reveal()];

    $entity_type7 = static::getEntityType($entity_type6);
    $bundle_entity_type = $prophet->prophesize(ConfigEntityTypeInterface::class);
    $bundle_entity_type->entityClassImplements(FieldableEntityInterface::class)->willReturn(FALSE);
    $field_storage_definition = $prophet->prophesize(FieldStorageDefinitionInterface::class);
    $route
      // Unset the 'the_entity_type_id' requirement.       ->setRequirements(['_entity_create_access' => $route->getRequirement('_entity_create_access')])
      ->setOption('parameters', [
        'the_bundle_entity_type_id' => [
          'type' => 'entity:the_bundle_entity_type_id',
          'with_config_overrides' => TRUE,
        ],
      ]);
    $data['add_form_bundle_entity_id_key_type_integer'] = [clone $route$entity_type7->reveal()$bundle_entity_type->reveal()$field_storage_definition->reveal()];

    return $data;
  }

  
if ('' !== $host = $route->getHost()) {
            $result = self::compilePattern($route$host, true);

            $hostVariables = $result['variables'];
            $variables = $hostVariables;

            $hostTokens = $result['tokens'];
            $hostRegex = $result['regex'];
        }

        $locale = $route->getDefault('_locale');
        if (null !== $locale && null !== $route->getDefault('_canonical_route') && preg_quote($locale) === $route->getRequirement('_locale')) {
            $requirements = $route->getRequirements();
            unset($requirements['_locale']);
            $route->setRequirements($requirements);
            $route->setPath(str_replace('{_locale}', $locale$route->getPath()));
        }

        $path = $route->getPath();

        $result = self::compilePattern($route$path, false);

        $staticPrefix = $result['staticPrefix'];

        

  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account = NULL) {
    [$relationship_field_name$field_operation] = explode('.', $route->getRequirement(static::ROUTE_REQUIREMENT_KEY));
    assert(in_array($field_operation['view', 'edit'], TRUE));
    $entity_operation = $field_operation === 'view' ? 'view' : 'update';
    if ($resource_type = $route_match->getParameter(Routes::RESOURCE_TYPE_KEY)) {
      assert($resource_type instanceof ResourceType);
      $entity = $route_match->getParameter('entity');
      $internal_name = $resource_type->getInternalName($relationship_field_name);
      if ($entity instanceof FieldableEntityInterface && $entity->hasField($internal_name)) {
        $entity_access = $this->entityAccessChecker->checkEntityAccess($entity$entity_operation$account);
        $field_access = $entity->get($internal_name)->access($field_operation$account, TRUE);
        // Ensure that access is respected for different entity revisions.         $access_result = $entity_access->andIf($field_access);
        
$this->assertEquals('/here', $routes->get('action.en')->getPath());
        $this->assertEquals('/hier', $routes->get('action.nl')->getPath());
    }

    public function testLocalizedPathRoutes()
    {
        $routes = $this->loader->load($this->getNamespace().'\LocalizedActionPathController');
        $this->assertCount(2, $routes);
        $this->assertEquals('/path', $routes->get('action.en')->getPath());
        $this->assertEquals('/pad', $routes->get('action.nl')->getPath());

        $this->assertEquals('nl', $routes->get('action.nl')->getRequirement('_locale'));
        $this->assertEquals('en', $routes->get('action.en')->getRequirement('_locale'));
    }

    public function testLocalizedPathRoutesWithExplicitPathPropety()
    {
        $routes = $this->loader->load($this->getNamespace().'\ExplicitLocalizedActionPathController');
        $this->assertCount(2, $routes);
        $this->assertEquals('/path', $routes->get('action.en')->getPath());
        $this->assertEquals('/pad', $routes->get('action.nl')->getPath());
    }

    
/** * @covers \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider::getRoutes */
  public function testHtmlRoutes() {
    /** @var \Drupal\Core\Routing\RouteProviderInterface $route_provider */
    $route_provider = \Drupal::service('router.route_provider');

    $route = $route_provider->getRouteByName('entity.entity_test_mul.canonical');
    $this->assertEquals('entity_test_mul.full', $route->getDefault('_entity_view'));
    $this->assertEquals('\Drupal\Core\Entity\Controller\EntityController::title', $route->getDefault('_title_callback'));
    $this->assertEquals('entity_test_mul.view', $route->getRequirement('_entity_access'));
    $this->assertFalse($route->hasOption('_admin_route'));

    $route = $route_provider->getRouteByName('entity.entity_test_mul.edit_form');
    $this->assertEquals('entity_test_mul.default', $route->getDefault('_entity_form'));
    $this->assertEquals('\Drupal\Core\Entity\Controller\EntityController::editTitle', $route->getDefault('_title_callback'));
    $this->assertEquals('entity_test_mul.update', $route->getRequirement('_entity_access'));
    $this->assertFalse($route->hasOption('_admin_route'));

    $route = $route_provider->getRouteByName('entity.entity_test_mul.delete_form');
    $this->assertEquals('entity_test_mul.delete', $route->getDefault('_entity_form'));
    $this->assertEquals('\Drupal\Core\Entity\Controller\EntityController::deleteTitle', $route->getDefault('_title_callback'));
    

  public function getResponseFormat(RouteMatchInterface $route_match, Request $request) {
    $route = $route_match->getRouteObject();
    $acceptable_response_formats = $route->hasRequirement('_format') ? explode('|', $route->getRequirement('_format')) : [];
    $acceptable_request_formats = $route->hasRequirement('_content_type_format') ? explode('|', $route->getRequirement('_content_type_format')) : [];
    $acceptable_formats = $request->isMethodCacheable() ? $acceptable_response_formats : $acceptable_request_formats;

    $requested_format = $request->getRequestFormat();
    $content_type_format = $request->getContentTypeFormat();

    // If an acceptable response format is requested, then use that. Otherwise,     // including and particularly when the client forgot to specify a response     // format, then use heuristics to select the format that is most likely     // expected.     if (in_array($requested_format$acceptable_response_formats, TRUE)) {
      
$route = new Route('/test-path', []['_foo' => '1', '_bar' => '1']);
    $route2 = new Route('/test-path', []['_foo' => '1', '_bar' => '2']);
    $collection = new RouteCollection();
    $collection->add('test_route', $route);
    $collection->add('test_route2', $route2);

    $access_check->expects($this->exactly(2))
      ->method('applies')
      ->with($this->isInstanceOf('Symfony\Component\Routing\Route'))
      ->willReturnCallback(function DRoute $route) {
        return $route->getRequirement('_bar') == 2;
      });

    $this->checkProvider->setChecks($collection);
    $this->assertEmpty($route->getOption('_access_checks'));
    $this->assertEquals(['test_access']$route2->getOption('_access_checks'));
  }

  /** * Tests \Drupal\Core\Access\AccessManager::check(). */
  public function testCheck() {
    

  protected static function isGetAndHtmlRoute(Route $route) {
    $methods = $route->getMethods() ?: ['GET'];
    // If a route has no explicit format, then HTML is valid.     // @see \Drupal\Core\Routing\RequestFormatRouteFilter::getAvailableFormats()     $format = $route->hasRequirement('_format') ? explode('|', $route->getRequirement('_format')) : ['html'];
    return in_array('GET', $methods, TRUE) && in_array('html', $format, TRUE);
  }

}

  public function onRoutingAlterAddFormats(RouteBuildEvent $event) {
    $route_names = [
      'user.login_status.http',
      'user.login.http',
      'user.logout.http',
      'user.pass.http',
    ];
    $routes = $event->getRouteCollection();
    foreach ($route_names as $route_name) {
      if ($route = $routes->get($route_name)) {
        $formats = explode('|', $route->getRequirement('_format'));
        $formats = array_unique(array_merge($formats$this->serializerFormats));
        $route->setRequirement('_format', implode('|', $formats));
      }
    }
  }

}
// Do not include fields with         // - non-configurable field storages,         // - locked field storages,         // - field storages that should not be added via user interface,         // - field storages that already have a field in the bundle.         $field_type = $field_storage->getType();
        $access->addCacheableDependency($field_storage);
        if ($field_storage instanceof FieldStorageConfigInterface
          && !$field_storage->isLocked()
          && empty($field_types[$field_type]['no_ui'])
          && !in_array($bundle$field_storage->getBundles(), TRUE)) {
          $permission = $route->getRequirement('_field_ui_field_reuse_access');
          $access = $access->orIf(AccessResult::allowedIfHasPermission($account$permission));
        }
      }
      $access->addCacheableDependency($this->entityFieldManager);
    }
    return $access;
  }

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