setRequirement example



    $routes = new RouteCollection();

    // Collection route like `/jsonapi/node/article`.     if ($resource_type->isLocatable()) {
      $collection_route = new Route("/{$resource_type->getPath()}");
      $collection_route->addDefaults([RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_SERVICE_NAME . ':getCollection']);
      $collection_route->setMethods(['GET']);
      // Allow anybody access because "view" and "view label" access are checked       // in the controller.       $collection_route->setRequirement('_access', 'TRUE');
      $routes->add(static::getRouteName($resource_type, 'collection')$collection_route);
    }

    // Creation route.     if ($resource_type->isMutable()) {
      $collection_create_route = new Route("/{$resource_type->getPath()}");
      $collection_create_route->addDefaults([RouteObjectInterface::CONTROLLER_NAME => static::CONTROLLER_SERVICE_NAME . ':createIndividual']);
      $collection_create_route->setMethods(['POST']);
      $create_requirement = sprintf("%s:%s", $resource_type->getEntityTypeId()$resource_type->getBundle());
      $collection_create_route->setRequirement('_entity_create_access', $create_requirement);
      $collection_create_route->setRequirement('_csrf_request_header_token', 'TRUE');
      
$discount,
                $promotion,
                $currencyId,
                $currencyFactor
            )
        );

        // add our lazy-validation rules.         // this is required within the recalculation process.         // if the requirements are not met, the calculation process         // will remove our discount line item.         $promotionItem->setRequirement($promotion->getPreconditionRule());

        return $promotionItem;
    }

    /** * in case of a delivery discount we add a 0.0 lineItem just to show customers and * shop owners, that delivery costs have been discounted by a promotion discount * if promotion is a auto promotion (no code) it may not be removed from cart * * @throws CartException */
    
      $route->setMethods(['GET']);

      $formats = $style_plugin->getFormats();

      // If there are no configured formats, add all formats that serialization       // is known to support.       if (!$formats) {
        $formats = $this->getFormatOptions();
      }

      // Format as a string using pipes as a delimiter.       $route->setRequirement('_format', implode('|', $formats));

      // Add authentication to the route if it was set. If no authentication was       // set, the default authentication will be used, which is cookie based by       // default.       $auth = $this->getOption('auth');
      if (!empty($auth)) {
        $route->setOption('_auth', $auth);
      }
    }
  }

  
->method('getCacheMaxAge')
      ->willReturn(Cache::PERMANENT);
    $entity->expects($this->once())
      ->method('getCacheTags')
      ->willReturn(['node:1337']);
    $entity->expects($this->once())
      ->method('getCacheContexts')
      ->willReturn([]);

    // Set the route requirements.     $route = new Route('test_route');
    $route->setRequirement('_access_content_translation_manage', 'create');

    // Set up the route match.     $route_match = $this->createMock('Drupal\Core\Routing\RouteMatchInterface');
    $route_match->expects($this->once())
      ->method('getParameter')
      ->with('node')
      ->willReturn($entity);

    // Set the mock account.     $account = $this->createMock('Drupal\Core\Session\AccountInterface');

    

  protected function getAddPageRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('add-page') && $entity_type->getKey('bundle')) {
      $route = new Route($entity_type->getLinkTemplate('add-page'));
      $route->setDefault('_controller', EntityController::class D '::addPage');
      $route->setDefault('_title_callback', EntityController::class D '::addTitle');
      $route->setDefault('entity_type_id', $entity_type->id());
      $route->setRequirement('_entity_create_any_access', $entity_type->id());

      return $route;
    }
  }

  /** * Gets the add-form route. * * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type * The entity type. * * @return \Symfony\Component\Routing\Route|null * The generated route, if available. */

                    break;
                }
            }
        }

        foreach ($paths as $locale => $path) {
            $route = $this->createRoute($path$defaults$requirements$options$host$schemes$methods$condition);
            $this->configureRoute($route$class$method$annot);
            if (0 !== $locale) {
                $route->setDefault('_locale', $locale);
                $route->setRequirement('_locale', preg_quote($locale));
                $route->setDefault('_canonical_route', $name);
                $collection->add($name.'.'.$locale$route$priority);
            } else {
                $collection->add($name$route$priority);
            }
        }
    }

    public function supports(mixed $resource, string $type = null): bool
    {
        return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || \in_array($type['annotation', 'attribute'], true));
    }

                    break;
                }
            }
        }

        foreach ($paths as $locale => $path) {
            $route = $this->createRoute($path$defaults$requirements$options$host$schemes$methods$condition);
            $this->configureRoute($route$class$method$annot);
            if (0 !== $locale) {
                $route->setDefault('_locale', $locale);
                $route->setRequirement('_locale', preg_quote($locale));
                $route->setDefault('_canonical_route', $name);
                $collection->add($name.'.'.$locale$route$priority);
            } else {
                $collection->add($name$route$priority);
            }
        }
    }

    public function supports(mixed $resource, string $type = null): bool
    {
        return \is_string($resource) && preg_match('/^(?:\\\\?[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)+$/', $resource) && (!$type || \in_array($type['annotation', 'attribute'], true));
    }
$data['admin in part of a word not at the start of the path'] = [
      new Route('/foo/administration/bar'),
      NULL,
    ];
    $data['admin option'] = [
      (new Route('/foo'))
        ->setOption('_admin_route', TRUE),
      TRUE,
    ];
    $data['admin prefix, non-HTML format'] = [
      (new Route('/admin/foo'))
        ->setRequirement('_format', 'json'),
      NULL,
    ];
    $data['admin option, non-HTML format'] = [
      (new Route('/foo'))
        ->setRequirement('_format', 'json')
        ->setOption('_admin_route', TRUE),
      TRUE,
    ];
    $data['admin prefix, HTML format'] = [
      (new Route('/admin/foo'))
        ->setRequirement('_format', 'html'),
      
private function extractInlineDefaultsAndRequirements(string $pattern): string
    {
        if (false === strpbrk($pattern, '?<')) {
            return $pattern;
        }

        return preg_replace_callback('#\{(!?)([\w\x80-\xFF]++)(<.*?>)?(\?[^\}]*+)?\}#', function D$m) {
            if (isset($m[4][0])) {
                $this->setDefault($m[2], '?' !== $m[4] ? substr($m[4], 1) : null);
            }
            if (isset($m[3][0])) {
                $this->setRequirement($m[2]substr($m[3], 1, -1));
            }

            return '{'.$m[1].$m[2].'}';
        }$pattern);
    }

    private function sanitizeRequirement(string $key, string $regex): string
    {
        if ('' !== $regex) {
            if ('^' === $regex[0]) {
                $regex = substr($regex, 1);
            }
$request = new Request();
    $request->setRequestFormat($request_format);
    $collection = $route_filter->filter($collection$request);

    $this->assertSameSize($expected_filtered_collection$collection);
    $this->assertSame($expected_filtered_collectionarray_keys($collection->all()));
  }

  public function filterProvider() {
    $route_without_format = new Route('/test');
    $route_with_format = new Route('/test');
    $route_with_format->setRequirement('_format', 'json');
    $route_with_multiple_formats = new Route('/test');
    $route_with_multiple_formats->setRequirement('_format', 'json|xml');

    $collection = new RouteCollection();
    $collection->add('test_0', $route_without_format);
    $collection->add('test_1', $route_with_format);
    $collection->add('test_2', $route_with_multiple_formats);

    $sole_route_match_single_format = new RouteCollection();
    $sole_route_match_single_format->add('sole_route_single_format', $route_with_format);

    
protected function getVersionHistoryRoute(EntityTypeInterface $entityType): ?Route {
    if (!$entityType->hasLinkTemplate('version-history')) {
      return NULL;
    }

    $entityTypeId = $entityType->id();
    return (new Route($entityType->getLinkTemplate('version-history')))
      ->addDefaults([
        '_controller' => VersionHistoryController::class,
        '_title' => 'Revisions',
      ])
      ->setRequirement('_entity_access', $entityTypeId . '.view all revisions')
      ->setOption('entity_type_id', $entityTypeId)
      ->setOption('_admin_route', TRUE)
      ->setOption('parameters', [
        $entityTypeId => [
          'type' => 'entity:' . $entityTypeId,
        ],
      ]);
  }

  /** * Gets the entity revision view route. * * @param \Drupal\Core\Entity\EntityTypeInterface $entityType * The entity type. * * @return \Symfony\Component\Routing\Route|null * The entity revision view route, or NULL if the entity type does not * support viewing revisions. */

        if (\is_array($prefix)) {
            foreach ($prefix as $locale => $localePrefix) {
                $prefix[$locale] = trim(trim($localePrefix), '/');
            }
            foreach ($routes->all() as $name => $route) {
                if (null === $locale = $route->getDefault('_locale')) {
                    $routes->remove($name);
                    foreach ($prefix as $locale => $localePrefix) {
                        $localizedRoute = clone $route;
                        $localizedRoute->setDefault('_locale', $locale);
                        $localizedRoute->setRequirement('_locale', preg_quote($locale));
                        $localizedRoute->setDefault('_canonical_route', $name);
                        $localizedRoute->setPath($localePrefix.(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
                        $routes->add($name.'.'.$locale$localizedRoute);
                    }
                } elseif (!isset($prefix[$locale])) {
                    throw new \InvalidArgumentException(sprintf('Route "%s" with locale "%s" is missing a corresponding prefix in its parent collection.', $name$locale));
                } else {
                    $route->setPath($prefix[$locale].(!$trailingSlashOnRoot && '/' === $route->getPath() ? '' : $route->getPath()));
                    $routes->add($name$route);
                }
            }

            
protected function getRoutesForResourceConfig(RestResourceConfigInterface $rest_resource_config) {
    $plugin = $rest_resource_config->getResourcePlugin();
    $collection = new RouteCollection();

    foreach ($plugin->routes() as $name => $route) {
      /** @var \Symfony\Component\Routing\Route $route */
      // @todo: Are multiple methods possible here?       $methods = $route->getMethods();
      // Only expose routes that have an explicit method and allow >=1 format       // for that method.       if (($methods && ($method = $methods[0]) && $rest_resource_config->getFormats($method))) {
        $route->setRequirement('_csrf_request_header_token', 'TRUE');

        // Check that authentication providers are defined.         if (empty($rest_resource_config->getAuthenticationProviders($method))) {
          $this->logger->error('At least one authentication provider must be defined for resource @id', ['@id' => $rest_resource_config->id()]);
          continue;
        }

        // Check that formats are defined.         if (empty($rest_resource_config->getFormats($method))) {
          $this->logger->error('At least one format must be defined for resource @id', ['@id' => $rest_resource_config->id()]);
          continue;
        }
$this->assertSame('AppBundle:Baz:view', $route->getDefault('_controller'));
    }

    public function testRoutingI18nConfigurator()
    {
        $locator = new FileLocator([__DIR__.'/../Fixtures']);
        $loader = new PhpFileLoader($locator);
        $routeCollection = $loader->load('php_dsl_i18n.php');

        $expectedCollection = new RouteCollection();

        $expectedCollection->add('foo.en', (new Route('/glish/foo'))->setDefaults(['_locale' => 'en', '_canonical_route' => 'foo'])->setRequirement('_locale', 'en'));
        $expectedCollection->add('bar.en', (new Route('/glish/bar'))->setDefaults(['_locale' => 'en', '_canonical_route' => 'bar'])->setRequirement('_locale', 'en'));
        $expectedCollection->add('baz.en', (new Route('/baz'))->setDefaults(['_locale' => 'en', '_canonical_route' => 'baz'])->setRequirement('_locale', 'en'));
        $expectedCollection->add('c_foo.fr', (new Route('/ench/pub/foo'))->setDefaults(['_locale' => 'fr', '_canonical_route' => 'c_foo'])->setRequirement('_locale', 'fr'));
        $expectedCollection->add('c_bar.fr', (new Route('/ench/pub/bar'))->setDefaults(['_locale' => 'fr', '_canonical_route' => 'c_bar'])->setRequirement('_locale', 'fr'));
        $expectedCollection->add('non_localized.fr', (new Route('/ench/non-localized'))->setDefaults(['_locale' => 'fr', '_canonical_route' => 'non_localized'])->setRequirement('_locale', 'fr'));

        $expectedCollection->addResource(new FileResource(realpath(__DIR__.'/../Fixtures/php_dsl_sub_i18n.php')));
        $expectedCollection->addResource(new FileResource(realpath(__DIR__.'/../Fixtures/php_dsl_i18n.php')));

        $this->assertEquals($expectedCollection$routeCollection);
    }

    

  public function access(AccountInterface $account) {
    return !empty(array_intersect(array_filter($this->options['role'])$account->getRoles()));
  }

  /** * {@inheritdoc} */
  public function alterRouteDefinition(Route $route) {
    if ($this->options['role']) {
      $route->setRequirement('_role', (string) implode('+', $this->options['role']));
    }
  }

  public function summaryTitle() {
    $count = count($this->options['role']);
    if ($count < 1) {
      return $this->t('No role(s) selected');
    }
    elseif ($count > 1) {
      return $this->t('Multiple roles');
    }
    
Home | Imprint | This part of the site doesn't use cookies.