setMethods example

/** * Sets the HTTP methods (e.g. 'POST') all child routes are restricted to. * * @param string|string[] $methods The method or an array of methods * * @return void */
    public function setMethods(string|array $methods)
    {
        foreach ($this->routes as $route) {
            $route->setMethods($methods);
        }
    }

    /** * Returns an array of resources loaded to build this collection. * * @return ResourceInterface[] */
    public function getResources(): array
    {
        return array_values($this->resources);
    }
$expectedCollection->add('c_pub_buz', (new Route('/sub/pub/buz'))
            ->setHost('host')
            ->setRequirements(['id' => '\d+'])
        );
        $expectedCollection->add('z_c_root', new Route('/zub/pub/'));
        $expectedCollection->add('z_c_bar', new Route('/zub/pub/bar'));
        $expectedCollection->add('z_c_pub_buz', (new Route('/zub/pub/buz'))->setHost('host'));
        $expectedCollection->add('r_root', new Route('/bus'));
        $expectedCollection->add('r_bar', new Route('/bus/bar/'));
        $expectedCollection->add('ouf', (new Route('/ouf'))
            ->setSchemes(['https'])
            ->setMethods(['GET'])
            ->setDefaults(['id' => 0])
        );

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

        $expectedCollectionClosure = $expectedCollection;
        $expectedCollectionObject = clone $expectedCollection;

        $expectedCollectionClosure->addResource(new FileResource(realpath(__DIR__.'/../Fixtures/php_dsl.php')));
        $expectedCollectionObject->addResource(new FileResource(realpath(__DIR__.'/../Fixtures/php_object_dsl.php')));

        

  public function collectRoutes(RouteCollection $collection) {
    parent::collectRoutes($collection);
    $view_id = $this->view->storage->id();
    $display_id = $this->display['id'];

    if ($route = $collection->get("view.$view_id.$display_id")) {
      $style_plugin = $this->getPlugin('style');

      // REST exports should only respond to GET methods.       $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));

      

  public function testRunTestsError() {
    $test_id = 23;
    $log_path = 'test_log_path';

    // Create a mock test run storage.     $storage = $this->getMockBuilder(SimpletestTestRunResultsStorage::class)
      ->disableOriginalConstructor()
      ->setMethods(['createNew'])
      ->getMock();

    // Set some expectations for createNew().     $storage->expects($this->once())
      ->method('createNew')
      ->willReturn($test_id);

    // Create a mock runner.     $runner = $this->getMockBuilder(PhpUnitTestRunner::class)
      ->disableOriginalConstructor()
      ->onlyMethods(['xmlLogFilepath', 'runCommand'])
      
$this->expectExceptionMessage('No routes found for "/".');
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/', [][][], null, ['https']['POST']));

        $matcher = $this->getUrlMatcher($coll);
        $matcher->match('/');
    }

    public function testSiblingRoutes()
    {
        $coll = new RouteCollection();
        $coll->add('a', (new Route('/a{a}'))->setMethods('POST'));
        $coll->add('b', (new Route('/a{a}'))->setMethods('PUT'));
        $coll->add('c', new Route('/a{a}'));
        $coll->add('d', (new Route('/b{a}'))->setCondition('false'));
        $coll->add('e', (new Route('/{b}{a}'))->setCondition('false'));
        $coll->add('f', (new Route('/{b}{a}'))->setRequirements(['b' => 'b']));

        $matcher = $this->getUrlMatcher($coll);
        $this->assertEquals(['_route' => 'c', 'a' => 'a']$matcher->match('/aa'));
        $this->assertEquals(['_route' => 'f', 'b' => 'b', 'a' => 'a']$matcher->match('/ba'));
    }

    
// Internal resources have no routes.     if ($resource_type->isInternal()) {
      return new RouteCollection();
    }

    $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']);
      
/** * Sets the HTTP methods (e.g. 'POST') all child routes are restricted to. * * @param string|string[] $methods The method or an array of methods * * @return void */
    public function setMethods(string|array $methods)
    {
        foreach ($this->routes as $route) {
            $route->setMethods($methods);
        }
    }

    /** * Returns an array of resources loaded to build this collection. * * @return ResourceInterface[] */
    public function getResources(): array
    {
        return array_values($this->resources);
    }
/** * Sets the HTTP methods (e.g. 'POST') this route is restricted to. * So an empty array means that any method is allowed. * * @param string[] $methods * * @return $this */
    final public function methods(array $methods)static
    {
        $this->route->setMethods($methods);

        return $this;
    }

    /** * Adds the "_controller" entry to defaults. * * @param callable|string|array $controller a callable or parseable pseudo-callable * * @return $this */
    
        $listSuffix = '(\/[0-9a-f]{32}\/(extensions\/)?[a-zA-Z-]+)*\/?$';

        $elements = $this->definitionRegistry->getDefinitions();
        usort($elementsfn (EntityDefinition $a, EntityDefinition $b) => $a->getEntityName() <=> $b->getEntityName());

        foreach ($elements as $definition) {
            $entityName = $definition->getEntityName();
            $resourceName = str_replace('_', '-', $definition->getEntityName());

            // detail routes             $route = new Route('/api/' . $resourceName . '/{path}');
            $route->setMethods(['GET']);
            $route->setDefault('_controller', $class . '::detail');
            $route->setDefault('entityName', $resourceName);
            $route->setDefault(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, ['api']);
            $route->addRequirements(['path' => $detailSuffix, 'version' => '\d+']);
            $routes->add('api.' . $entityName . '.detail', $route);

            $route = new Route('/api/' . $resourceName . '/{path}');
            $route->setMethods(['PATCH']);
            $route->setDefault('_controller', $class . '::update');
            $route->setDefault('entityName', $resourceName);
            $route->setDefault(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, ['api']);
            
$this->assertFalse($route->hasDefault('view_id'));
    $this->assertFalse($route->hasDefault('display_id'));
    $this->assertSame($collection->get('test_route_2')$route_2);
  }

  /** * Tests the altering of a REST route. */
  public function testAlterPostRestRoute() {
    $collection = new RouteCollection();
    $route = new Route('test_route', ['_controller' => 'Drupal\Tests\Core\Controller\TestController::content']);
    $route->setMethods(['POST']);
    $collection->add('test_route', $route);

    [$view] = $this->setupViewExecutableAccessPlugin();

    $display = [];
    $display['display_plugin'] = 'page';
    $display['id'] = 'page_1';
    $display['display_options'] = [
      'path' => 'test_route',
    ];
    $this->pathPlugin->initDisplay($view$display);

    
$schemes = [];
            foreach ($route->getSchemes() as $scheme) {
                $schemes[] = explode('|', $this->resolve($scheme));
            }
            $route->setSchemes(array_merge([], ...$schemes));

            $methods = [];
            foreach ($route->getMethods() as $method) {
                $methods[] = explode('|', $this->resolve($method));
            }
            $route->setMethods(array_merge([], ...$methods));
            $route->setCondition($this->resolve($route->getCondition()));
        }
    }

    /** * Recursively replaces %placeholders% with the service container parameters. * * @throws ParameterNotFoundException When a placeholder does not exist as a container parameter * @throws RuntimeException When a container value is not a string or a numeric value */
    private function resolve(mixed $value): mixed
    {
if ($route_name === '<current>') {
      if ($current_route = $this->routeMatch->getRouteObject()) {
        $requirements = $current_route->getRequirements();
        // Setting _method and _schema is deprecated since 2.7. Using         // setMethods() and setSchemes() are now the recommended ways.         unset($requirements['_method']);
        unset($requirements['_schema']);
        $route->setRequirements($requirements);

        $route->setPath($current_route->getPath());
        $route->setSchemes($current_route->getSchemes());
        $route->setMethods($current_route->getMethods());
        $route->setOptions($current_route->getOptions());
        $route->setDefaults($current_route->getDefaults());
        $parameters = array_merge($parameters$this->routeMatch->getRawParameters()->all());
        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheContexts(['route']);
        }
      }
      else {
        // If we have no current route match available, point to the frontpage.         $route->setPath('/');
      }
    }

            ['quoter' => '[\']+']
        ));
        // space in pattern         $collection->add('space', new Route(
            '/spa ce'
        ));

        // prefixes         $collection1 = new RouteCollection();
        $collection1->add('overridden', new Route('/overridden1'));
        $collection1->add('foo1', (new Route('/{foo}'))->setMethods('PUT'));
        $collection1->add('bar1', new Route('/{bar}'));
        $collection1->addPrefix('/b\'b');
        $collection2 = new RouteCollection();
        $collection2->addCollection($collection1);
        $collection2->add('overridden', new Route('/{var}', []['var' => '.*']));
        $collection1 = new RouteCollection();
        $collection1->add('foo2', new Route('/{foo1}'));
        $collection1->add('bar2', new Route('/{bar1}'));
        $collection1->addPrefix('/b\'b');
        $collection2->addCollection($collection1);
        $collection2->addPrefix('/a');
        
$this->assertFalse($route->hasScheme('httpS'));
        $route->setSchemes(['HttpS', 'hTTp']);
        $this->assertEquals(['https', 'http']$route->getSchemes(), '->setSchemes() accepts an array of schemes and lowercases them');
        $this->assertTrue($route->hasScheme('htTp'));
        $this->assertTrue($route->hasScheme('httpS'));
    }

    public function testMethod()
    {
        $route = new Route('/');
        $this->assertEquals([]$route->getMethods(), 'methods is initialized with []');
        $route->setMethods('gEt');
        $this->assertEquals(['GET']$route->getMethods(), '->setMethods() accepts a single method string and uppercases it');
        $route->setMethods(['gEt', 'PosT']);
        $this->assertEquals(['GET', 'POST']$route->getMethods(), '->setMethods() accepts an array of methods and uppercases them');
    }

    public function testCondition()
    {
        $route = new Route('/');
        $this->assertSame('', $route->getCondition());
        $route->setCondition('context.getMethod() == "GET"');
        $this->assertSame('context.getMethod() == "GET"', $route->getCondition());
    }

    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 [
            'path' => $this->path,
            'host' => $this->host,
            'defaults' => $this->defaults,
            'requirements' => $this->requirements,
            'options' => $this->options,
            
Home | Imprint | This part of the site doesn't use cookies.