addDefaults example

public function testDefaultRequirementOfVariable()
    {
        $routes = $this->getRoutes('test', new Route('/{page}.{_format}'));
        $generator = $this->getGenerator($routes);

        $this->assertSame('/app.php/index.mobile.html', $generator->generate('test', ['page' => 'index', '_format' => 'mobile.html']));
    }

    public function testImportantVariable()
    {
        $routes = $this->getRoutes('test', (new Route('/{page}.{!_format}'))->addDefaults(['_format' => 'mobile.html']));
        $generator = $this->getGenerator($routes);

        $this->assertSame('/app.php/index.xml', $generator->generate('test', ['page' => 'index', '_format' => 'xml']));
        $this->assertSame('/app.php/index.mobile.html', $generator->generate('test', ['page' => 'index', '_format' => 'mobile.html']));
        $this->assertSame('/app.php/index.mobile.html', $generator->generate('test', ['page' => 'index']));
    }

    public function testImportantVariableWithNoDefault()
    {
        $this->expectException(MissingMandatoryParametersException::class);
        $this->expectExceptionMessage('Some mandatory parameters are missing ("_format") to generate a URL for route "test".');
        
// Require the JSON:API media type header on every route, except on file     // upload routes, where we require `application/octet-stream`.     $routes->addRequirements(['_content_type_format' => 'api_json']);
    $upload_routes->addRequirements(['_content_type_format' => 'bin']);

    $routes->addCollection($upload_routes);

    // Enable all available authentication providers.     $routes->addOptions(['_auth' => $this->providerIds]);

    // Flag every route as belonging to the JSON:API module.     $routes->addDefaults([static::JSON_API_ROUTE_FLAG_KEY => TRUE]);

    // All routes serve only the JSON:API media type.     $routes->addRequirements(['_format' => 'api_json']);

    return $routes;
  }

  /** * Gets applicable resource routes for a JSON:API resource type. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type for which to get the routes. * @param string $path_prefix * The root path prefix. * * @return \Symfony\Component\Routing\RouteCollection * A collection of routes for the given resource type. */
$defaults$requirements$options$condition$paths, /* $prefixes */, $hosts] = $this->parseConfigs($node$path);

        if (!$paths && '' === $node->getAttribute('path')) {
            throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must have a "path" attribute or <path> child nodes.', $path));
        }

        if ($paths && '' !== $node->getAttribute('path')) {
            throw new \InvalidArgumentException(sprintf('The <route> element in file "%s" must not have both a "path" attribute and <path> child nodes.', $path));
        }

        $routes = $this->createLocalizedRoute($collection$id$paths ?: $node->getAttribute('path'));
        $routes->addDefaults($defaults);
        $routes->addRequirements($requirements);
        $routes->addOptions($options);
        $routes->setSchemes($schemes);
        $routes->setMethods($methods);
        $routes->setCondition($condition);

        if (null !== $hosts) {
            $this->addHost($routes$hosts);
        }
    }

    
<?php
/** @var $loader \Symfony\Component\Routing\Loader\PhpFileLoader */
/** @var \Symfony\Component\Routing\RouteCollection $collection */
$collection = $loader->import('validpattern.php');
$collection->addDefaults([
    'foo' => 123,
]);
$collection->addRequirements([
    'foo' => '\d+',
]);
$collection->addOptions([
    'foo' => 'bar',
]);
$collection->setCondition('context.getMethod() == "POST"');
$collection->addPrefix('/prefix');

$route->setDefault('foo', 'bar');
        $this->assertEquals('bar', $route->getDefault('foo'), '->setDefault() sets a default value');

        $route->setDefault('foo2', 'bar2');
        $this->assertEquals('bar2', $route->getDefault('foo2'), '->getDefault() return the default value');
        $this->assertNull($route->getDefault('not_defined'), '->getDefault() return null if default value is not set');

        $route->setDefault('_controller', $closure = fn () => 'Hello');
        $this->assertEquals($closure$route->getDefault('_controller'), '->setDefault() sets a default value');

        $route->setDefaults(['foo' => 'foo']);
        $route->addDefaults(['bar' => 'bar']);
        $this->assertEquals($route$route->addDefaults([]), '->addDefaults() implements a fluent interface');
        $this->assertEquals(['foo' => 'foo', 'bar' => 'bar']$route->getDefaults(), '->addDefaults() keep previous defaults');
    }

    public function testRequirements()
    {
        $route = new Route('/{foo}');
        $route->setRequirements(['foo' => '\d+']);
        $this->assertEquals(['foo' => '\d+']$route->getRequirements(), '->setRequirements() sets the requirements');
        $this->assertEquals('\d+', $route->getRequirement('foo'), '->getRequirement() returns a requirement');
        $this->assertNull($route->getRequirement('bar'), '->getRequirement() returns null if a requirement is not defined');
        
public function testAddDefaultsAndRequirementsAndOptions()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/{placeholder}'));
        $collection1 = new RouteCollection();
        $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(
            [
if (isset($config['format'])) {
            $defaults['_format'] = $config['format'];
        }
        if (isset($config['utf8'])) {
            $options['utf8'] = $config['utf8'];
        }
        if (isset($config['stateless'])) {
            $defaults['_stateless'] = $config['stateless'];
        }

        $routes = $this->createLocalizedRoute($collection$name$config['path']);
        $routes->addDefaults($defaults);
        $routes->addRequirements($requirements);
        $routes->addOptions($options);
        $routes->setSchemes($config['schemes'] ?? []);
        $routes->setMethods($config['methods'] ?? []);
        $routes->setCondition($config['condition'] ?? null);

        if (isset($config['host'])) {
            $this->addHost($routes$config['host']);
        }
    }

    


      $route_names = [
        "entity.entity_view_display.{$entity_type_id}.default",
        "entity.entity_view_display.{$entity_type_id}.view_mode",
      ];
      foreach ($route_names as $route_name) {
        if (!$route = $collection->get($route_name)) {
          continue;
        }

        $route->addDefaults([
          'section_storage_type' => $this->getStorageType(),
          'section_storage' => '',
        ] + $defaults);
        $parameters['section_storage']['layout_builder_tempstore'] = TRUE;
        $parameters = NestedArray::mergeDeep($parameters$route->getOption('parameters') ?: []);
        $route->setOption('parameters', $parameters);
      }
    }
  }

  /** * Returns an array of relevant entity types. * * @return \Drupal\Core\Entity\EntityTypeInterface[] * An array of entity types. */

  protected function getLatestVersionRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('latest-version') && $entity_type->hasViewBuilderClass()) {
      $entity_type_id = $entity_type->id();
      $route = new Route($entity_type->getLinkTemplate('latest-version'));
      $route
        ->addDefaults([
          '_entity_view' => "{$entity_type_id}.full",
          '_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
        ])
        // If the entity type is a node, unpublished content will be visible         // if the user has the "view any unpublished content" permission.         ->setRequirement('_entity_access', "{$entity_type_id}.view")
        ->setRequirement('_content_moderation_latest_version', 'TRUE')
        ->setOption('_content_moderation_entity_type', $entity_type_id)
        ->setOption('parameters', [
          $entity_type_id => [
            'type' => 'entity:' . $entity_type_id,
            

    public function __construct(string $path, array $defaults = [], array $requirements = [], array $options = [], ?string $host = '', string|array $schemes = [], string|array $methods = [], ?string $condition = '')
    {
        $this->setPath($path);
        $this->addDefaults($defaults);
        $this->addRequirements($requirements);
        $this->setOptions($options);
        $this->setHost($host);
        $this->setSchemes($schemes);
        $this->setMethods($methods);
        $this->setCondition($condition);
    }

    public function __serialize(): array
    {
        return [
            

  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,
        ],
      ]);
  }

  protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('canonical') && $entity_type->hasViewBuilderClass()) {
      $entity_type_id = $entity_type->id();
      $route = new Route($entity_type->getLinkTemplate('canonical'));
      $route
        ->addDefaults([
          '_entity_view' => "{$entity_type_id}.full",
          '_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
        ])
        ->setRequirement('_entity_access', "{$entity_type_id}.view")
        ->setOption('parameters', [
          $entity_type_id => ['type' => 'entity:' . $entity_type_id],
        ]);

      // Entity types with serial IDs can specify this in their route       // requirements, improving the matching process.       if ($this->getEntityTypeIdKeyType($entity_type) === 'integer') {
        
if (isset($config['format'])) {
            $defaults['_format'] = $config['format'];
        }
        if (isset($config['utf8'])) {
            $options['utf8'] = $config['utf8'];
        }
        if (isset($config['stateless'])) {
            $defaults['_stateless'] = $config['stateless'];
        }

        $routes = $this->createLocalizedRoute($collection$name$config['path']);
        $routes->addDefaults($defaults);
        $routes->addRequirements($requirements);
        $routes->addOptions($options);
        $routes->setSchemes($config['schemes'] ?? []);
        $routes->setMethods($config['methods'] ?? []);
        $routes->setCondition($config['condition'] ?? null);

        if (isset($config['host'])) {
            $this->addHost($routes$config['host']);
        }
    }

    
/** * Provides routes for nodes. */
class NodeRouteProvider implements EntityRouteProviderInterface {

  /** * {@inheritdoc} */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $route_collection = new RouteCollection();
    $route = (new Route('/node/{node}'))
      ->addDefaults([
        '_controller' => '\Drupal\node\Controller\NodeViewController::view',
        '_title_callback' => '\Drupal\node\Controller\NodeViewController::title',
      ])
      ->setRequirement('node', '\d+')
      ->setRequirement('_entity_access', 'node.view');
    $route_collection->add('entity.node.canonical', $route);

    $route = (new Route('/node/{node}/delete'))
      ->addDefaults([
        '_entity_form' => 'node.delete',
        '_title' => 'Delete',
      ])

    public function __construct(string $path, array $defaults = [], array $requirements = [], array $options = [], ?string $host = '', string|array $schemes = [], string|array $methods = [], ?string $condition = '')
    {
        $this->setPath($path);
        $this->addDefaults($defaults);
        $this->addRequirements($requirements);
        $this->setOptions($options);
        $this->setHost($host);
        $this->setSchemes($schemes);
        $this->setMethods($methods);
        $this->setCondition($condition);
    }

    public function __serialize(): array
    {
        return [
            
Home | Imprint | This part of the site doesn't use cookies.