• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

nepada / file-upload-control / 27069805852

06 Jun 2026 06:01PM UTC coverage: 81.716%. Remained the same
27069805852

push

github

xificurk
Update phpstan baseline

724 of 886 relevant lines covered (81.72%)

0.82 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

81.03
/src/FileUploadControl/FileUploadControl.php
1
<?php
2
declare(strict_types = 1);
3

4
namespace Nepada\FileUploadControl;
5

6
use Nepada\FileUploadControl\Responses\ListResponse;
7
use Nepada\FileUploadControl\Responses\Response;
8
use Nepada\FileUploadControl\Responses\UploadErrorResponse;
9
use Nepada\FileUploadControl\Responses\UploadSuccessResponse;
10
use Nepada\FileUploadControl\Storage\ContentRange;
11
use Nepada\FileUploadControl\Storage\FailedUpload;
12
use Nepada\FileUploadControl\Storage\FileUploadChunk;
13
use Nepada\FileUploadControl\Storage\FileUploadId;
14
use Nepada\FileUploadControl\Storage\FileUploadItem;
15
use Nepada\FileUploadControl\Storage\FileUploadNotFoundException;
16
use Nepada\FileUploadControl\Storage\Storage;
17
use Nepada\FileUploadControl\Storage\StorageDoesNotExistException;
18
use Nepada\FileUploadControl\Storage\StorageManager;
19
use Nepada\FileUploadControl\Storage\UnableToSaveFileUploadException;
20
use Nepada\FileUploadControl\Storage\UploadNamespace;
21
use Nepada\FileUploadControl\Thumbnail\NullThumbnailProvider;
22
use Nepada\FileUploadControl\Thumbnail\ThumbnailProvider;
23
use Nepada\FileUploadControl\Validation\ClientSide;
24
use Nepada\FileUploadControl\Validation\FakeUploadControl;
25
use Nepada\FileUploadControl\Validation\UploadValidation;
26
use Nette;
27
use Nette\Bridges\ApplicationLatte\Template;
28
use Nette\Forms\Form;
29
use Nette\Http\FileUpload;
30
use Nette\Utils\Arrays;
31
use Nette\Utils\Html;
32
use Stringable;
33
use function implode;
34

35
class FileUploadControl extends BaseControl
36
{
37

38
    use UploadValidation {
39
        UploadValidation::addRule as private _addRule;
40
    }
41

42
    final public const TEMPLATE_FILE_BOOTSTRAP4 = __DIR__ . '/templates/bootstrap4.latte';
43
    final public const TEMPLATE_FILE_BOOTSTRAP5 = __DIR__ . '/templates/bootstrap5.latte';
44
    final public const DEFAULT_TEMPLATE_FILE = self::TEMPLATE_FILE_BOOTSTRAP4;
45

46
    private string $templateFile = self::DEFAULT_TEMPLATE_FILE;
47

48
    private StorageManager $storageManager;
49

50
    private ThumbnailProvider $thumbnailProvider;
51

52
    private bool $httpDataLoaded = false;
53

54
    public function __construct(StorageManager $storageManager, string|\Stringable|null $caption = null)
1✔
55
    {
56
        parent::__construct($caption);
1✔
57
        $this->storageManager = $storageManager;
1✔
58
        $this->thumbnailProvider = new NullThumbnailProvider();
1✔
59
        $this->control = Html::el();
1✔
60
        $this->setOption('type', 'file-upload');
1✔
61
        $this->addComponent(new Nette\Forms\Controls\UploadControl($caption, true), 'upload');
1✔
62
        $this->addComponent(new Nette\Forms\Controls\HiddenField(), 'namespace');
1✔
63
        $this->initializeValidation($this);
1✔
64
        /** @var string $errorMessage */
65
        $errorMessage = Nette\Forms\Validator::$messages[Nette\Forms\Controls\UploadControl::Valid];
1✔
66
        $this->addCondition(fn () => $this->getPresenterIfExists()?->isSignalReceiver($this, 'upload') !== true) // disable during file upload via signal
1✔
67
            ->addRule($this->validateUploadSuccess(...), $errorMessage);
1✔
68
        $this->addRule(ClientSide::NO_UPLOAD_IN_PROGRESS, 'File upload is still in progress - wait until it is finished, or abort it.');
1✔
69
    }
1✔
70

71
    private function validateUploadSuccess(FakeUploadControl $control): bool
1✔
72
    {
73
        return Arrays::every($control->getValue(), fn (FileUpload $upload): bool => $upload->isOk());
1✔
74
    }
75

76
    public function setThumbnailProvider(ThumbnailProvider $thumbnailProvider): void
1✔
77
    {
78
        $this->thumbnailProvider = $thumbnailProvider;
1✔
79
    }
1✔
80

81
    public function setTemplateFile(string $templateFile): void
1✔
82
    {
83
        $this->templateFile = $templateFile;
1✔
84
    }
1✔
85

86
    /**
87
     * @throws Nette\Application\BadRequestException
88
     */
89
    public function loadHttpData(): void
90
    {
91
        $this->getNamespaceControl()->loadHttpData();
1✔
92
        try {
93
            $storage = $this->getStorage();
1✔
94
        } catch (StorageDoesNotExistException $exception) {
×
95
            // refresh namespace
96
            $this->setUploadNamespace($this->storageManager->createNewNamespace());
×
97
            try {
98
                $storage = $this->getStorage();
×
99
            } catch (StorageDoesNotExistException $exception) {
×
100
                throw new \LogicException($exception->getMessage(), 0, $exception);
×
101
            }
102
        }
103

104
        if ($this->httpDataLoaded || $this->isDisabled()) {
1✔
105
            return;
×
106
        }
107

108
        $this->httpDataLoaded = true;
1✔
109

110
        $fileUploadChunks = $this->getFileUploadChunks();
1✔
111
        if (count($fileUploadChunks) === 0) {
1✔
112
            return;
1✔
113
        }
114

115
        $uploadFailed = false;
1✔
116
        foreach ($fileUploadChunks as $fileUploadChunk) {
1✔
117
            if ($fileUploadChunk instanceof FailedUpload) {
1✔
118
                $uploadFailed = true;
1✔
119
                continue;
1✔
120
            }
121
            try {
122
                $storage->save($fileUploadChunk);
1✔
123
            } catch (UnableToSaveFileUploadException $exception) {
×
124
                $uploadFailed = true;
×
125
            }
126
        }
127
        if ($uploadFailed) {
1✔
128
            /** @var string $errorMessage */
129
            $errorMessage = Nette\Forms\Validator::$messages[Nette\Forms\Controls\UploadControl::Valid];
1✔
130
            $this->addError($errorMessage);
1✔
131
        }
132
    }
1✔
133

134
    /**
135
     * @return list<FileUpload>
136
     */
137
    public function getValue(): array
138
    {
139
        if ($this->isDisabled()) {
1✔
140
            return [];
1✔
141
        }
142

143
        try {
144
            return array_map(fn (FileUploadItem $fileUploadItem): FileUpload => $fileUploadItem->fileUpload, $this->getStorage()->list());
1✔
145
        } catch (StorageDoesNotExistException $exception) {
×
146
            throw new \LogicException($exception->getMessage(), 0, $exception);
×
147
        }
148
    }
149

150
    /**
151
     * @return $this
152
     * @internal
153
     */
154
    public function setValue(mixed $value): static
1✔
155
    {
156
        return $this;
1✔
157
    }
158

159
    public function isDisabled(): bool
160
    {
161
        return $this->getUploadControl()->isDisabled();
1✔
162
    }
163

164
    /**
165
     * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint
166
     * @param bool $value
167
     * @return $this
168
     * @throws Nette\Application\BadRequestException
169
     */
170
    public function setDisabled($value = true): static
1✔
171
    {
172
        $this->getUploadControl()->setDisabled($value);
1✔
173
        if (! $value) {
1✔
174
            return $this;
×
175
        }
176

177
        $form = $this->getForm(false);
1✔
178
        if ($form !== null && $form->isAnchored() && (bool) $form->isSubmitted()) {
1✔
179
            $this->loadHttpData();
×
180
        }
181

182
        return $this;
1✔
183
    }
184

185
    public function getControlPart(?string $key = null): ?Html
1✔
186
    {
187
        if ($key === 'namespace') {
1✔
188
            return $this->getNamespaceControl()->getControl();
1✔
189
        }
190

191
        if ($key === 'upload') {
1✔
192
            $control = $this->getUploadControl()->getControl();
1✔
193
            assert($control instanceof Html);
1✔
194
            $control->{'data-nette-rules'} = Nette\Forms\Helpers::exportRules($this->getRules());
1✔
195
            return $control;
1✔
196
        }
197

198
        return $this->getControl();
×
199
    }
200

201
    public function getControl(): Html
202
    {
203
        $this->setOption('rendered', true);
1✔
204
        $control = clone $this->control;
1✔
205

206
        $template = $this->getTemplate();
1✔
207
        assert($template instanceof Template);
1✔
208

209
        try {
210
            $storage = $this->getStorage();
1✔
211
        } catch (StorageDoesNotExistException $exception) {
×
212
            throw new \LogicException($exception->getMessage(), 0, $exception);
×
213
        }
214
        $fileUploadItems = $storage->list();
1✔
215

216
        $uniqueFilenames = array_map(fn (FileUploadItem $fileUploadItem): string => $fileUploadItem->fileUpload->getUntrustedName(), $fileUploadItems);
1✔
217
        $completedFiles = [];
1✔
218
        $partiallyUploadedFiles = [];
1✔
219
        foreach ($fileUploadItems as $fileUploadItem) {
1✔
220
            if ($fileUploadItem->fileUpload->isOk()) {
1✔
221
                $completedFiles[] = $this->createUploadSuccessResponse($fileUploadItem);
1✔
222
            } else {
223
                $partiallyUploadedFiles[] = $this->createUploadSuccessResponse($fileUploadItem);
1✔
224
            }
225
        }
226

227
        $template->uniqueFilenames = $uniqueFilenames;
1✔
228
        $template->completedFiles = $completedFiles;
1✔
229
        $template->partiallyUploadedFiles = $partiallyUploadedFiles;
1✔
230
        $template->allFiles = array_merge($completedFiles, $partiallyUploadedFiles);
1✔
231
        $template->uploadUrl = $this->link('upload!', ['namespace' => $this->getUploadNamespace()->toString()]);
1✔
232

233
        $controlHtml = Nette\Utils\Helpers::capture(function () use ($template): void {
1✔
234
            $template->render($this->templateFile);
1✔
235
        });
1✔
236
        return $control->addHtml($controlHtml);
1✔
237
    }
238

239
    public function getLabelPrototype(): Html
240
    {
241
        return $this->getUploadControl()->getLabelPrototype();
1✔
242
    }
243

244
    public function getLabel(string|Stringable|null $caption = null): Html
1✔
245
    {
246
        $label = $this->getUploadControl()->getLabel($caption);
1✔
247
        assert($label instanceof Html);
1✔
248
        return $label;
1✔
249
    }
250

251
    /**
252
     * @return $this
253
     */
254
    public function addRule(callable|string $validator, string|Stringable|null $errorMessage = null, mixed $arg = null): static
1✔
255
    {
256
        if ($validator === Form::Image) {
1✔
257
            $this->getUploadControl()->setHtmlAttribute('accept', implode(',', Nette\Forms\Helpers::getSupportedImages()));
1✔
258
        } elseif ($validator === Form::MimeType) {
1✔
259
            $mimeTypes = is_array($arg) ? $arg : ($arg === null ? [] : [$arg]);
1✔
260
            $this->getUploadControl()->setHtmlAttribute('accept', implode(',', $mimeTypes));
1✔
261
        }
262

263
        return $this->_addRule($validator, $errorMessage, $arg);
1✔
264
    }
265

266
    /**
267
     * @throws Nette\Application\BadRequestException
268
     */
269
    public function handleUpload(string $namespace): void
1✔
270
    {
271
        $uploadNamespace = $this->parseUploadNamespace($namespace);
1✔
272
        $this->setUploadNamespace($uploadNamespace);
1✔
273

274
        $fileUploadChunks = $this->getFileUploadChunks();
1✔
275
        $responses = [];
1✔
276
        foreach ($fileUploadChunks as $fileUploadChunk) {
1✔
277
            if ($this->isDisabled()) {
1✔
278
                $responses[] = $this->createUploadErrorResponse($fileUploadChunk, $this->translate('Upload disabled'));
1✔
279
                continue;
1✔
280
            }
281

282
            if ($fileUploadChunk instanceof FailedUpload) {
1✔
283
                $responses[] = $this->createUploadErrorResponse($fileUploadChunk, $this->translate(Nette\Forms\Validator::$messages[Nette\Forms\Controls\UploadControl::Valid]));
1✔
284
                continue;
1✔
285
            }
286

287
            if ($fileUploadChunk->contentRange->containsFirstByte()) {
1✔
288
                $fakeFileUpload = new FileUpload([
1✔
289
                    'name' => $fileUploadChunk->fileUpload->getUntrustedName(),
1✔
290
                    'size' => $fileUploadChunk->contentRange->getSize(),
1✔
291
                    'tmp_name' => $fileUploadChunk->fileUpload->getTemporaryFile(),
1✔
292
                    'error' => UPLOAD_ERR_OK,
1✔
293
                ]);
294
                $this->fakeUploadControl->setNewFileUpload($fakeFileUpload);
1✔
295
                $this->validate();
1✔
296
                $error = $this->getError();
1✔
297
                if ($error !== null) {
1✔
298
                    $responses[] = $this->createUploadErrorResponse($fileUploadChunk, $error);
1✔
299
                    continue;
1✔
300
                }
301
            }
302

303
            try {
304
                $fileUploadItem = $this->getStorage()->save($fileUploadChunk);
1✔
305
                $responses[] = $this->createUploadSuccessResponse($fileUploadItem);
1✔
306
            } catch (StorageDoesNotExistException | UnableToSaveFileUploadException $exception) {
×
307
                $responses[] = $this->createUploadErrorResponse($fileUploadChunk, $this->translate(Nette\Forms\Validator::$messages[Nette\Forms\Controls\UploadControl::Valid]));
×
308
            }
309
        }
310

311
        $this->sendJson(new ListResponse(...$responses));
1✔
312
    }
313

314
    /**
315
     * @throws Nette\Application\BadRequestException
316
     */
317
    public function handleDelete(string $namespace, string $id): void
318
    {
319
        $fileUploadId = $this->parseFileUploadId($id);
×
320
        $uploadNamespace = $this->parseUploadNamespace($namespace);
×
321
        $this->setUploadNamespace($uploadNamespace);
×
322

323
        try {
324
            $this->getStorage()->delete($fileUploadId);
×
325
        } catch (StorageDoesNotExistException $exception) {
×
326
            // noop
327
        }
328
        $this->sendJson('');
×
329
    }
330

331
    /**
332
     * @throws Nette\Application\BadRequestException
333
     */
334
    public function handleDownload(string $namespace, string $id): void
1✔
335
    {
336
        $fileUploadId = $this->parseFileUploadId($id);
1✔
337
        $uploadNamespace = $this->parseUploadNamespace($namespace);
1✔
338
        $this->setUploadNamespace($uploadNamespace);
1✔
339

340
        try {
341
            $fileUploadItem = $this->getStorage()->load($fileUploadId);
1✔
342
        } catch (StorageDoesNotExistException | FileUploadNotFoundException $exception) {
×
343
            throw new Nette\Application\BadRequestException('File upload not found.', 0, $exception);
×
344
        }
345

346
        $fileUpload = $fileUploadItem->fileUpload;
1✔
347
        $response = new Nette\Application\Responses\FileResponse(
1✔
348
            $fileUpload->getTemporaryFile(),
1✔
349
            $fileUpload->getUntrustedName(),
1✔
350
        );
351
        $this->getPresenter()->sendResponse($response);
1✔
352
    }
353

354
    /**
355
     * @throws Nette\Application\BadRequestException
356
     */
357
    public function handleThumbnail(string $namespace, string $id): void
358
    {
359
        $fileUploadId = $this->parseFileUploadId($id);
×
360
        $uploadNamespace = $this->parseUploadNamespace($namespace);
×
361
        $this->setUploadNamespace($uploadNamespace);
×
362

363
        try {
364
            $fileUpload = $this->getStorage()->load($fileUploadId)->fileUpload;
×
365
        } catch (StorageDoesNotExistException | FileUploadNotFoundException $exception) {
×
366
            throw new Nette\Application\BadRequestException('Source file for thumbnail not found.', 0, $exception);
×
367
        }
368

369
        if (! $this->thumbnailProvider->isSupported($fileUpload)) {
×
370
            throw new Nette\Application\BadRequestException('Thumbnail could not be generated');
×
371
        }
372

373
        $response = $this->thumbnailProvider->createThumbnail($fileUpload);
×
374
        $this->getPresenter()->sendResponse($response);
×
375
    }
376

377
    /**
378
     * @template T of Template
379
     * @param ?class-string<T>  $class
380
     * @return ($class is null ? Template : T)
381
     */
382
    protected function createTemplate(?string $class = null): Template
1✔
383
    {
384
        $template = parent::createTemplate($class);
1✔
385
        assert($template instanceof Template);
1✔
386

387
        $translator = $this->getTranslator();
1✔
388
        if ($translator !== null) {
1✔
389
            $template->setTranslator($translator);
1✔
390
        }
391

392
        $template->getLatte()->addFilter('json', fn (mixed $data): string => Nette\Utils\Json::encode($data));
1✔
393

394
        return $template;
1✔
395
    }
396

397
    protected function getHttpRequest(): Nette\Http\IRequest
398
    {
399
        return $this->getPresenter()->getHttpRequest();
1✔
400
    }
401

402
    /**
403
     * Sends back JSON response.
404
     * Sets the right content type based on the support on the other end.
405
     * https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#wiki-content-type-negotiation
406
     */
407
    protected function sendJson(mixed $data): void
1✔
408
    {
409
        $contentType = str_contains((string) $this->getHttpRequest()->getHeader('accept'), 'application/json') ? 'application/json' : 'text/plain';
1✔
410
        $response = new Nette\Application\Responses\JsonResponse($data, $contentType);
1✔
411
        $this->getPresenter()->sendResponse($response);
1✔
412
    }
413

414
    protected function getUploadControl(): Nette\Forms\Controls\UploadControl
415
    {
416
        return $this->getComponent('upload');
1✔
417
    }
418

419
    protected function getNamespaceControl(): Nette\Forms\Controls\HiddenField
420
    {
421
        return $this->getComponent('namespace');
1✔
422
    }
423

424
    protected function getThumbnailProvider(): ThumbnailProvider
425
    {
426
        return $this->thumbnailProvider;
×
427
    }
428

429
    protected function getUploadNamespace(): UploadNamespace
430
    {
431
        /** @var string|null $nameSpaceValue */
432
        $nameSpaceValue = $this->getNamespaceControl()->getValue();
1✔
433
        if ($nameSpaceValue !== null && UploadNamespace::isValid($nameSpaceValue)) {
1✔
434
            return UploadNamespace::fromString($nameSpaceValue);
1✔
435
        }
436

437
        $namespace = $this->storageManager->createNewNamespace();
×
438
        $this->setUploadNamespace($namespace);
×
439
        return $namespace;
×
440
    }
441

442
    protected function setUploadNamespace(UploadNamespace $namespace): void
1✔
443
    {
444
        $this->getNamespaceControl()->setValue($namespace->toString());
1✔
445
    }
1✔
446

447
    /**
448
     * @throws StorageDoesNotExistException
449
     */
450
    protected function getStorage(): Storage
451
    {
452
        return $this->storageManager->getStorage($this->getUploadNamespace());
1✔
453
    }
454

455
    protected function createUploadSuccessResponse(FileUploadItem $fileUploadItem): Response
1✔
456
    {
457
        $fileUpload = $fileUploadItem->fileUpload;
1✔
458
        $idValue = $fileUploadItem->id->toString();
1✔
459
        $namespaceValue = $this->getUploadNamespace()->toString();
1✔
460
        return new UploadSuccessResponse(
1✔
461
            $fileUpload->getUntrustedName(),
1✔
462
            $fileUpload->getSize(),
1✔
463
            $fileUpload->getContentType(),
1✔
464
            $this->link('download!', ['namespace' => $namespaceValue, 'id' => $idValue]),
1✔
465
            $this->link('delete!', ['namespace' => $namespaceValue, 'id' => $idValue]),
1✔
466
            $this->thumbnailProvider->isSupported($fileUpload) ? $this->link('thumbnail!', ['namespace' => $namespaceValue, 'id' => $idValue]) : null,
1✔
467
        );
468
    }
469

470
    protected function createUploadErrorResponse(FileUploadChunk|FailedUpload $upload, string $error): Response
1✔
471
    {
472
        return new UploadErrorResponse(
1✔
473
            $upload->fileUpload->getUntrustedName(),
1✔
474
            $upload->contentRange?->getSize() ?? 0,
1✔
475
            $error,
476
        );
477
    }
478

479
    /**
480
     * @throws Nette\Application\BadRequestException
481
     */
482
    protected function parseUploadNamespace(string $value): UploadNamespace
1✔
483
    {
484
        if (! UploadNamespace::isValid($value)) {
1✔
485
            throw new Nette\Application\BadRequestException('Invalid namespace value', 400);
×
486
        }
487
        return UploadNamespace::fromString($value);
1✔
488
    }
489

490
    /**
491
     * @throws Nette\Application\BadRequestException
492
     */
493
    protected function parseFileUploadId(string $value): FileUploadId
1✔
494
    {
495
        if (! FileUploadId::isValid($value)) {
1✔
496
            throw new Nette\Application\BadRequestException('Invalid file upload id value', 400);
×
497
        }
498
        return FileUploadId::fromString($value);
1✔
499
    }
500

501
    /**
502
     * @return list<FileUploadChunk|FailedUpload>
503
     * @throws Nette\Application\BadRequestException
504
     */
505
    protected function getFileUploadChunks(): array
506
    {
507
        $httpRequest = $this->getHttpRequest();
1✔
508
        /** @var array<int, FileUpload> $files */
509
        $files = Nette\Forms\Helpers::extractHttpData($httpRequest->getFiles(), $this->getUploadControl()->getHtmlName() . '[]', Form::DataFile);
1✔
510
        if (count($files) === 0) {
1✔
511
            return [];
1✔
512
        }
513

514
        $contentRangeHeaderValue = $httpRequest->getHeader('content-range');
1✔
515
        if ($contentRangeHeaderValue !== null) {
1✔
516
            if (count($files) > 1) {
1✔
517
                throw new Nette\Application\BadRequestException('Chunk upload does not support multi-file upload', 400);
×
518
            }
519
            $file = reset($files);
1✔
520

521
            try {
522
                $contentRange = ContentRange::fromHttpHeaderValue($contentRangeHeaderValue);
1✔
523
                $fileUpload = $file->isOk() ? FileUploadChunk::partialUpload($file, $contentRange) : FailedUpload::of($file, $contentRange);
1✔
524
                return [$fileUpload];
1✔
525
            } catch (\Throwable $exception) {
×
526
                throw new Nette\Application\BadRequestException('Invalid content-range header value', 400, $exception);
×
527
            }
528
        }
529

530
        /** @var list<FileUploadChunk|FailedUpload> $fileUploads */
531
        $fileUploads = [];
1✔
532
        foreach ($files as $file) {
1✔
533
            $fileUploads[] = $file->isOk() ? FileUploadChunk::completeUpload($file) : FailedUpload::of($file);
1✔
534
        }
535

536
        return $fileUploads;
1✔
537
    }
538

539
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc