diff --git a/composer.json b/composer.json index 310601c..9b2e1f9 100644 --- a/composer.json +++ b/composer.json @@ -19,12 +19,12 @@ "php": ">8.2", "ext-sodium": "*", "ext-ctype": "*", - "ext-zip": "*" + "ext-zip": "*", + "ext-fileinfo": "*" }, "require-dev": { "phpunit/phpunit": "^10", "squizlabs/php_codesniffer": "^3.7", - "symfony/dotenv": "^6.3", - "ext-fileinfo": "*" + "symfony/dotenv": "^6.3" } } diff --git a/src/FileHandler.php b/src/FileHandler.php index 30c70ec..abd5c07 100644 --- a/src/FileHandler.php +++ b/src/FileHandler.php @@ -2,6 +2,7 @@ namespace rcsofttech85\FileHandler; +use finfo; use Generator; use rcsofttech85\FileHandler\Exception\FileHandlerException; use ZipArchive; @@ -69,6 +70,24 @@ public function compress(string $filename, string $zipFilename): void $zip->close(); } + /** + * @throws FileHandlerException + */ + public function getMimeType(string $filename): string + { + if (!file_exists($filename)) { + throw new FileHandlerException('file does not exist.'); + } + + $fileInfo = new finfo(FILEINFO_MIME_TYPE); + $mimeType = $fileInfo->file($filename); + if (!$mimeType) { + throw new FileHandlerException('unknown mime type'); + } + + return $mimeType; + } + /** * @throws FileHandlerException */ diff --git a/tests/unit/FileHandlerTest.php b/tests/unit/FileHandlerTest.php index 8b39348..371e064 100644 --- a/tests/unit/FileHandlerTest.php +++ b/tests/unit/FileHandlerTest.php @@ -2,7 +2,6 @@ namespace unit; -use finfo; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\Attributes\TestDox; @@ -135,6 +134,7 @@ public function studioIsFoundForExactNameMatch(string $keyword) $this->assertTrue($isStudioFound); } + #[Test] public function successfulCompression() { @@ -143,13 +143,22 @@ public function successfulCompression() $this->fileHandler->compress($testFile, $compressedZipFilename); - $fileInfo = new finfo(FILEINFO_MIME_TYPE); - $mimeType = $fileInfo->file($compressedZipFilename); + $mimeType = $this->fileHandler->getMimeType($compressedZipFilename); $this->assertFileExists($compressedZipFilename); $this->assertEquals('application/zip', $mimeType); } + #[Test] + public function getMimeTypeFunctionReturnsCorrectInfo() + { + $csvFile = $this->fileHandler->getMimeType("movie.csv"); + $zipFile = $this->fileHandler->getMimeType("compressed.zip"); + + $this->assertEquals("text/csv", $csvFile); + $this->assertEquals('application/zip', $zipFile); + } + #[Test] public function successfulDecompression() {