Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add App::terminate() stream support #2028

Merged
merged 25 commits into from
Apr 8, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 41 additions & 0 deletions demos/_unit-test/stream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace Atk4\Ui\Demos;

use Atk4\Ui\Button;
use Nyholm\Psr7\Factory\Psr17Factory;

/** @var \Atk4\Ui\App $app */
require_once __DIR__ . '/../init-app.php';

/**
* Size in Mb of generated download file.
* This can also be passed as GET['size_mb'] parameter.
*
* @var int
*/
$size_mb = (int) ($_GET['size_mb'] ?? 64);

$button = Button::addTo($app, ['Download', 'class.atk-test' => true]);
$button->on('click', function () use ($app, $size_mb) {
// Generate big data and write it to a temporary file
$pattern = str_repeat('0123456789ABCDEF', 65536); // 1Mb
$total_size = strlen($pattern) * $size_mb;
$tempFile = tempnam(sys_get_temp_dir(), 'test.txt');
mvorisek marked this conversation as resolved.
Show resolved Hide resolved

$fh = fopen($tempFile, 'w');
for ($i = 0; $i < $size_mb; ++$i) {
fwrite($fh, $pattern);
}
fclose($fh);

// Send the data using a file stream response
$factory = new Psr17Factory();
$stream = $factory->createStreamFromFile($tempFile);
$app->setResponseHeader('Content-Type', 'text/plain');
$app->setResponseHeader('Content-Disposition', 'attachment; filename="test.txt"');
$app->setResponseHeader('Content-Length', (string) $total_size);
$app->terminate($stream);
});
14 changes: 11 additions & 3 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Nyholm\Psr7Server\ServerRequestCreator;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Log\LoggerInterface;

class App
Expand Down Expand Up @@ -394,7 +395,7 @@ public function setResponseHeader(string $name, string $value): self
* directly, instead call it form Callback, JsCallback or similar
* other classes.
*
* @param string|array $output Array type is supported only for JSON response
* @param string|StreamInterface|array $output Array type is supported only for JSON response
*
* @return never
*/
Expand All @@ -405,7 +406,10 @@ public function terminate($output = ''): void
throw new Exception('Content type must be always set');
}

if ($type === 'application/json') {
if ($output instanceof StreamInterface) {
$this->response = $this->response->withBody($output);
$this->outputResponse('');
} elseif ($type === 'application/json') {
if (is_string($output)) {
$output = $this->decodeJson($output);
}
Expand Down Expand Up @@ -1128,7 +1132,11 @@ protected function outputResponse(string $data): void
return;
}

$this->response->getBody()->write($data);
$stream = $this->response->getBody();
if ($data !== '' /* && $stream->isWritable() */) {
$stream->write($data);
}

$this->emitResponse();
}

Expand Down
13 changes: 13 additions & 0 deletions tests/DemosTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,19 @@ public function testWizard(): void
static::assertMatchesRegularExpression($this->regexHtml, $response->getBody()->getContents());
}

public function testDownloadAsStream(): void
{
$btn = 'atk_layout_maestro_button_click';
$response = $this->getResponseFromRequest(
'_unit-test/stream.php?' . Callback::URL_QUERY_TRIGGER_PREFIX . $btn . '=ajax&' . Callback::URL_QUERY_TARGET . '=' . $btn,
[
'size_mb' => 64, // 128Mb will give out of memory error
]
);
static::assertSame(200, $response->getStatusCode());
static::assertSame(16 * 65536 * 64, strlen($response->getBody()->getContents())); // 64Mb
}

/**
* Test reload and loader callback.
*/
Expand Down