createRequest example

public function testOrderWithFailedPaymentMethod(): void
    {
        $this->createFailedPaymentMethodData();

        $contextToken = Uuid::randomHex();

        $this->fillCart($contextToken, false, true);

        $requestDataBag = $this->createRequestDataBag('');
        $salesChannelContext = $this->createSalesChannelContext($contextToken, true);
        $request = $this->createRequest();

        /** @var RedirectResponse|Response $response */
        $response = $this->getContainer()->get(CheckoutController::class)->order($requestDataBag$salesChannelContext$request);

        static::assertInstanceOf(RedirectResponse::class$response);
        static::assertStringContainsString('/account/order/edit', $response->getTargetUrl(), 'Target Url does not point to /checkout/finish');
    }

    public function testAffiliateAndCampaignTracking(): void
    {
        $request = $this->createRequest();
        
$this->logger?->debug('Access denied, the user is neither anonymous, nor remember-me.', ['exception' => $exception]);

        try {
            if (null !== $this->accessDeniedHandler) {
                $response = $this->accessDeniedHandler->handle($event->getRequest()$exception);

                if ($response instanceof Response) {
                    $event->setResponse($response);
                }
            } elseif (null !== $this->errorPage) {
                $subRequest = $this->httpUtils->createRequest($event->getRequest()$this->errorPage);
                $subRequest->attributes->set(SecurityRequestAttributes::ACCESS_DENIED_ERROR, $exception);

                $event->setResponse($event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true));
                $event->allowCustomResponseCode();
            }
        } catch (\Exception $e) {
            $this->logger?->error('An exception was thrown when handling an AccessDeniedException.', ['exception' => $e]);

            $event->setThrowable(new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
        }
    }

    
$connection->rollBack();
    }

    public function testCacheHit(): void
    {
        $kernel = $this->getCacheKernel();

        $appUrl = EnvironmentHelper::getVariable('APP_URL');
        static::assertIsString($appUrl);

        $request = $this->createRequest($appUrl);

        $response = $kernel->handle($request);
        static::assertTrue($response->headers->has('x-symfony-cache'));
        static::assertEquals('GET /: miss, store', $response->headers->get('x-symfony-cache'));

        $response = $kernel->handle($request);
        static::assertEquals('GET /: fresh', $response->headers->get('x-symfony-cache'));
    }

    public function testCacheHitWithDifferentCacheKeys(): void
    {
        
 else {
            $routeParameters = func_get_arg(3);

            if (!\is_array($routeParameters)) {
                throw new \TypeError(sprintf('"%s": Argument $routeParameters is expected to be an array, got "%s".', __METHOD__, get_debug_type($routeParameters)));
            }
        }

        // expression condition         if ($route->getCondition() && !$this->getExpressionLanguage()->evaluate($route->getCondition()[
            'context' => $this->context,
            'request' => $this->request ?: $this->createRequest($pathinfo),
            'params' => $routeParameters,
        ])) {
            return [self::REQUIREMENT_MISMATCH, null];
        }

        return [self::REQUIREMENT_MATCH, null];
    }

    /** * Get merged default parameters. */
    
$resolver = new BackedEnumValueResolver();

        if (!$expectedSupport) {
            $this->assertSame([]$resolver->resolve($request$metadata));
        }
        self::assertSame($expectedSupport$resolver->supports($request$metadata));
    }

    public static function provideTestSupportsData(): iterable
    {
        yield 'unsupported type' => [
            self::createRequest(['suit' => 'H']),
            self::createArgumentMetadata('suit', \stdClass::class),
            false,
        ];

        yield 'supports from attributes' => [
            self::createRequest(['suit' => 'H']),
            self::createArgumentMetadata('suit', Suit::class),
            true,
        ];

        yield 'with null attribute value' => [
            

        if (!class_exists(Psr7Request::class)) {
            $this->markTestSkipped('nyholm/psr7 is not installed.');
        }
    }

    /** * @dataProvider requestProvider */
    public function testConvertRequestMultipleTimes(ServerRequestInterface|Request $request, HttpMessageFactoryInterface|HttpFoundationFactoryInterface $firstFactory, HttpMessageFactoryInterface|HttpFoundationFactoryInterface $secondFactory)
    {
        $temporaryRequest = $firstFactory->createRequest($request);
        $finalRequest = $secondFactory->createRequest($temporaryRequest);

        if ($finalRequest instanceof Request) {
            $this->assertEquals($request->getBasePath()$finalRequest->getBasePath());
            $this->assertEquals($request->getBaseUrl()$finalRequest->getBaseUrl());
            $this->assertEquals($request->getContent()$finalRequest->getContent());
            $this->assertEquals($request->getEncodings()$finalRequest->getEncodings());
            $this->assertEquals($request->getETags()$finalRequest->getETags());
            $this->assertEquals($request->getHost()$finalRequest->getHost());
            $this->assertEquals($request->getHttpHost()$finalRequest->getHttpHost());
            $this->assertEquals($request->getMethod()$finalRequest->getMethod());
            
 $catalogue->all('messages'));
    }

    /** * @dataProvider getSnippetSetIdRequestProvider * * @param string[] $dbSnippetSetIds */
    public function testGetSnippetId(array $dbSnippetSetIds, ?string $expectedSnippetSetId, ?string $locale, ?string $requestSnippetSetId): void
    {
        $requestStack = new RequestStack();
        $requestStack->push($this->createRequest(null, $requestSnippetSetId));

        $connection = $this->createMock(Connection::class);
        $connection->expects($locale ? static::once() : static::never())->method('fetchFirstColumn')->willReturn($dbSnippetSetIds);

        $translator = new Translator(
            $this->createMock(SymfonyTranslator::class),
            $requestStack,
            $this->createMock(CacheInterface::class),
            $this->createMock(MessageFormatterInterface::class),
            'prod',
            $connection,
            
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Tests\Fixtures\DataCollector\DummyController;

class RequestDataCollectorTest extends TestCase
{
    public function testCollect()
    {
        $c = new RequestDataCollector();

        $c->collect($request = $this->createRequest()$this->createResponse());
        $c->lateCollect();

        $attributes = $c->getRequestAttributes();

        $this->assertSame('request', $c->getName());
        $this->assertInstanceOf(ParameterBag::class$c->getRequestHeaders());
        $this->assertInstanceOf(ParameterBag::class$c->getRequestServer());
        $this->assertInstanceOf(ParameterBag::class$c->getRequestCookies());
        $this->assertInstanceOf(ParameterBag::class$attributes);
        $this->assertInstanceOf(ParameterBag::class$c->getRequestRequest());
        $this->assertInstanceOf(ParameterBag::class$c->getRequestQuery());
        
class HttplugClientTest extends TestCase
{
    public static function setUpBeforeClass(): void
    {
        TestHttpServer::start();
    }

    public function testSendRequest()
    {
        $client = new HttplugClient(new NativeHttpClient());

        $response = $client->sendRequest($client->createRequest('GET', 'http://localhost:8057'));

        $this->assertSame(200, $response->getStatusCode());
        $this->assertSame('application/json', $response->getHeaderLine('content-type'));

        $body = json_decode((string) $response->getBody(), true);

        $this->assertSame('HTTP/1.1', $body['SERVER_PROTOCOL']);
    }

    public function testSendAsyncRequest()
    {
        
public function __construct(
        private readonly HttpMessageFactoryInterface $httpMessageFactory,
    ) {
    }

    public function resolve(Request $request, ArgumentMetadata $argument): \Traversable
    {
        if (!isset(self::SUPPORTED_TYPES[$argument->getType()])) {
            return;
        }

        yield $this->httpMessageFactory->createRequest($request);
    }
}

        $request = $event->getRequest();

        if (!$request->attributes->get('auth_required', true)) {
            return;
        }

        if (!$this->isRequestScoped($request, ApiContextRouteScopeDependant::class)) {
            return;
        }

        $psr7Request = $this->psrHttpFactory->createRequest($event->getRequest());
        $psr7Request = $this->resourceServer->validateAuthenticatedRequest($psr7Request);

        $request->attributes->add($psr7Request->getAttributes());
    }

    protected function getScopeRegistry(): RouteScopeRegistry
    {
        return $this->routeScopeRegistry;
    }
}
/** * @param string $method * @param UriInterface|string $uri */
    public function createRequest($method$uri, array $headers = []$body = null, $protocolVersion = '1.1'): RequestInterface
    {
        if (2 < \func_num_args()) {
            trigger_deprecation('symfony/http-client', '6.2', 'Passing more than 2 arguments to "%s()" is deprecated.', __METHOD__);
        }
        if ($this->responseFactory instanceof RequestFactoryInterface) {
            $request = $this->responseFactory->createRequest($method$uri);
        } elseif (class_exists(Psr17FactoryDiscovery::class)) {
            $request = Psr17FactoryDiscovery::findRequestFactory()->createRequest($method$uri);
        } elseif (class_exists(Request::class)) {
            $request = new Request($method$uri);
        } else {
            throw new \LogicException(sprintf('You cannot use "%s()" as no PSR-17 factories have been found. Try running "composer require php-http/discovery psr/http-factory-implementation:*".', __METHOD__));
        }

        $request = $request
            ->withProtocolVersion($protocolVersion)
            ->withBody($this->createStream($body ?? ''))
        ;

    public function testValidation(bool $isValid, Request $request, Response $response): void
    {
        $validator = new CacheStateValidator([]);
        static::assertSame($isValid$validator->isValid($request$response));
    }

    public static function cases(): array
    {
        return [
            [true, new Request()new Response()],
            [false, self::createRequest('logged-in'), self::createResponse('logged-in')],
            [true, self::createRequest('logged-in'), self::createResponse()],
            [true, self::createRequest(), self::createResponse('cart-filled')],
            [false, self::createRequest('logged-in'), self::createResponse('cart-filled', 'logged-in')],
            [false, self::createRequest('cart-filled', 'logged-in'), self::createResponse('cart-filled', 'logged-in')],
        ];
    }

    private static function createRequest(string ...$states): Request
    {
        $request = new Request();
        $request->cookies->set(CacheResponseSubscriber::SYSTEM_STATE_COOKIE, implode(',', $states));

        
$this->getContainer()->get(AccountLoginPageLoader::class),
            $passwordRecoveryMailRoute,
            $this->getContainer()->get(ResetPasswordRoute::class),
            $this->getContainer()->get(LoginRoute::class),
            $this->getContainer()->get(LogoutRoute::class),
            $this->getContainer()->get(StorefrontCartFacade::class),
            $this->getContainer()->get(AccountRecoverPasswordPageLoader::class),
            $this->getContainer()->get(SalesChannelContextService::class)
        );
        $controller->setContainer($this->getContainer());

        $request = $this->createRequest('frontend.account.recover.request');

        $this->getContainer()->get('request_stack')->push($request);

        $controller->generateAccountRecovery($requestnew RequestDataBag([
            'email' => [
                'email' => 'test@example.com',
            ],
        ])$this->salesChannelContext);

        $session = $this->getSession();
        static::assertInstanceOf(Session::class$session);
        
if (\is_string($failureUrl) && (str_starts_with($failureUrl, '/') || str_starts_with($failureUrl, 'http'))) {
            $options['failure_path'] = $failureUrl;
        } elseif ($this->logger && $failureUrl) {
            $this->logger->debug(sprintf('Ignoring query parameter "%s": not a valid URL.', $options['failure_path_parameter']));
        }

        $options['failure_path'] ??= $options['login_path'];

        if ($options['failure_forward']) {
            $this->logger?->debug('Authentication failure, forward triggered.', ['failure_path' => $options['failure_path']]);

            $subRequest = $this->httpUtils->createRequest($request$options['failure_path']);
            $subRequest->attributes->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);

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

        $this->logger?->debug('Authentication failure, redirect triggered.', ['failure_path' => $options['failure_path']]);

        if (!$request->attributes->getBoolean('_stateless')) {
            $request->getSession()->set(SecurityRequestAttributes::AUTHENTICATION_ERROR, $exception);
        }

        
Home | Imprint | This part of the site doesn't use cookies.