-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathGotenbergFileResult.php
90 lines (76 loc) · 2.65 KB
/
GotenbergFileResult.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace Sensiolabs\GotenbergBundle\Builder;
use Sensiolabs\GotenbergBundle\Client\GotenbergResponse;
use Sensiolabs\GotenbergBundle\Exception\ProcessorException;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Contracts\HttpClient\ChunkInterface;
class GotenbergFileResult
{
/**
* @param \Generator<int, void, ChunkInterface, mixed> $processorGenerator
*/
public function __construct(
protected readonly GotenbergResponse $response,
protected readonly \Generator $processorGenerator,
protected readonly string $disposition,
protected readonly string|null $fileName = null,
) {
}
public function getStatusCode(): int
{
return $this->response->getStatusCode();
}
public function getHeaders(): ResponseHeaderBag
{
return $this->response->getHeaders();
}
public function getFileName(): string|null
{
return $this->response->getFileName();
}
/**
* @return non-negative-int|null
*/
public function getContentLength(): int|null
{
return $this->response->getContentLength();
}
public function getTrace(): string
{
return $this->response->getHeaders()->get('Gotenberg-Trace', '');
}
public function process(): mixed
{
if (!$this->response->getStream()->valid()) {
throw new ProcessorException('Already processed query.');
}
foreach ($this->response->getStream() as $chunk) {
$this->processorGenerator->send($chunk);
}
return $this->processorGenerator->getReturn();
}
public function stream(): StreamedResponse
{
$headers = $this->getHeaders();
$headers->set('X-Accel-Buffering', 'no'); // See https://symfony.com/doc/current/components/http_foundation.html#streaming-a-json-response
if (null !== $this->fileName) {
$headers->set('Content-Disposition', HeaderUtils::makeDisposition($this->disposition, $this->fileName));
}
return new StreamedResponse(
function (): void {
if (!$this->response->getStream()->valid()) {
throw new ProcessorException('Already processed query.');
}
foreach ($this->response->getStream() as $chunk) {
$this->processorGenerator->send($chunk);
echo $chunk->getContent();
flush();
}
},
$this->response->getStatusCode(),
$headers->all(),
);
}
}