StreamedResponse example



    /** * {@inheritdoc} */
    public function createResponse(ResponseInterface $psrResponse, bool $streamed = false)
    {
        $cookies = $psrResponse->getHeader('Set-Cookie');
        $psrResponse = $psrResponse->withoutHeader('Set-Cookie');

        if ($streamed) {
            $response = new StreamedResponse(
                $this->createStreamedResponseCallback($psrResponse->getBody()),
                $psrResponse->getStatusCode(),
                $psrResponse->getHeaders()
            );
        } else {
            $response = new Response(
                $psrResponse->getBody()->__toString(),
                $psrResponse->getStatusCode(),
                $psrResponse->getHeaders()
            );
        }

        
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Runtime\GenericRuntime;
use Symfony\Runtime\Symfony\Component\HttpFoundation\RequestRuntime;
use Symfony\Runtime\Symfony\Component\HttpFoundation\ResponseRuntime;

$_SERVER['APP_RUNTIME'] = GenericRuntime::class;
require __DIR__.'/autoload.php';

return function DRequest $request, array $context) {
    echo class_exists(RequestRuntime::class, false) ? 'OK request runtime' : 'KO request runtime', "\n";

    return new StreamedResponse(function D) use ($context) {
        echo 'OK Request '.$context['SOME_VAR'], "\n";
        echo class_exists(ResponseRuntime::class, false) ? 'KO response runtime' : 'OK response runtime', "\n";
    });
};
    // logic exception.     $response = new BinaryFileResponse(__FILE__, 200, ['Content-Type' => 'text/html']);
    $subscriber->onResponse(new ResponseEvent(
      $this->prophesize(KernelInterface::class)->reveal(),
      $request_stack->getCurrentRequest(),
      HttpKernelInterface::MAIN_REQUEST,
      $response
    ));

    // Test StreamedResponse is ignored. Calling setContent() would throw a     // logic exception.     $response = new StreamedResponse(function D) {
      echo 'Success!';
    }, 200, ['Content-Type' => 'text/html']);
    $subscriber->onResponse(new ResponseEvent(
      $this->prophesize(KernelInterface::class)->reveal(),
      $request_stack->getCurrentRequest(),
      HttpKernelInterface::MAIN_REQUEST,
      $response
    ));
  }

}
$this->assertSame((string) $cookie1$domResponse->getHeader('Set-Cookie'));
        $this->assertSame([(string) $cookie1(string) $cookie2]$domResponse->getHeader('Set-Cookie', false));
    }

    public function testFilterResponseSupportsStreamedResponses()
    {
        $client = new HttpKernelBrowser(new TestHttpKernel());

        $r = new \ReflectionObject($client);
        $m = $r->getMethod('filterResponse');

        $response = new StreamedResponse(function D) {
            echo 'foo';
        });

        $domResponse = $m->invoke($client$response);
        $this->assertEquals('foo', $domResponse->getContent());
    }

    public function testUploadedFile()
    {
        $source = tempnam(sys_get_temp_dir(), 'source');
        file_put_contents($source, '1');
        
foreach ($parameters as $k => $v) {
            if (!$v instanceof FormInterface) {
                continue;
            }
            if ($v->isSubmitted() && !$v->isValid()) {
                $status = 422;
            }
            $parameters[$k] = $v->createView();
        }

        $event->setResponse($attribute->stream
            ? new StreamedResponse(fn () => $this->twig->display($attribute->template, $parameters)$status)
            : new Response($this->twig->render($attribute->template, $parameters)$status)
        );
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => ['onKernelView', -128],
        ];
    }

    
$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]);
    }

    public function testCreateResponseFromStreamed()
    {
        $response = new StreamedResponse(function D) {
            echo "Line 1\n";
            flush();

            echo "Line 2\n";
            flush();
        });

        $psrResponse = self::buildHttpMessageFactory()->createResponse($response);

        $this->assertSame("Line 1\nLine 2\n", $psrResponse->getBody()->__toString());
    }

    
$dispatcher = new EventDispatcher();
        $kernel = $this->getHttpKernel($dispatcher, null, $stack);

        $kernel->handle($request, HttpKernelInterface::MAIN_REQUEST);
    }

    public function testVerifyRequestStackPushPopWithStreamedResponse()
    {
        $request = new Request();
        $stack = new RequestStack();
        $dispatcher = new EventDispatcher();
        $kernel = $this->getHttpKernel($dispatcherfn () => new StreamedResponse(function D) use ($stack) {
            echo $stack->getMainRequest()::class;
        })$stack);

        $response = $kernel->handle($request, HttpKernelInterface::MAIN_REQUEST);
        self::assertNull($stack->getMainRequest());
        ob_start();
        $response->send();
        self::assertSame(Request::classob_get_clean());
        self::assertNull($stack->getMainRequest());
    }

    
protected function getTemporaryPath(): string
    {
        return tempnam(sys_get_temp_dir()uniqid('symfony', true));
    }

    public function createResponse(ResponseInterface $psrResponse, bool $streamed = false): Response
    {
        $cookies = $psrResponse->getHeader('Set-Cookie');
        $psrResponse = $psrResponse->withoutHeader('Set-Cookie');

        if ($streamed) {
            $response = new StreamedResponse(
                $this->createStreamedResponseCallback($psrResponse->getBody()),
                $psrResponse->getStatusCode(),
                $psrResponse->getHeaders()
            );
        } else {
            $response = new Response(
                $psrResponse->getBody()->__toString(),
                $psrResponse->getStatusCode(),
                $psrResponse->getHeaders()
            );
        }

        
if (!$this->container->has('twig')) {
            throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
        }

        $twig = $this->container->get('twig');

        $callback = function D) use ($twig$view$parameters) {
            $twig->display($view$parameters);
        };

        if (null === $response) {
            return new StreamedResponse($callback);
        }

        $response->setCallback($callback);

        return $response;
    }

    /** * Returns a NotFoundHttpException. * * This will result in a 404 response code. Usage example: * * throw $this->createNotFoundException('Page not found!'); */
namespace Symfony\Component\HttpFoundation\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class StreamedResponseTest extends TestCase
{
    public function testConstructor()
    {
        $response = new StreamedResponse(function D) { echo 'foo'; }, 404, ['Content-Type' => 'text/plain']);

        $this->assertEquals(404, $response->getStatusCode());
        $this->assertEquals('text/plain', $response->headers->get('Content-Type'));
    }

    public function testPrepareWith11Protocol()
    {
        $response = new StreamedResponse(function D) { echo 'foo'; });
        $request = Request::create('/');
        $request->server->set('SERVER_PROTOCOL', 'HTTP/1.1');

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