Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
19 / 19 |
|
100.00% |
6 / 6 |
CRAP | |
100.00% |
1 / 1 |
| MimeService | |
100.00% |
19 / 19 |
|
100.00% |
6 / 6 |
10 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| setMimeType | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| getMimeType | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| getExtension | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
4 | |||
| reset | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getCurrentMimeType | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | /** |
| 6 | * SPDX-FileCopyrightText: 2025 LibreCode coop and contributors |
| 7 | * SPDX-License-Identifier: AGPL-3.0-or-later |
| 8 | */ |
| 9 | |
| 10 | namespace OCA\Libresign\Service\File; |
| 11 | |
| 12 | use OCA\Libresign\Service\Validation\FileInputValidator; |
| 13 | use OCP\Files\IMimeTypeDetector; |
| 14 | |
| 15 | class MimeService { |
| 16 | private ?string $mimetype = null; |
| 17 | |
| 18 | public function __construct( |
| 19 | private IMimeTypeDetector $mimeTypeDetector, |
| 20 | private FileInputValidator $fileInputValidator, |
| 21 | ) { |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Set and validate a MIME type |
| 26 | * |
| 27 | * @throws \Exception if MIME type is not accepted |
| 28 | */ |
| 29 | public function setMimeType(string $mimetype): void { |
| 30 | $this->fileInputValidator->validateMimeTypeAcceptedByMime($mimetype); |
| 31 | $this->mimetype = $mimetype; |
| 32 | } |
| 33 | |
| 34 | public function getMimeType(string $content): string { |
| 35 | if ($this->mimetype === null) { |
| 36 | $detected = $this->mimeTypeDetector->detectString($content); |
| 37 | $this->setMimeType($detected); |
| 38 | } |
| 39 | // After setMimeType, mimetype is guaranteed to be non-null |
| 40 | // (or an exception was thrown) |
| 41 | assert($this->mimetype !== null); |
| 42 | return $this->mimetype; |
| 43 | } |
| 44 | |
| 45 | public function getExtension(string $content): string { |
| 46 | $mimetype = $this->getMimeType($content); |
| 47 | $mappings = $this->mimeTypeDetector->getAllMappings(); |
| 48 | |
| 49 | foreach ($mappings as $ext => $mimetypes) { |
| 50 | $ext = (string)$ext; |
| 51 | // Skip internal mappings starting with underscore |
| 52 | if ($ext[0] === '_') { |
| 53 | continue; |
| 54 | } |
| 55 | if (in_array($mimetype, $mimetypes)) { |
| 56 | return $ext; |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return ''; |
| 61 | } |
| 62 | |
| 63 | public function reset(): void { |
| 64 | $this->mimetype = null; |
| 65 | } |
| 66 | |
| 67 | public function getCurrentMimeType(): ?string { |
| 68 | return $this->mimetype; |
| 69 | } |
| 70 | } |