-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathDefaultBuilderTrait.php
253 lines (203 loc) · 7.34 KB
/
DefaultBuilderTrait.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
<?php
namespace Sensiolabs\GotenbergBundle\Builder;
use Psr\Log\LoggerInterface;
use Sensiolabs\GotenbergBundle\Client\GotenbergClientInterface;
use Sensiolabs\GotenbergBundle\Exception\JsonEncodingException;
use Sensiolabs\GotenbergBundle\Formatter\AssetBaseDirFormatter;
use Sensiolabs\GotenbergBundle\Processor\NullProcessor;
use Sensiolabs\GotenbergBundle\Processor\ProcessorInterface;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\HeaderUtils;
use Symfony\Component\Mime\Part\DataPart;
trait DefaultBuilderTrait
{
private readonly GotenbergClientInterface $client;
protected readonly AssetBaseDirFormatter $asset;
/**
* @var array<string, mixed>
*/
protected array $formFields = [];
/**
* @var array<string, (\Closure(mixed): array<string, array<string|int, mixed>|string|\Stringable|int|float|bool|\BackedEnum|DataPart>)>
*/
private array $normalizers = [];
private string|null $fileName = null;
private string $headerDisposition = HeaderUtils::DISPOSITION_INLINE;
protected LoggerInterface|null $logger = null;
/** @var ProcessorInterface<mixed>|null */
private ProcessorInterface|null $processor;
/**
* @var \Closure(): string
*/
private \Closure $traceGenerator;
public function setLogger(LoggerInterface|null $logger): void
{
$this->logger = $logger;
}
/**
* @param (\Closure(mixed): array<string, array<string|int, mixed>|string|\Stringable|int|float|bool|\BackedEnum|DataPart>) $normalizer
*/
protected function addNormalizer(string $key, \Closure $normalizer): void
{
$this->normalizers[$key] = $normalizer;
}
/**
* @return array<string, mixed>
*/
protected function encodeData(string $key, mixed $value): array
{
try {
$encodedValue = json_encode($value, \JSON_THROW_ON_ERROR);
} catch (\JsonException $exception) {
throw new JsonEncodingException(\sprintf('Could not encode property "%s" into JSON', $key), previous: $exception);
}
return [$key => $encodedValue];
}
/**
* @param HeaderUtils::DISPOSITION_* $headerDisposition
*/
public function fileName(string $fileName, string $headerDisposition = HeaderUtils::DISPOSITION_INLINE): static
{
$this->fileName = $fileName;
$this->headerDisposition = $headerDisposition;
return $this;
}
/**
* @param ProcessorInterface<mixed> $processor
*/
public function processor(ProcessorInterface $processor): static
{
$this->processor = $processor;
return $this;
}
/**
* The Gotenberg API endpoint path.
*/
abstract protected function getEndpoint(): string;
/**
* @param array<string, mixed> $configurations
*/
abstract public function setConfigurations(array $configurations): static;
/**
* @param non-empty-list<string> $validExtensions eg: ['png', 'jpeg']
*/
protected function assertFileExtension(string $path, array $validExtensions): void
{
$file = new File($this->asset->resolve($path));
$extension = $file->getExtension();
if (!\in_array($extension, $validExtensions, true)) {
throw new \InvalidArgumentException(\sprintf('The file extension "%s" is not valid in this context.', $extension));
}
}
/**
* Compiles the form values into a multipart form data array to send to the HTTP client.
*
* @return array<int, array<string, string>>
*/
public function getMultipartFormData(): array
{
$multipartFormData = [];
foreach ($this->formFields as $key => $value) {
if (null === $value) {
$this->logger?->debug('Key {sensiolabs_gotenberg.key} is null, skipping.', [
'sensiolabs_gotenberg.key' => $key,
]);
continue;
}
$preCallback = null;
if (\array_key_exists($key, $this->normalizers)) {
$this->logger?->debug('Normalizer found for key {sensiolabs_gotenberg.key}.', [
'sensiolabs_gotenberg.key' => $key,
]);
$preCallback = $this->normalizers[$key](...);
}
foreach ($this->convertToMultipartItems($key, $value, $preCallback) as $multiPart) {
$multipartFormData[] = $multiPart;
}
}
return $multipartFormData;
}
/**
* @param array<int|string, mixed>|string|\Stringable|int|float|bool|\BackedEnum|DataPart $value
*
* @return list<array<string, mixed>>
*/
private function convertToMultipartItems(string $key, array|string|\Stringable|int|float|bool|\BackedEnum|DataPart $value, \Closure|null $preCallback = null): array
{
if (null !== $preCallback) {
$result = [];
foreach ($preCallback($value) as $innerKey => $innerValue) {
$result[] = $this->convertToMultipartItems($innerKey, $innerValue);
}
return array_merge(...$result);
}
if (\is_bool($value)) {
return [[
$key => $value ? 'true' : 'false',
]];
}
if (\is_int($value)) {
return [[
$key => (string) $value,
]];
}
if (\is_float($value)) {
[$left, $right] = sscanf((string) $value, '%d.%s') ?? [$value, ''];
$right ??= '0';
return [[
$key => "{$left}.{$right}",
]];
}
if ($value instanceof \BackedEnum) {
return [[
$key => (string) $value->value,
]];
}
if ($value instanceof \Stringable) {
return [[
$key => (string) $value,
]];
}
if (\is_array($value)) {
$result = [];
foreach ($value as $nestedValue) {
$result[] = $this->convertToMultipartItems($key, $nestedValue);
}
return array_merge(...$result);
}
return [[
$key => $value,
]];
}
public function generate(): GotenbergFileResult
{
$this->traceGenerator ??= $this::defaultTraceGenerator(...);
$trace = ($this->traceGenerator)();
$headers = ['Gotenberg-Trace' => $trace];
$this->logger?->debug('Processing file with trace "{sensiolabs_gotenberg.trace}" using {sensiolabs_gotenberg.builder} builder.', [
'sensiolabs_gotenberg.trace' => $trace,
'sensiolabs_gotenberg.builder' => $this::class,
]);
$processor = $this->processor ?? new NullProcessor();
return new GotenbergFileResult(
$this->client->call($this->getEndpoint(), $this->getMultipartFormData(), $headers),
$processor($this->fileName),
$this->headerDisposition,
$this->fileName,
);
}
/**
* Sets the callable that will generate the trace ID for each operation.
*
* @param \Closure(): string $traceGenerator
*/
public function traceGenerator(\Closure $traceGenerator): static
{
$this->traceGenerator = $traceGenerator;
return $this;
}
protected static function defaultTraceGenerator(): string
{
return bin2hex(random_bytes(16)).microtime(true);
}
}