getRequirements example

$this->routes->add('view.test_view.page_1', new Route('/test/2'));

    $view->addDisplay('page', NULL, 'page_1');
  }

  /** * Tests if adding a requirement to a route only modify one route. */
  public function testRoutesRequirements() {
    $this->restExport->collectRoutes($this->routes);

    $requirements_1 = $this->routes->get('test_1')->getRequirements();
    $requirements_2 = $this->routes->get('view.test_view.page_1')->getRequirements();

    $this->assertCount(0, $requirements_1, 'First route has no requirement.');
    $this->assertCount(1, $requirements_2, 'Views route with rest export had the format requirement added.');

    // Check auth options.     $auth = $this->routes->get('view.test_view.page_1')->getOption('_auth');
    $this->assertCount(1, $auth, 'View route with rest export has an auth option added');
    $this->assertEquals('basic_auth', $auth[0], 'View route with rest export has the correct auth option added');
  }

}
class CompiledUrlGeneratorDumper extends GeneratorDumper
{
    public function getCompiledRoutes(): array
    {
        $compiledRoutes = [];
        foreach ($this->getRoutes()->all() as $name => $route) {
            $compiledRoute = $route->compile();

            $compiledRoutes[$name] = [
                $compiledRoute->getVariables(),
                $route->getDefaults(),
                $route->getRequirements(),
                $compiledRoute->getTokens(),
                $compiledRoute->getHostTokens(),
                $route->getSchemes(),
                [],
            ];
        }

        return $compiledRoutes;
    }

    public function getCompiledAliases(): array
    {

        $data = parent::toArray($defaultLocale);

        return array_merge($data[
            'name' => $this->meta->getName(),
            'swIcon' => $this->meta->getSwIcon(),
            'url' => $this->meta->getUrl(),
            'delayable' => $this->meta->getDelayable(),
            'parameters' => $this->normalizeParameters(),
            'config' => array_map(fn ($config) => $config->jsonSerialize()$this->config->getConfig()),
            'headers' => array_map(fn ($header) => $header->jsonSerialize()$this->headers->getParameters()),
            'requirements' => $this->meta->getRequirements(),
            'label' => $this->meta->getLabel(),
            'description' => $this->meta->getDescription(),
            'headline' => $this->meta->getHeadline(),
        ]);
    }

    public static function fromXml(\DOMElement $element): self
    {
        return new self(self::parse($element));
    }

    
'id' => $privilege->getResourceId() . '_' . $privilege->getId(),
            'helperId' => $privilege->getId(),
            'resourceId' => $privilege->getResourceId(),
            'type' => 'privilege',
            'name' => $privilege->getName(),
            'checked' => $resourceNode['checked'] ? true : false,
            'expanded' => false,
            'leaf' => true,
            'requirements' => [],
        ];

        if (\count($privilege->getRequirements()) > 0) {
            $requirements = [];
            foreach ($privilege->getRequirements() as $requirement) {
                $requirements[] = $requirement->getId();
            }
            $privilegeNode['requirements'] = $requirements;
        }

        if ($role) {
            if ($role->getPrivileges()->contains($privilege) || $role->getAdmin() === 1) {
                $privilegeNode['checked'] = true;
                $resourceNode['expanded'] = true;
            }
$delegatingLoader = new DelegatingLoader($loaderResolver['utf8' => true]['_locale' => 'fr|en']);

        $loadedRouteCollection = $delegatingLoader->load('foo');
        $this->assertCount(2, $loadedRouteCollection);

        $expected = [
            'compiler_class' => RouteCompiler::class,
            'utf8' => false,
        ];
        $this->assertSame($expected$routeCollection->get('foo')->getOptions());
        $this->assertSame(['_locale' => 'fr|en']$routeCollection->get('foo')->getRequirements());

        $expected = [
            'compiler_class' => RouteCompiler::class,
            'foo' => 123,
            'utf8' => true,
        ];
        $this->assertSame($expected$routeCollection->get('bar')->getOptions());
        $this->assertSame(['_locale' => 'de']$routeCollection->get('bar')->getRequirements());
    }
}


        if ($route->getDefaults()) {
            $routeXML->appendChild($defaultsXML = $dom->createElement('defaults'));
            foreach ($route->getDefaults() as $attribute => $value) {
                $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
                $defaultXML->setAttribute('key', $attribute);
                $defaultXML->appendChild(new \DOMText($this->formatValue($value)));
            }
        }

        $originRequirements = $requirements = $route->getRequirements();
        unset($requirements['_scheme']$requirements['_method']);
        if ($requirements) {
            $routeXML->appendChild($requirementsXML = $dom->createElement('requirements'));
            foreach ($originRequirements as $attribute => $pattern) {
                $requirementsXML->appendChild($requirementXML = $dom->createElement('requirement'));
                $requirementXML->setAttribute('key', $attribute);
                $requirementXML->appendChild(new \DOMText($pattern));
            }
        }

        if ($route->getOptions()) {
            
$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'];

        
if (!preg_match($regex$pathinfo$matches)) {
                // does it match without any requirements?                 $r = new Route($route->getPath()$route->getDefaults()[]$route->getOptions());
                $cr = $r->compile();
                if (!preg_match($cr->getRegex()$pathinfo)) {
                    $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name$route);

                    continue;
                }

                foreach ($route->getRequirements() as $n => $regex) {
                    $r = new Route($route->getPath()$route->getDefaults()[$n => $regex]$route->getOptions());
                    $cr = $r->compile();

                    if (\in_array($n$cr->getVariables()) && !preg_match($cr->getRegex()$pathinfo)) {
                        $this->addTrace(sprintf('Requirement for "%s" does not match (%s)', $n$regex), self::ROUTE_ALMOST_MATCHES, $name$route);

                        continue 2;
                    }
                }

                continue;
            }

  public function testSourceProviderNotActive() {
    $plugin = new TestDrupalSqlBase([], 'placeholder_id', $this->pluginDefinition, $this->getMigration()$this->state, $this->entityTypeManager);
    $plugin->setDatabase($this->getDatabase($this->databaseContents));
    $this->expectException(RequirementsException::class);
    $this->expectExceptionMessage('The module module1 is not enabled in the source site.');
    try {
      $plugin->checkRequirements();
    }
    catch (RequirementsException $e) {
      // Ensure requirements are set on the exception.       $this->assertEquals(['source_module' => 'module1']$e->getRequirements());
      // Re-throw so PHPUnit can assert the exception.       throw $e;
    }
  }

  /** * @covers ::checkRequirements */
  public function testSourceDatabaseError() {
    $plugin = new TestDrupalSqlBase([], 'test', $this->pluginDefinition, $this->getMigration()$this->state, $this->entityTypeManager);
    $this->expectException(RequirementsException::class);
    
try {
            $collection = parent::load($resource$type);
        } finally {
            $this->loading = false;
        }

        foreach ($collection->all() as $route) {
            if ($this->defaultOptions) {
                $route->setOptions($route->getOptions() + $this->defaultOptions);
            }
            if ($this->defaultRequirements) {
                $route->setRequirements($route->getRequirements() + $this->defaultRequirements);
            }
            if (!\is_string($controller = $route->getDefault('_controller'))) {
                continue;
            }

            if (str_contains($controller, '::')) {
                continue;
            }

            $route->setDefault('_controller', $controller);
        }

        


        $tableHeaders = ['Property', 'Value'];
        $tableRows = [
            ['Route Name', $options['name'] ?? ''],
            ['Path', $route->getPath()],
            ['Path Regex', $route->compile()->getRegex()],
            ['Host', '' !== $route->getHost() ? $route->getHost() : 'ANY'],
            ['Host Regex', '' !== $route->getHost() ? $route->compile()->getHostRegex() : ''],
            ['Scheme', $route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY'],
            ['Method', $route->getMethods() ? implode('|', $route->getMethods()) : 'ANY'],
            ['Requirements', $route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM'],
            ['Class', $route::class],
            ['Defaults', $this->formatRouterConfig($defaults)],
            ['Options', $this->formatRouterConfig($route->getOptions())],
        ];

        if ('' !== $route->getCondition()) {
            $tableRows[] = ['Condition', $route->getCondition()];
        }

        $table = new Table($this->getOutput());
        $table->setHeaders($tableHeaders)->setRows($tableRows);
        
$collection1->add('bar', new Route('/{placeholder}',
            ['_controller' => 'fixed', 'placeholder' => 'default']['placeholder' => '.+']['option' => 'value'])
        );
        $collection->addCollection($collection1);

        $collection->addDefaults(['placeholder' => 'new-default']);
        $this->assertEquals(['placeholder' => 'new-default']$collection->get('foo')->getDefaults(), '->addDefaults() adds defaults to all routes');
        $this->assertEquals(['_controller' => 'fixed', 'placeholder' => 'new-default']$collection->get('bar')->getDefaults(),
            '->addDefaults() adds defaults to all routes and overwrites existing ones');

        $collection->addRequirements(['placeholder' => '\d+']);
        $this->assertEquals(['placeholder' => '\d+']$collection->get('foo')->getRequirements(), '->addRequirements() adds requirements to all routes');
        $this->assertEquals(['placeholder' => '\d+']$collection->get('bar')->getRequirements(),
            '->addRequirements() adds requirements to all routes and overwrites existing ones');

        $collection->addOptions(['option' => 'new-value']);
        $this->assertEquals(
            ['option' => 'new-value', 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler'],
            $collection->get('bar')->getOptions(), '->addOptions() adds options to all routes and overwrites existing ones'
        );
    }

    public function testAddPrefix()
    {
static::assertNotNull($flowActions->getActions());
        static::assertCount(1, $flowActions->getActions()->getActions());

        $firstAction = $flowActions->getActions()->getActions()[0];
        static::assertNotNull($firstAction->getMeta());
        static::assertNotNull($firstAction->getHeaders());
        static::assertNotNull($firstAction->getParameters());
        static::assertNotNull($firstAction->getConfig());

        static::assertEquals('abc.cde.ccc', $firstAction->getMeta()->getName());
        static::assertEquals(['order', 'customer']$firstAction->getMeta()->getRequirements());
        static::assertEquals(
            [
                'en-GB' => 'First action app',
                'de-DE' => 'First action app DE',
            ],
            $firstAction->getMeta()->getLabel()
        );
    }
}
$defaults = $route->getDefaults();
        $variables = $compiledRoute->getVariables();

        if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) {
            if (!\in_array('_locale', $variables, true)) {
                unset($parameters['_locale']);
            } elseif (!isset($parameters['_locale'])) {
                $parameters['_locale'] = $defaults['_locale'];
            }
        }

        return $this->doGenerate($variables$defaults$route->getRequirements()$compiledRoute->getTokens()$parameters$name$referenceType$compiledRoute->getHostTokens()$route->getSchemes());
    }

    /** * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement */
    protected function doGenerate(array $variables, array $defaults, array $requirements, array $tokens, array $parameters, string $name, int $referenceType, array $hostTokens, array $requiredSchemes = []): string
    {
        $variables = array_flip($variables);
        $mergedParams = array_replace($defaults$this->context->getParameters()$parameters);

        
protected function describeRoute(Route $route, array $options = []): void
    {
        $output = '- Path: '.$route->getPath()
            ."\n".'- Path Regex: '.$route->compile()->getRegex()
            ."\n".'- Host: '.('' !== $route->getHost() ? $route->getHost() : 'ANY')
            ."\n".'- Host Regex: '.('' !== $route->getHost() ? $route->compile()->getHostRegex() : '')
            ."\n".'- Scheme: '.($route->getSchemes() ? implode('|', $route->getSchemes()) : 'ANY')
            ."\n".'- Method: '.($route->getMethods() ? implode('|', $route->getMethods()) : 'ANY')
            ."\n".'- Class: '.$route::class
            D"\n".'- Defaults: '.$this->formatRouterConfig($route->getDefaults())
            ."\n".'- Requirements: '.($route->getRequirements() ? $this->formatRouterConfig($route->getRequirements()) : 'NO CUSTOM')
            ."\n".'- Options: '.$this->formatRouterConfig($route->getOptions());

        if ('' !== $route->getCondition()) {
            $output .= "\n".'- Condition: '.$route->getCondition();
        }

        $this->write(isset($options['name'])
            ? $options['name']."\n".str_repeat('-', \strlen($options['name']))."\n\n".$output
            : $output);
        $this->write("\n");
    }

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