duplicate example

/** * @see AbstractController::forward() */
    private function executeSubRequest(AppAction $action): string
    {
        try {
            $route = $this->router->match($action->getTargetUrl());

            /** @var Request $request */
            $request = $this->requestStack->getCurrentRequest();
            $subRequest = $request->duplicate(null, null, $route);

            $response = $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);

            return $response->getContent() ?: '';
        } catch (\Exception $e) {
            throw AppException::actionButtonProcessException($action->getActionId(), 'ActionButton local execution failed', $e);
        }
    }
}
class SubRequestServiceResolutionController
{
    public function __construct(private ContainerInterface $container)
    {
    }

    public function indexAction()
    {
        $request = $this->container->get('request_stack')->getCurrentRequest();
        $path['_controller'] = self::class.'::fragmentAction';
        $subRequest = $request->duplicate([], null, $path);

        return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }

    public function fragmentAction(LoggerInterface $logger)
    {
        return new Response('---');
    }
}
return new Response($exception->getAsString()$exception->getStatusCode()$exception->getHeaders());
    }

    public function preview(Request $request, int $code): Response
    {
        /* * This Request mimics the parameters set by * \Symfony\Component\HttpKernel\EventListener\ErrorListener::duplicateRequest, with * the additional "showException" flag. */
        $subRequest = $request->duplicate(null, null, [
            '_controller' => $this->controller,
            'exception' => new HttpException($code, 'This is a sample exception.'),
            'logger' => null,
            'showException' => false,
        ]);

        return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }
}
/** * Clones the request for the exception. */
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
    {
        $attributes = [
            '_controller' => $this->controller,
            'exception' => $exception,
            'logger' => $this->logger instanceof DebugLoggerInterface ? $this->logger : null,
        ];
        $request = $request->duplicate(null, null, $attributes);
        $request->setMethod('GET');

        return $request;
    }
}


    /** * Forwards the request to another controller. * * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction) */
    protected function forward(string $controller, array $path = [], array $query = []): Response
    {
        $request = $this->container->get('request_stack')->getCurrentRequest();
        $path['_controller'] = $controller;
        $subRequest = $request->duplicate($query, null, $path);

        return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }

    /** * Returns a RedirectResponse to the given URL. * * @param int $status The HTTP status code (302 "Found" by default) */
    protected function redirect(string $url, int $status = 302): RedirectResponse
    {
        
public function matchRequest(Request $request): array
    {
        if (!$request->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID)) {
            return $this->decorated->matchRequest($request);
        }

        $server = array_merge(
            $request->server->all(),
            ['REQUEST_URI' => $request->attributes->get(RequestTransformer::SALES_CHANNEL_RESOLVED_URI)]
        );

        $localClone = $request->duplicate(null, null, null, null, null, $server);

        return $this->decorated->matchRequest($localClone);
    }

    public function setContext(RequestContext $context): void
    {
        $this->decorated->setContext($context);
    }

    public function getContext(): RequestContext
    {
        
if (!isset($languages[$original_langcode])) {
      // If the language is not configured on the site, create a dummy language       // object for this listing only to ensure the user gets useful info.       $language_name = $this->languageManager->getLanguageName($original_langcode);
      $languages[$original_langcode] = new Language(['id' => $original_langcode, 'name' => $language_name]);
    }

    // We create a fake request object to pass into     // ConfigMapperInterface::populateFromRouteMatch() for the different languages.     // Creating a separate request for each language and route is neither easily     // possible nor performant.     $fake_request = $request->duplicate();

    $page['languages'] = [
      '#type' => 'table',
      '#header' => [$this->t('Language')$this->t('Operations')],
    ];
    foreach ($languages as $language) {
      $langcode = $language->getId();

      // This is needed because       // ConfigMapperInterface::getAddRouteParameters(), for example,       // needs to return the correct language code for each table row.
return new Response($exception->getAsString()$exception->getStatusCode()$exception->getHeaders());
    }

    public function preview(Request $request, int $code): Response
    {
        /* * This Request mimics the parameters set by * \Symfony\Component\HttpKernel\EventListener\ErrorListener::duplicateRequest, with * the additional "showException" flag. */
        $subRequest = $request->duplicate(null, null, [
            '_controller' => $this->controller,
            'exception' => new HttpException($code, 'This is a sample exception.'),
            'logger' => null,
            'showException' => false,
        ]);

        return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
    }
}

        $transformedServerVars = array_merge(
            $request->server->all(),
            ['REQUEST_URI' => rtrim($request->getBaseUrl(), '/') . $resolved['pathInfo']]
        );

        $transformedRequest = $request->duplicate(null, null, null, null, null, $transformedServerVars);
        $transformedRequest->attributes->set(self::SALES_CHANNEL_BASE_URL, $baseUrl);
        $transformedRequest->attributes->set(self::SALES_CHANNEL_ABSOLUTE_BASE_URL, rtrim($absoluteBaseUrl, '/'));
        $transformedRequest->attributes->set(
            self::STOREFRONT_URL,
            $transformedRequest->attributes->get(self::SALES_CHANNEL_ABSOLUTE_BASE_URL)
            . $transformedRequest->attributes->get(self::SALES_CHANNEL_BASE_URL)
        );
        $transformedRequest->attributes->set(self::SALES_CHANNEL_RESOLVED_URI, $resolved['pathInfo']);

        $transformedRequest->attributes->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID, $salesChannel['salesChannelId']);
        $transformedRequest->attributes->set(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST, true);
        
$collection = new CriteriaCollection();

        $queries = $this->serializer->decode($request->getContent(), 'json');

        foreach ($queries as $entityName => $query) {
            if (!$this->definitionInstanceRegistry->has($entityName)) {
                continue;
            }

            $definition = $this->definitionInstanceRegistry->getByEntityName($entityName);

            $criteriaRequest = $request->duplicate($request->query->all()$query);

            $criteria = $this->requestCriteriaBuilder->handleRequest($criteriaRequestnew Criteria()$definition$context);

            $collection->set($entityName$criteria);
        }

        return $collection;
    }
}
/** * Clones the request for the exception. */
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
    {
        $attributes = [
            '_controller' => $this->controller,
            'exception' => $exception,
            'logger' => DebugLoggerConfigurator::getDebugLogger($this->logger),
        ];
        $request = $request->duplicate(null, null, $attributes);
        $request->setMethod('GET');

        return $request;
    }
}
$this->assertEquals('example.net', $request->getHost());
        $this->assertEquals(8080, $request->getPort());
        $this->assertFalse($request->isSecure());
        $this->assertEquals('thomas', $request->getUser());
        $this->assertEquals('pokemon', $request->getPassword());
        $this->assertEquals('foo=bar', $request->getQueryString());
    }

    public function testDuplicate()
    {
        $request = new Request(['foo' => 'bar']['foo' => 'bar']['foo' => 'bar'][][]['HTTP_FOO' => 'bar']);
        $dup = $request->duplicate();

        $this->assertEquals($request->query->all()$dup->query->all(), '->duplicate() duplicates a request an copy the current query parameters');
        $this->assertEquals($request->request->all()$dup->request->all(), '->duplicate() duplicates a request an copy the current request parameters');
        $this->assertEquals($request->attributes->all()$dup->attributes->all(), '->duplicate() duplicates a request an copy the current attributes');
        $this->assertEquals($request->headers->all()$dup->headers->all(), '->duplicate() duplicates a request an copy the current HTTP headers');

        $dup = $request->duplicate(['foo' => 'foobar']['foo' => 'foobar']['foo' => 'foobar'][][]['HTTP_FOO' => 'foobar']);

        $this->assertEquals(['foo' => 'foobar']$dup->query->all(), '->duplicate() overrides the query parameters if provided');
        $this->assertEquals(['foo' => 'foobar']$dup->request->all(), '->duplicate() overrides the request parameters if provided');
        $this->assertEquals(['foo' => 'foobar']$dup->attributes->all(), '->duplicate() overrides the attributes if provided');
        
$container = new Container();
        $container->set('session_factory', $sessionFactory);
        $container->set('request_stack', $requestStack);

        $event = new RequestEvent($kernel$mainRequest, HttpKernelInterface::MAIN_REQUEST);

        $listener = new SessionListener($container);
        $listener->onKernelRequest($event);

        // storage->setOptions() should have been called already         $subRequest = $mainRequest->duplicate();
        // at this point both main and subrequest have a closure to build the session
        $mainRequest->getSession();

        // calling the factory on the subRequest should not trigger a second call to storage->setOptions()         $subRequest->getSession();
    }

    public function testGetSessionSetsSessionOnMainRequest()
    {
        $mainRequest = new Request();
        
return $call();
        } finally {
            $this->restoreRequestStack($this->requestStack, $requestStackBackup);
        }
    }

    private function setUpSalesChannelApiRequest(string $path, string $salesChannelId, Request $request, SalesChannelEntity $salesChannel): Request
    {
        $contextToken = $this->getContextToken($request);

        $server = array_merge($request->server->all()['REQUEST_URI' => '/store-api/' . $path]);
        $subrequest = $request->duplicate(null, null, [], null, null, $server);

        $subrequest->headers->set(PlatformRequest::HEADER_ACCESS_KEY, $salesChannel->getAccessKey());
        $subrequest->headers->set(PlatformRequest::HEADER_CONTEXT_TOKEN, $contextToken);
        $subrequest->attributes->set(PlatformRequest::ATTRIBUTE_OAUTH_CLIENT_ID, $salesChannel->getAccessKey());

        $this->requestContextResolver->handleSalesChannelContext(
            $subrequest,
            $salesChannelId,
            $contextToken
        );

        
'html_response_attachment_placeholders' => [
            'scripts_bottom' => $js_bottom_placeholder,
          ],
        ],
      ]);
      $html_response->getCacheableMetadata()->setCacheMaxAge(0);

      // Push a fake request with the asset libraries loaded so far and dispatch       // KernelEvents::RESPONSE event. This results in the attachments for the       // HTML response being processed by HtmlResponseAttachmentsProcessor and       // hence the HTML to load the bottom JavaScript can be rendered.       $fake_request = $this->requestStack->getMainRequest()->duplicate();
      $html_response = $this->filterEmbeddedResponse($fake_request$html_response);
      $scripts_bottom = $html_response->getContent();
    }

    $this->sendChunk($scripts_bottom);
  }

  /** * Sends no-JS BigPipe placeholders' replacements as embedded HTML responses. * * @param string $html * HTML markup. * @param array $no_js_placeholders * Associative array; the no-JS BigPipe placeholders. Keys are the BigPipe * selectors. * @param \Drupal\Core\Asset\AttachedAssetsInterface $cumulative_assets * The cumulative assets sent so far; to be updated while rendering no-JS * BigPipe placeholders. * * @throws \Exception * If an exception is thrown during the rendering of a placeholder, it is * caught to allow the other placeholders to still be replaced. But when * error logging is configured to be verbose, the exception is rethrown to * simplify debugging. */
Home | Imprint | This part of the site doesn't use cookies.