RequestContext example


    private array $expressionLanguageProviders = [];

    private static ?array $cache = [];

    public function __construct(LoaderInterface $loader, mixed $resource, array $options = [], RequestContext $context = null, LoggerInterface $logger = null, string $defaultLocale = null)
    {
        $this->loader = $loader;
        $this->resource = $resource;
        $this->logger = $logger;
        $this->context = $context ?? new RequestContext();
        $this->setOptions($options);
        $this->defaultLocale = $defaultLocale;
    }

    /** * Sets options. * * Available options: * * * cache_dir: The cache directory (or null to disable caching) * * debug: Whether to enable debugging or not (false by default) * * generator_class: The name of a UrlGeneratorInterface implementation * * generator_dumper_class: The name of a GeneratorDumperInterface implementation * * matcher_class: The name of a UrlMatcherInterface implementation * * matcher_dumper_class: The name of a MatcherDumperInterface implementation * * resource_type: Type hint for the main resource (optional) * * strict_requirements: Configure strict requirement checking for generators * implementing ConfigurableRequirementsInterface (default is true) * * @return void * * @throws \InvalidArgumentException When unsupported option is provided */

    public function test()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo', [][][], '', []['POST']));
        $coll->add('bar', new Route('/bar/{id}', []['id' => '\d+']));
        $coll->add('bar1', new Route('/bar/{name}', []['id' => '\w+'][], '', []['POST']));
        $coll->add('bar2', new Route('/foo', [][][], 'baz'));
        $coll->add('bar3', new Route('/foo1', [][][], 'baz'));
        $coll->add('bar4', new Route('/foo2', [][][], 'baz', [][], 'context.getMethod() == "GET"'));

        $context = new RequestContext();
        $context->setHost('baz');

        $matcher = new TraceableUrlMatcher($coll$context);
        $traces = $matcher->getTraces('/babar');
        $this->assertSame([0, 0, 0, 0, 0, 0]$this->getLevels($traces));

        $traces = $matcher->getTraces('/foo');
        $this->assertSame([1, 0, 0, 2]$this->getLevels($traces));

        $traces = $matcher->getTraces('/bar/12');
        $this->assertSame([0, 2]$this->getLevels($traces));

        
'stdClass' => ['?foo%5Bbaz%5D=bar', 'foo', $stdClass],
            'stdClass in nested stdClass' => ['?foo%5Bnested%5D%5Bbaz%5D=bar', 'foo', $nestedStdClass],
            'non stringable object' => ['', 'foo', new NonStringableObject()],
            'non stringable object but has public property' => ['?foo%5Bfoo%5D=property', 'foo', new NonStringableObjectWithPublicProperty()],
        ];
    }

    public function testUrlWithExtraParametersFromGlobals()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $generator = $this->getGenerator($routes);
        $context = new RequestContext('/app.php');
        $context->setParameter('bar', 'bar');
        $generator->setContext($context);
        $url = $generator->generate('test', ['foo' => 'bar']);

        $this->assertEquals('/app.php/testing?foo=bar', $url);
    }

    public function testUrlWithGlobalParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
        $generator = $this->getGenerator($routes);
        
private ContainerInterface $container;
    private array $collectedParameters = [];
    private \Closure $paramFetcher;

    /** * @param mixed $resource The main resource to load */
    public function __construct(ContainerInterface $container, mixed $resource, array $options = [], RequestContext $context = null, ContainerInterface $parameters = null, LoggerInterface $logger = null, string $defaultLocale = null)
    {
        $this->container = $container;
        $this->resource = $resource;
        $this->context = $context ?? new RequestContext();
        $this->logger = $logger;
        $this->setOptions($options);

        if ($parameters) {
            $this->paramFetcher = $parameters->get(...);
        } elseif ($container instanceof SymfonyContainerInterface) {
            $this->paramFetcher = $container->getParameter(...);
        } else {
            throw new \LogicException(sprintf('You should either pass a "%s" instance or provide the $parameters argument of the "%s" method.', SymfonyContainerInterface::class, __METHOD__));
        }

        
protected function setUp(): void
    {
        $functionProvider = new ServiceLocator([
            'env' => fn () => fn (string $arg) => [
                'APP_ENV' => 'test',
                'PHP_VERSION' => '7.2',
            ][$arg] ?? null,
            'sum' => fn () => fn ($a$b) => $a + $b,
            'foo' => fn () => fn () => 'bar',
        ]);

        $this->context = new RequestContext();
        $this->context->setParameter('_functions', $functionProvider);

        $this->expressionLanguage = new ExpressionLanguage();
        $this->expressionLanguage->registerProvider(new ExpressionLanguageProvider($functionProvider));
    }

    /** * @dataProvider compileProvider */
    public function testCompile(string $expression, string $expected)
    {
        
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class RedirectableCompiledUrlMatcherTest extends TestCase
{
    public function testRedirectWhenNoSlash()
    {
        $routes = new RouteCollection();
        $routes->add('foo', new Route('/foo/'));

        $matcher = $this->getMatcher($routes$context = new RequestContext());

        $this->assertEquals([
                '_controller' => 'Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction',
                'path' => '/foo/',
                'permanent' => true,
                'scheme' => null,
                'httpPort' => $context->getHttpPort(),
                'httpsPort' => $context->getHttpsPort(),
                '_route' => 'foo',
            ],
            $matcher->match('/foo')
        );


    private function generateDumpedMatcher(RouteCollection $collection)
    {
        $dumper = new CompiledUrlMatcherDumper($collection);
        $code = $dumper->dump();

        file_put_contents($this->dumpPath, $code);
        $compiledRoutes = require $this->dumpPath;

        return $this->getMockBuilder(TestCompiledUrlMatcher::class)
            ->setConstructorArgs([$compiledRoutesnew RequestContext()])
            ->onlyMethods(['redirect'])
            ->getMock();
    }

    public function testGenerateDumperMatcherWithObject()
    {
        $this->expectException(\InvalidArgumentException::class);
        $this->expectExceptionMessage('Symfony\Component\Routing\Route cannot contain objects');
        $routeCollection = new RouteCollection();
        $routeCollection->add('_', new Route('/', [new \stdClass()]));
        $dumper = new CompiledUrlMatcherDumper($routeCollection);
        


    /** * @dataProvider getGenerateAbsoluteUrlRequestContextData */
    public function testGenerateAbsoluteUrlWithRequestContext($path$baseUrl$host$scheme$httpPort$httpsPort$expected)
    {
        if (!class_exists(RequestContext::class)) {
            $this->markTestSkipped('The Routing component is needed to run tests that depend on its request context.');
        }

        $requestContext = new RequestContext($baseUrl, 'GET', $host$scheme$httpPort$httpsPort$path);

        $helper = new UrlHelper(new RequestStack()$requestContext);

        $this->assertEquals($expected$helper->getAbsoluteUrl($path));
    }

    /** * @dataProvider getGenerateAbsoluteUrlRequestContextData */
    public function testGenerateAbsoluteUrlWithRequestContextAwareInterface($path$baseUrl$host$scheme$httpPort$httpsPort$expected)
    {
        
public function testSetTargetUrlWithInternalUrl() {
    $redirect_response = new TrustedRedirectResponse('/example');
    $redirect_response->setTargetUrl('/example2');

    $this->assertEquals('/example2', $redirect_response->getTargetUrl());
  }

  /** * @covers ::setTargetUrl */
  public function testSetTargetUrlWithUntrustedUrl() {
    $request_context = new RequestContext();
    $request_context->setCompleteBaseUrl('https://www.drupal.org');
    $container = new ContainerBuilder();
    $container->set('router.request_context', $request_context);
    \Drupal::setContainer($container);

    $redirect_response = new TrustedRedirectResponse('/example');

    $this->expectException(\InvalidArgumentException::class);
    $redirect_response->setTargetUrl('http://evil-url.com/example');
  }

  
$expiresAt = new \DateTimeImmutable('@'.$expires);

        $parameters = [
            'user' => $user->getUserIdentifier(),
            'expires' => $expires,
            'hash' => $this->signatureHasher->computeSignatureHash($user$expires),
        ];

        if ($request) {
            $currentRequestContext = $this->urlGenerator->getContext();
            $this->urlGenerator->setContext(
                (new RequestContext())
                    ->fromRequest($request)
                    ->setParameter('_locale', $request->getLocale())
            );
        }

        try {
            $url = $this->urlGenerator->generate(
                $this->options['route_name'],
                $parameters,
                UrlGeneratorInterface::ABSOLUTE_URL
            );
        }
                    && abs(time() + 600 - $parameters['expires']) <= 1
                    // make sure hash is what we expect                     && $parameters['hash'] === $this->createSignatureHash('weaverryan', $parameters['expires']$extraProperties)
                ),
                UrlGeneratorInterface::ABSOLUTE_URL
            )
            ->willReturn('https://example.com/login/verify?user=weaverryan&hash=abchash&expires=1601235000');

        if ($request) {
            $this->router->expects($this->once())
                ->method('getContext')
                ->willReturn($currentRequestContext = new RequestContext());

            $series = [
                $this->equalTo((new RequestContext())->fromRequest($request)->setParameter('_locale', $request->getLocale())),
                $currentRequestContext,
            ];

            $this->router->expects($this->exactly(2))
                ->method('setContext')
                ->willReturnCallback(function DRequestContext $context) use (&$series) {
                    $expectedContext = array_shift($series);

                    
      // empty string.       '',
      // If no request was even pushed onto the request stack, and hence.       FALSE,
    ];
    foreach ($methods as $method) {
      if ($method === FALSE) {
        $request_stack = $this->container->get('request_stack');
        while ($request_stack->getCurrentRequest()) {
          $request_stack->pop();
        }
        $this->container->set('router.request_context', new RequestContext());
      }

      $requestContext->setMethod($method);
      /** @var \Drupal\Core\Url $url */
      $url = $pathValidator->getUrlIfValidWithoutAccessCheck($entity->toUrl()->toString(TRUE)->getGeneratedUrl());
      $this->assertEquals($method$requestContext->getMethod());
      $this->assertInstanceOf(Url::class$url);
      $this->assertSame(['entity_test' => $entity->id()]$url->getRouteParameters());
    }
  }

}
$this->assertSame('fr', $switcher->getLocale());
            $this->assertSame('fr', $locale);
        });

        $this->assertSame('en', \Locale::getDefault());
        $this->assertSame('en', $service->getLocale());
        $this->assertSame('en', $switcher->getLocale());
    }

    public function testWithRequestContext()
    {
        $context = new RequestContext();
        $service = new LocaleSwitcher('en', []$context);

        $this->assertSame('en', $service->getLocale());

        $service->setLocale('fr');

        $this->assertSame('fr', $service->getLocale());
        $this->assertSame('fr', $context->getParameter('_locale'));

        $service->reset();

        
unlink($this->testTmpFilepath);
    }

    public function testDumpWithRoutes()
    {
        $this->routeCollection->add('Test', new Route('/testing/{foo}'));
        $this->routeCollection->add('Test2', new Route('/testing2'));

        file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump());

        $projectUrlGenerator = new CompiledUrlGenerator(require $this->testTmpFilepath, new RequestContext('/app.php'));

        $absoluteUrlWithParameter = $projectUrlGenerator->generate('Test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL);
        $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', [], UrlGeneratorInterface::ABSOLUTE_URL);
        $relativeUrlWithParameter = $projectUrlGenerator->generate('Test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_PATH);
        $relativeUrlWithoutParameter = $projectUrlGenerator->generate('Test2', [], UrlGeneratorInterface::ABSOLUTE_PATH);

        $this->assertEquals('http://localhost/app.php/testing/bar', $absoluteUrlWithParameter);
        $this->assertEquals('http://localhost/app.php/testing2', $absoluteUrlWithoutParameter);
        $this->assertEquals('/app.php/testing/bar', $relativeUrlWithParameter);
        $this->assertEquals('/app.php/testing2', $relativeUrlWithoutParameter);
    }

    
use Symfony\Component\Routing\Matcher\CompiledUrlMatcher;
use Symfony\Component\Routing\Matcher\Dumper\CompiledUrlMatcherDumper;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;

class CompiledUrlMatcherTest extends UrlMatcherTest
{
    protected function getUrlMatcher(RouteCollection $routes, RequestContext $context = null)
    {
        $dumper = new CompiledUrlMatcherDumper($routes);

        return new CompiledUrlMatcher($dumper->getCompiledRoutes()$context ?? new RequestContext());
    }
}
Home | Imprint | This part of the site doesn't use cookies.