createResponse example


    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));

        
$response = new Response();

        try {
            $cacheKey = $request->get('username') . '-' . $request->getClientIp();

            $this->rateLimiter->ensureAccepted(RateLimiter::OAUTH, $cacheKey);
        } catch (RateLimitExceededException $exception) {
            throw new AuthThrottledException($exception->getWaitTime()$exception);
        }

        $psr7Request = $this->psrHttpFactory->createRequest($request);
        $psr7Response = $this->psrHttpFactory->createResponse($response);

        $response = $this->authorizationServer->respondToAccessTokenRequest($psr7Request$psr7Response);

        $this->rateLimiter->reset(RateLimiter::OAUTH, $cacheKey);

        return (new HttpFoundationFactory())->createResponse($response);
    }
}
/** * Converts a PSR-7 response to a Symfony response. * * @param \Symfony\Component\HttpKernel\Event\ViewEvent $event * The Event to process. */
  public function onKernelView(ViewEvent $event) {
    $controller_result = $event->getControllerResult();

    if ($controller_result instanceof ResponseInterface) {
      $event->setResponse($this->httpFoundationFactory->createResponse($controller_result));
    }

  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    $events[KernelEvents::VIEW][] = ['onKernelView'];
    return $events;
  }

}
$sfRequest$psr17Factory$symfonyFactory],
        ]array_map(function D$psr7Request) use ($symfonyFactory$psr17Factory) {
            return [$psr7Request$symfonyFactory$psr17Factory];
        }$psr7Requests));
    }

    /** * @dataProvider responseProvider */
    public function testConvertResponseMultipleTimes(ResponseInterface|Response $response, HttpMessageFactoryInterface|HttpFoundationFactoryInterface $firstFactory, HttpMessageFactoryInterface|HttpFoundationFactoryInterface $secondFactory)
    {
        $temporaryResponse = $firstFactory->createResponse($response);
        $finalResponse = $secondFactory->createResponse($temporaryResponse);

        if ($finalResponse instanceof Response) {
            $this->assertEquals($response->getAge()$finalResponse->getAge());
            $this->assertEquals($response->getCharset()$finalResponse->getCharset());
            $this->assertEquals($response->getContent()$finalResponse->getContent());
            $this->assertEquals($response->getDate()$finalResponse->getDate());
            $this->assertEquals($response->getEtag()$finalResponse->getEtag());
            $this->assertEquals($response->getExpires()$finalResponse->getExpires());
            $this->assertEquals($response->getLastModified()$finalResponse->getLastModified());
            $this->assertEquals($response->getMaxAge()$finalResponse->getMaxAge());
            

    // Catch RequestException rather than TransferException because we want     // to re-throw the exception whenever the response is NULL, and     // ConnectException always has a NULL response.     catch (RequestException $e) {
      if (!$e->hasResponse()) {
        throw $e;
      }
      $response = $e->getResponse();
    }

    return $this->createResponse($response);
  }

  /** * Adds files to the $multipart array. * * @param array $files * The files. * @param array $multipart * A reference to the multipart array to add the files to. * @param string $array_name * Internal parameter used by recursive calls. */

        $response = new Response(
            'Response content.',
            202,
            [
                'X-Symfony' => ['3.4'],
                ' X-Broken-Header' => 'abc',
            ]
        );
        $response->headers->setCookie(new Cookie('city', 'Lille', new \DateTime('Wed, 13 Jan 2021 22:23:01 GMT'), '/', null, false, true, false, 'lax'));

        $psrResponse = $factory->createResponse($response);
        $this->assertSame('Response content.', $psrResponse->getBody()->__toString());
        $this->assertSame(202, $psrResponse->getStatusCode());
        $this->assertSame(['3.4']$psrResponse->getHeader('x-symfony'));
        $this->assertFalse($psrResponse->hasHeader(' X-Broken-Header'));
        $this->assertFalse($psrResponse->hasHeader('X-Broken-Header'));

        $cookieHeader = $psrResponse->getHeader('Set-Cookie');
        $this->assertIsArray($cookieHeader);
        $this->assertCount(1, $cookieHeader);
        $this->assertMatchesRegularExpression('{city=Lille; expires=Wed, 13.Jan.2021 22:23:01 GMT;( max-age=\d+;)? path=/; httponly}i', $cookieHeader[0]);
    }

    
$symfonyUploadedFile->getError(),
            $symfonyUploadedFile->getClientOriginalName(),
            $symfonyUploadedFile->getClientMimeType()
        );
    }

    /** * {@inheritdoc} */
    public function createResponse(Response $symfonyResponse)
    {
        $response = $this->responseFactory->createResponse($symfonyResponse->getStatusCode(), Response::$statusTexts[$symfonyResponse->getStatusCode()] ?? '');

        if ($symfonyResponse instanceof BinaryFileResponse && !$symfonyResponse->headers->has('Content-Range')) {
            $stream = $this->streamFactory->createStreamFromFile(
                $symfonyResponse->getFile()->getPathname()
            );
        } else {
            $stream = $this->streamFactory->createStreamFromFile('php://temp', 'wb+');
            if ($symfonyResponse instanceof StreamedResponse || $symfonyResponse instanceof BinaryFileResponse) {
                ob_start(function D$buffer) use ($stream) {
                    $stream->write($buffer);

                    
$symfonyUploadedFile->getRealPath()
            ),
            (int) $symfonyUploadedFile->getSize(),
            $symfonyUploadedFile->getError(),
            $symfonyUploadedFile->getClientOriginalName(),
            $symfonyUploadedFile->getClientMimeType()
        );
    }

    public function createResponse(Response $symfonyResponse): ResponseInterface
    {
        $response = $this->responseFactory->createResponse($symfonyResponse->getStatusCode(), Response::$statusTexts[$symfonyResponse->getStatusCode()] ?? '');

        if ($symfonyResponse instanceof BinaryFileResponse && !$symfonyResponse->headers->has('Content-Range')) {
            $stream = $this->streamFactory->createStreamFromFile(
                $symfonyResponse->getFile()->getPathname()
            );
        } else {
            $stream = $this->streamFactory->createStreamFromFile('php://temp', 'wb+');
            if ($symfonyResponse instanceof StreamedResponse || $symfonyResponse instanceof BinaryFileResponse) {
                ob_start(function D$buffer) use ($stream) {
                    $stream->write($buffer);

                    


  /** * @covers ::doValidateResponse */
  public function testDoValidateResponse() {
    $request = $this->createRequest(
      'jsonapi.node--article.individual',
      new ResourceType('node', 'article', NULL)
    );

    $response = $this->createResponse('{"data":null}');

    // Capture the default assert settings.     $zend_assertions_default = ini_get('zend.assertions');
    $assert_active_default = assert_options(ASSERT_ACTIVE);

    // The validator *should* be called when asserts are active.     $validator = $this->prophesize(Validator::class);
    $validator->check(Argument::any(), Argument::any())->shouldBeCalled('Validation should be run when asserts are active.');
    $validator->isValid()->willReturn(TRUE);
    $this->subscriber->setValidator($validator->reveal());

    
$requestNonceHeaders = [
            'X-SymfonyProfiler-Script-Nonce' => $requestScriptNonce,
            'X-SymfonyProfiler-Style-Nonce' => $requestStyleNonce,
        ];
        $responseNonceHeaders = [
            'X-SymfonyProfiler-Script-Nonce' => $responseScriptNonce,
            'X-SymfonyProfiler-Style-Nonce' => $responseStyleNonce,
        ];

        return [
            [$nonce['csp_script_nonce' => $nonce, 'csp_style_nonce' => $nonce], self::createRequest(), self::createResponse()],
            [$nonce['csp_script_nonce' => $requestScriptNonce, 'csp_style_nonce' => $requestStyleNonce], self::createRequest($requestNonceHeaders), self::createResponse($responseNonceHeaders)],
            [$nonce['csp_script_nonce' => $requestScriptNonce, 'csp_style_nonce' => $requestStyleNonce], self::createRequest($requestNonceHeaders), self::createResponse()],
            [$nonce['csp_script_nonce' => $responseScriptNonce, 'csp_style_nonce' => $responseStyleNonce], self::createRequest(), self::createResponse($responseNonceHeaders)],
        ];
    }

    public static function provideRequestAndResponsesForOnKernelResponse()
    {
        $nonce = bin2hex(random_bytes(16));

        $requestScriptNonce = 'request-with-headers-script-nonce';
        
'X-Symfony' => ['2.8'],
                'Set-Cookie' => [
                    'theme=light',
                    'test',
                    'ABC=AeD; Domain=dunglas.fr; Path=/kevin; Expires=Wed, 13 Jan 2021 22:23:01 GMT; Secure; HttpOnly; SameSite=Strict',
                ],
            ],
            new Stream('The response body'),
            200
        );

        $symfonyResponse = $this->factory->createResponse($response);

        $this->assertEquals('1.0', $symfonyResponse->getProtocolVersion());
        $this->assertEquals('2.8', $symfonyResponse->headers->get('X-Symfony'));

        $cookies = $symfonyResponse->headers->getCookies();
        $this->assertEquals('theme', $cookies[0]->getName());
        $this->assertEquals('light', $cookies[0]->getValue());
        $this->assertEquals(0, $cookies[0]->getExpiresTime());
        $this->assertNull($cookies[0]->getDomain());
        $this->assertEquals('/', $cookies[0]->getPath());
        $this->assertFalse($cookies[0]->isSecure());
        
/** * Do the conversion if applicable and update the response of the event. */
    public function onKernelView(ViewEvent $event): void
    {
        $controllerResult = $event->getControllerResult();

        if (!$controllerResult instanceof ResponseInterface) {
            return;
        }

        $event->setResponse($this->httpFoundationFactory->createResponse($controllerResult));
    }

    /** * {@inheritdoc} */
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => 'onKernelView',
        ];
    }
}


        return static function D$ch$h) use (
            $onHeaders,
            $easy,
            &$startingResponse
        ) {
            $value = \trim($h);
            if ($value === '') {
                $startingResponse = true;
                try {
                    $easy->createResponse();
                } catch (\Exception $e) {
                    $easy->createResponseException = $e;

                    return -1;
                }
                if ($onHeaders !== null) {
                    try {
                        $onHeaders($easy->response);
                    } catch (\Exception $e) {
                        // Associate the exception with the handle and trigger                         // a curl header write error by returning 0.
$operation['payload'] ?? [],
                $operation['criteria'] ?? []
            );

            if (empty($operation['entity'])) {
                throw ApiException::invalidSyncOperationException(sprintf('Missing "entity" argument for operation with key "%s". It needs to be a non-empty string.', (string) $key));
            }
        }

        $result = $context->scope(Context::CRUD_API_SCOPE, fn (Context $context): SyncResult => $this->syncService->sync($operations$context$behavior));

        return $this->createResponse($result, Response::HTTP_OK);
    }

    private function createResponse(SyncResult $result, int $statusCode = 200): JsonResponse
    {
        $response = new JsonResponse(null, $statusCode);
        $response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_INVALID_UTF8_SUBSTITUTE);
        $response->setData($result);

        return $response;
    }
}
/** * Do the conversion if applicable and update the response of the event. */
    public function onKernelView(ViewEvent $event): void
    {
        $controllerResult = $event->getControllerResult();

        if (!$controllerResult instanceof ResponseInterface) {
            return;
        }

        $event->setResponse($this->httpFoundationFactory->createResponse($controllerResult));
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => 'onKernelView',
        ];
    }
}
Home | Imprint | This part of the site doesn't use cookies.