getPathInfo example

class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  /** * Redirects paths containing successive slashes to those with single slashes. * * @param \Symfony\Component\HttpKernel\Event\RequestEvent $event * The RequestEvent to process. */
  public function redirect(RequestEvent $event) {
    $request = $event->getRequest();
    // Get the requested path minus the base path.     $path = $request->getPathInfo();

    // It is impossible to create a link or a route to a path starting with     // multiple leading slashes. However if a form is added to the 404 page that     // submits back to the same URI this presents an open redirect     // vulnerability. Also, Drupal 7 renders the same page for     // http://www.example.org/foo and http://www.example.org////foo.     if (str_contains($path, '//')) {
      $path = preg_replace('/\/+/', '/', $path);
      $qs = $request->getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
if ($request->attributes->has('_controller')) {
            // routing is already done             return;
        }

        // add attributes based on the request (routing)         try {
            // matching a request is more powerful than matching a URL path + context, so try that first             if ($this->matcher instanceof RequestMatcherInterface) {
                $parameters = $this->matcher->matchRequest($request);
            } else {
                $parameters = $this->matcher->match($request->getPathInfo());
            }

            $this->logger?->info('Matched route "{route}".', [
                'route' => $parameters['_route'] ?? 'n/a',
                'route_parameters' => $parameters,
                'request_uri' => $request->getUri(),
                'method' => $request->getMethod(),
            ]);

            $request->attributes->add($parameters);
            unset($parameters['_route']$parameters['_controller']);
            
public function match(string $pathinfo): array
    {
        return $this->getMatcher()->match($pathinfo);
    }

    public function matchRequest(Request $request): array
    {
        $matcher = $this->getMatcher();
        if (!$matcher instanceof RequestMatcherInterface) {
            // fallback to the default UrlMatcherInterface             return $matcher->match($request->getPathInfo());
        }

        return $matcher->matchRequest($request);
    }

    /** * Gets the UrlMatcher or RequestMatcher instance associated with this Router. */
    public function getMatcher(): UrlMatcherInterface|RequestMatcherInterface
    {
        if (null !== $this->matcher) {
            
$finder
            ->in($paths)
            ->files()
            ->name('*.php');

        foreach (self::MODULES as $module) {
            $finder->path($module);
        }

        foreach ($finder as $file) {
            $eventName = $this->buildEventName(
                $file->getPathInfo()->getBasename(),
                $file->getBasename('.php')
            );
            $controllers[$eventName] = $file->getPathname();
        }

        return $controllers;
    }

    /** * @param Plugin[] $actives * * @return string[] */
$hash = $params[$this->parameter];
        unset($params[$this->parameter]);

        return hash_equals($this->computeHash($this->buildUrl($url$params))$hash);
    }

    public function checkRequest(Request $request): bool
    {
        $qs = ($qs = $request->server->get('QUERY_STRING')) ? '?'.$qs : '';

        // we cannot use $request->getUri() here as we want to work with the original URI (no query string reordering)         return $this->check($request->getSchemeAndHttpHost().$request->getBaseUrl().$request->getPathInfo().$qs);
    }

    private function computeHash(string $uri): string
    {
        return base64_encode(hash_hmac('sha256', $uri$this->secret, true));
    }

    private function buildUrl(array $url, array $params = []): string
    {
        ksort($params, \SORT_STRING);
        $url['query'] = http_build_query($params, '', '&');

        
/** * Generates a normalized URI (URL) for the Request. * * @see getQueryString() */
    public function getUri(): string
    {
        if (null !== $qs = $this->getQueryString()) {
            $qs = '?'.$qs;
        }

        return $this->getSchemeAndHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
    }

    /** * Generates a normalized URI for the given path. * * @param string $path A path to use instead of the current one */
    public function getUriForPath(string $path): string
    {
        return $this->getSchemeAndHttpHost().$this->getBaseUrl().$path;
    }

    

    public function handle(Request $request$type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        $this->checkSltCookie($request);

        $request->headers->set('Surrogate-Capability', 'shopware="ESI/1.0"');

        if (str_starts_with($request->getPathInfo(), '/backend/')) {
            return $this->pass($request$catch);
        }

        if (stripos($request->getPathInfo(), '/widgets/index/refreshStatistic') === 0) {
            return $this->handleCookies($request$this->pass($request$catch));
        }

        if (str_starts_with($request->getPathInfo(), '/captcha/index/rand/')) {
            return $this->pass($request$catch);
        }

        
private readonly RequestTransformerInterface $decorated,
        private readonly AbstractSeoResolver $resolver,
        private readonly array $registeredApiPrefixes,
        private readonly AbstractDomainLoader $domainLoader
    ) {
    }

    public function transform(Request $request): Request
    {
        $request = $this->decorated->transform($request);

        if (!$this->isSalesChannelRequired($request->getPathInfo())) {
            return $this->decorated->transform($request);
        }

        $salesChannel = $this->findSalesChannel($request);
        if ($salesChannel === null) {
            // this class and therefore the "isSalesChannelRequired" method is currently not extendable             // which can cause problems when adding custom paths             throw new SalesChannelMappingException($request->getUri());
        }

        $absoluteBaseUrl = $this->getSchemeAndHttpHost($request) . $request->getBaseUrl();
        


    public function matches(Request $request): bool
    {
        if (!isset($this->language)) {
            throw new \LogicException('Unable to match the request as the expression language is not available. Try running "composer require symfony/expression-language".');
        }

        return $this->language->evaluate($this->expression, [
            'request' => $request,
            'method' => $request->getMethod(),
            'path' => rawurldecode($request->getPathInfo()),
            'host' => $request->getHost(),
            'ip' => $request->getClientIp(),
            'attributes' => $request->attributes->all(),
        ]) && parent::matches($request);
    }
}


        return $this->traces;
    }

    /** * @return array */
    public function getTracesForRequest(Request $request)
    {
        $this->request = $request;
        $traces = $this->getTraces($request->getPathInfo());
        $this->request = null;

        return $traces;
    }

    protected function matchCollection(string $pathinfo, RouteCollection $routes): array
    {
        // HEAD and GET are equivalent as per RFC         if ('HEAD' === $method = $this->context->getMethod()) {
            $method = 'GET';
        }
        
/** * This constraint checks whether a Request object has the right path. * * @param string $path * The path. * * @return \PHPUnit\Framework\Constraint\Callback * The constraint checks whether a Request object has the right path. */
  protected function getRequestConstraint($path) {
    return $this->callback(function DRequest $request) use ($path) {
      return $request->getPathInfo() == $path;
    });
  }

  /** * Tests the fromRoute() method with the special <front> path. * * @covers ::fromRoute */
  public function testFromRouteFront() {
    $url = Url::fromRoute('<front>');
    $this->assertSame('<front>', $url->getRouteName());
  }


    /** * Fixes request attributes when the path is '/_fragment'. * * @throws AccessDeniedHttpException if the request does not come from a trusted IP */
    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();

        if ($this->fragmentPath !== rawurldecode($request->getPathInfo())) {
            return;
        }

        if ($request->attributes->has('_controller')) {
            // Is a sub-request: no need to parse _path but it should still be removed from query parameters as below.             $request->query->remove('_path');

            return;
        }

        if ($event->isMainRequest()) {
            

  public function getLangcode(Request $request = NULL) {
    $langcode = NULL;

    if ($request && $this->languageManager) {
      $languages = $this->languageManager->getLanguages();
      $config = $this->config->get('language.negotiation')->get('url');

      switch ($config['source']) {
        case LanguageNegotiationUrl::CONFIG_PATH_PREFIX:
          $request_path = urldecode(trim($request->getPathInfo(), '/'));
          $path_args = explode('/', $request_path);
          $prefix = array_shift($path_args);

          // Search prefix within added languages.           $negotiated_language = FALSE;
          foreach ($languages as $language) {
            if (isset($config['prefixes'][$language->getId()]) && $config['prefixes'][$language->getId()] == $prefix) {
              $negotiated_language = $language;
              break;
            }
          }

          
'request_server' => $request->server->all(),
            'request_cookies' => $request->cookies->all(),
            'request_attributes' => $attributes,
            'route' => $route,
            'response_headers' => $response->headers->all(),
            'response_cookies' => $responseCookies,
            'session_metadata' => $sessionMetadata,
            'session_attributes' => $sessionAttributes,
            'session_usages' => array_values($this->sessionUsages),
            'stateless_check' => $this->requestStack?->getMainRequest()?->attributes->get('_stateless') ?? false,
            'flashes' => $flashes,
            'path_info' => $request->getPathInfo(),
            'controller' => 'n/a',
            'locale' => $request->getLocale(),
            'dotenv_vars' => $dotenvVars,
        ];

        if (isset($this->data['request_headers']['php-auth-pw'])) {
            $this->data['request_headers']['php-auth-pw'] = '******';
        }

        if (isset($this->data['request_server']['PHP_AUTH_PW'])) {
            $this->data['request_server']['PHP_AUTH_PW'] = '******';
        }
/** * @dataProvider provideAllowedData */
    public function testAllowedCombinations(ContextSource $source, bool $authRequired): void
    {
        $scope = $this->getContainer()->get(ApiRouteScope::class);

        $request = Request::create('/api/foo');
        $request->attributes->set(PlatformRequest::ATTRIBUTE_CONTEXT_OBJECT, Context::createDefaultContext($source));
        $request->attributes->set('auth_required', $authRequired);

        static::assertTrue($scope->isAllowedPath($request->getPathInfo()));
        static::assertTrue($scope->isAllowed($request));
    }

    /** * @dataProvider provideForbiddenData */
    public function testForbiddenCombinations(ContextSource $source, bool $authRequired): void
    {
        $scope = $this->getContainer()->get(ApiRouteScope::class);

        $request = Request::create('/api/foo');
        
Home | Imprint | This part of the site doesn't use cookies.