From bfa5a5ff52ab432a966070c6af19701293dd1e66 Mon Sep 17 00:00:00 2001 From: rahul Date: Mon, 18 Sep 2023 18:27:22 +0530 Subject: [PATCH] phpstan support Signed-off-by: rahul --- phpstan.neon | 6 +++ src/CsvFileHandler.php | 62 ++++++++++++++++++++--- src/FileEncryptor.php | 9 ++++ src/FileHandler.php | 29 +++-------- src/FileHashChecker.php | 7 ++- src/StreamHandler.php | 21 +++++--- src/TempFileHandler.php | 27 ++++++++-- tests/Base/BaseTest.php | 23 ++++++++- tests/Integration/FileDiffCommandTest.php | 17 +++++-- tests/Integration/StreamHandlerTest.php | 43 ++++++++++------ tests/unit/CsvFileHandlerTest.php | 46 ++++++++++++----- tests/unit/FileEncryptorTest.php | 12 ++--- tests/unit/FileHandlerTest.php | 18 +++---- tests/unit/FileHashCheckerTest.php | 24 ++------- tests/unit/TempFileHandlerTest.php | 3 ++ 15 files changed, 234 insertions(+), 113 deletions(-) create mode 100644 phpstan.neon diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..30348aa --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,6 @@ +parameters: + level: 7 + checkGenericClassInNonGenericObjectType: false + paths: + - src + - tests \ No newline at end of file diff --git a/src/CsvFileHandler.php b/src/CsvFileHandler.php index 4f8cded..298a09e 100644 --- a/src/CsvFileHandler.php +++ b/src/CsvFileHandler.php @@ -12,6 +12,14 @@ public function __construct( ) { } + /** + * @param string $filename + * @param string $keyword + * @param string $column + * @param string|null $format + * @return bool|array + * @throws FileHandlerException + */ public function searchInCsvFile( string $filename, string $keyword, @@ -32,13 +40,18 @@ public function searchInCsvFile( } - public function toJson(string $filename): string + public function toJson(string $filename): string|false { $data = $this->toArray($filename); return json_encode($data); } + /** + * @param string $filename + * @return array> + * @throws FileHandlerException + */ public function toArray(string $filename): array { if (!file_exists($filename)) { @@ -61,6 +74,9 @@ public function findAndReplaceInCsv( } $tempFilePath = $this->tempFileHandler->createTempFileWithHeaders($headers); + if (!$tempFilePath) { + return false; + } try { @@ -86,6 +102,11 @@ public function findAndReplaceInCsv( return true; } + /** + * @param mixed $file + * @return array|false + */ + private function extractHeader(mixed $file): array|false { $headers = []; @@ -93,15 +114,12 @@ private function extractHeader(mixed $file): array|false $headers = fgetcsv($file); } if (is_string($file)) { - if (!file_exists($file)) { + $file = fopen($file, 'r'); + if (!$file) { return false; } - try { - $file = fopen($file, 'r'); - $headers = fgetcsv($file); - } finally { - fclose($file); - } + $headers = fgetcsv($file); + fclose($file); } if (!$headers) { @@ -116,6 +134,10 @@ private function extractHeader(mixed $file): array|false return $headers; } + /** + * @param array $row + * @return bool + */ private function isValidCsvFileFormat(array $row): bool { if (count($row) <= 1) { @@ -124,10 +146,21 @@ private function isValidCsvFileFormat(array $row): bool return true; } + /** + * @param string $filename + * @return Generator + * @throws FileHandlerException + */ private function getRows(string $filename): Generator { $csvFile = fopen($filename, 'r'); + if (!$csvFile) { + throw new FileHandlerException('file not found'); + } $headers = $this->extractHeader($csvFile); + if (!is_array($headers)) { + throw new FileHandlerException('could not extract header'); + } $isEmptyFile = true; @@ -151,6 +184,12 @@ private function getRows(string $filename): Generator } } + /** + * @param array $row + * @param string $keyword + * @param string $replace + * @return int + */ private function replaceKeywordInRow(array &$row, string $keyword, string $replace): int { $count = 0; @@ -164,6 +203,13 @@ private function replaceKeywordInRow(array &$row, string $keyword, string $repla return $count; } + /** + * @param array $row + * @param string $column + * @param string $keyword + * @param string $replace + * @return int + */ private function replaceKeywordInColumn(array &$row, string $column, string $keyword, string $replace): int { $count = 0; diff --git a/src/FileEncryptor.php b/src/FileEncryptor.php index a0dde05..8629889 100644 --- a/src/FileEncryptor.php +++ b/src/FileEncryptor.php @@ -47,6 +47,9 @@ public function encryptFile(): bool $output = bin2hex($nonce . $ciphertext); $file = fopen($this->filename, 'w'); + if (!$file) { + return false; + } try { fwrite($file, $output); @@ -76,6 +79,9 @@ public function decryptFile(): bool } $bytes = hex2bin($encryptedData); + if (!$bytes) { + return false; + } $nonce = substr($bytes, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $ciphertext = substr($bytes, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); @@ -89,6 +95,9 @@ public function decryptFile(): bool $file = fopen($this->filename, 'w'); + if (!$file) { + return false; + } try { fwrite($file, $plaintext); diff --git a/src/FileHandler.php b/src/FileHandler.php index 5067053..73a7490 100644 --- a/src/FileHandler.php +++ b/src/FileHandler.php @@ -10,17 +10,17 @@ class FileHandler { public const ARRAY_FORMAT = 'array'; + /** + * @var array|null + */ private null|array $files = []; - /** - * @throws FileHandlerException - */ public function open( string $filename, string $mode = "w", bool $include_path = false, - $context = null + mixed $context = null ): self { $file = fopen($filename, $mode, $include_path, $context); @@ -35,6 +35,9 @@ public function open( /** + * @param string $data + * @param int<0, max>|null $length + * @return void * @throws FileHandlerException */ public function write(string $data, ?int $length = null): void @@ -144,22 +147,4 @@ public function delete(string $filename): void } unlink($filename); } - - - public function getSingleFileProcessing(string|null $filename): mixed - { - if (empty($this->files)) { - if ($filename && file_exists($filename)) { - $this->open($filename); - return $this->files[0]; - } - throw new FileHandlerException("No files to process or file not found: $filename"); - } - if (count($this->files) > 1) { - throw new FileHandlerException("Multiple files not allowed"); - } - - - return $this->files[0]; - } } diff --git a/src/FileHashChecker.php b/src/FileHashChecker.php index dd08ef1..43e0691 100644 --- a/src/FileHashChecker.php +++ b/src/FileHashChecker.php @@ -6,8 +6,8 @@ class FileHashChecker { - const ALGO_256 = 'sha3-256'; - const ALGO_512 = 'sha3-512'; + public const ALGO_256 = 'sha3-256'; + public const ALGO_512 = 'sha3-512'; /** * @param string $filename @@ -21,7 +21,6 @@ public function __construct(private readonly string $filename, private readonly } /** - * @param object $fileHandler * @param string $storedHashesFile * @param string $algo * @return bool @@ -42,7 +41,7 @@ public function verifyHash(string $storedHashesFile, string $algo = self::ALGO_2 format: FileHandler::ARRAY_FORMAT ); - if (!$file) { + if (!$file || !is_array($file)) { throw new HashException('this file is not hashed'); } diff --git a/src/StreamHandler.php b/src/StreamHandler.php index bf3c94b..bd38f78 100644 --- a/src/StreamHandler.php +++ b/src/StreamHandler.php @@ -8,10 +8,15 @@ class StreamHandler { + /** + * @var array $fibers + */ private array $fibers = []; /** + * @param array $streamUrls + * @param int<0,100> $chunk * @throws StreamException */ public function __construct(public readonly array $streamUrls, public readonly int $chunk = 100) @@ -21,23 +26,27 @@ public function __construct(public readonly array $streamUrls, public readonly i } } - /** - */ + private function stream(string $streamUrl, string $outputFilename): Fiber { return new Fiber(function () use ($streamUrl, $outputFilename) { $stream = fopen($streamUrl, 'r'); - if (!$stream) { + $outputFile = fopen($outputFilename, 'w'); + if (!$stream || !$outputFile) { throw new StreamException("Failed to open stream: $streamUrl"); } + stream_set_blocking($stream, false); - $outputFile = fopen($outputFilename, 'w'); try { while (!feof($stream)) { - $contents = fread($stream, $this->chunk); - fwrite($outputFile, $contents); + $length = $this->chunk; + $contents = fread($stream, $length); + if ($contents) { + fwrite($outputFile, $contents); + } + Fiber::suspend(); } } catch (Throwable $e) { diff --git a/src/TempFileHandler.php b/src/TempFileHandler.php index e54c1e6..5665966 100644 --- a/src/TempFileHandler.php +++ b/src/TempFileHandler.php @@ -20,19 +20,36 @@ public function cleanupTempFile(string $tempFilePath): void } } + /** + * @param string $tempFilePath + * @param array $row + * @return void + */ public function writeRowToTempFile(string $tempFilePath, array $row): void { $tempFileHandle = fopen($tempFilePath, 'a'); - fputs($tempFileHandle, implode(',', $row) . PHP_EOL); - fclose($tempFileHandle); + if ($tempFileHandle) { + fputs($tempFileHandle, implode(',', $row) . PHP_EOL); + fclose($tempFileHandle); + } } - public function createTempFileWithHeaders(array $headers): string + /** + * @param array $headers + * @return string + */ + public function createTempFileWithHeaders(array $headers): string|false { $tempFilePath = tempnam(sys_get_temp_dir(), 'tempfile_'); + if (!$tempFilePath) { + return false; + } $tempFileHandle = fopen($tempFilePath, 'w'); - fputs($tempFileHandle, implode(',', $headers) . PHP_EOL); - fclose($tempFileHandle); + if ($tempFileHandle) { + fputs($tempFileHandle, implode(',', $headers) . PHP_EOL); + fclose($tempFileHandle); + } + return $tempFilePath; } diff --git a/tests/Base/BaseTest.php b/tests/Base/BaseTest.php index 9bcc53b..3b5b7c2 100644 --- a/tests/Base/BaseTest.php +++ b/tests/Base/BaseTest.php @@ -9,9 +9,12 @@ class BaseTest extends TestCase { + /** + * @var array|null + */ protected static array|null $files = []; - protected static ContainerBuilder|null $containerBuilder; + private static ContainerBuilder|null $containerBuilder; public static function setUpBeforeClass(): void { @@ -38,4 +41,22 @@ public static function tearDownAfterClass(): void } static::$files = null; } + + protected function isFileValid(string $filename): mixed + { + if (!file_exists($filename) || !$data = file_get_contents($filename)) { + $this->fail('file does not exists or has no content'); + } + return $data; + } + + protected function setObjectHandler(string $classname, string $serviceId): mixed + { + $objectHandler = self::$containerBuilder->get($serviceId); + + if (!is_a($objectHandler, $classname)) { + $this->fail("provided service is not an instance of " . $classname); + } + return $objectHandler; + } } diff --git a/tests/Integration/FileDiffCommandTest.php b/tests/Integration/FileDiffCommandTest.php index e619b45..8f49507 100644 --- a/tests/Integration/FileDiffCommandTest.php +++ b/tests/Integration/FileDiffCommandTest.php @@ -16,6 +16,9 @@ public static function tearDownAfterClass(): void unlink('old'); } + /** + * @return iterable> + */ public static function commandArgumentProvider(): iterable { file_put_contents("old", "this is old file" . PHP_EOL, FILE_APPEND); @@ -29,7 +32,11 @@ public static function commandArgumentProvider(): iterable yield ['old', 'new', 'old (Line 2):']; } - public static function matchingDataProvider(): iterable + /** + * @return iterable> + */ + + public static function fileWithSameDataProvider(): iterable { file_put_contents("old", "this has matching content" . PHP_EOL, FILE_APPEND); file_put_contents("new", "this has matching content" . PHP_EOL, FILE_APPEND); @@ -40,7 +47,7 @@ public static function matchingDataProvider(): iterable #[Test] #[DataProvider('commandArgumentProvider')] - public function fileDiffShowsCorrectChanges(string $oldFile, string $newFile, string $expected) + public function fileDiffShowsCorrectChanges(string $oldFile, string $newFile, string $expected): void { $command = "php bin/file-diff $oldFile $newFile"; exec($command, $output, $exitCode); @@ -54,7 +61,7 @@ public function fileDiffShowsCorrectChanges(string $oldFile, string $newFile, st } #[Test] - public function throwsExceptionIfArgumentIsNotValidFile() + public function throwsExceptionIfArgumentIsNotValidFile(): void { $command = "php bin/file-diff unknown unknown"; exec($command, $output, $exitCode); @@ -68,8 +75,8 @@ public function throwsExceptionIfArgumentIsNotValidFile() } #[Test] - #[DataProvider('matchingDataProvider')] - public function sameContentShouldNotBeDisplayedInTheResult(string $oldFile, string $newFile, string $expected) + #[DataProvider('fileWithSameDataProvider')] + public function sameContentShouldNotBeDisplayedInTheResult(string $oldFile, string $newFile, string $expected): void { $command = "php bin/file-diff $oldFile $newFile"; exec($command, $output, $exitCode); diff --git a/tests/Integration/StreamHandlerTest.php b/tests/Integration/StreamHandlerTest.php index a4f0bac..3f5fe25 100644 --- a/tests/Integration/StreamHandlerTest.php +++ b/tests/Integration/StreamHandlerTest.php @@ -2,47 +2,54 @@ namespace Integration; +use Base\BaseTest; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\Attributes\Test; -use PHPUnit\Framework\TestCase; use rcsofttech85\FileHandler\Exception\StreamException; use rcsofttech85\FileHandler\StreamHandler; +use Throwable; #[Group("integration")] -class StreamHandlerTest extends TestCase +class StreamHandlerTest extends BaseTest { + public static function setUpBeforeClass(): void + { + parent::setUpBeforeClass(); + static::$files = ["output.html", "output1.html", "output2.html"]; + } + public static function tearDownAfterClass(): void { parent::tearDownAfterClass(); - - $files = ["output.html", "output1.html", "output2.html"]; - - foreach ($files as $file) { - if (file_exists($file)) { - unlink($file); - } - } } + /** + * @param array $urls + * @return void + * @throws StreamException + * @throws Throwable + */ #[Test] #[DataProvider('streamDataProvider')] - public function streamAndWriteToFile($urls) + public function streamAndWriteToFile(array $urls): void { $stream = new StreamHandler($urls); $stream->initiateConcurrentStreams()->start()->resume(); $files = array_keys($urls); foreach ($files as $file) { + $data = $this->isFileValid($file); $this->assertGreaterThan(0, filesize($file)); - $this->assertStringContainsString('', file_get_contents($file)); - $this->assertStringContainsString('', file_get_contents($file)); + $this->assertStringContainsString('', $data); + $this->assertStringContainsString('', $data); } } + #[Test] #[DataProvider('wrongStreamDataProvider')] - public function throwExceptionIfUrlIsInvalid($outputFile, $url) + public function throwExceptionIfUrlIsInvalid(string $outputFile, string $url): void { $stream = new StreamHandler([$outputFile => $url]); @@ -52,19 +59,25 @@ public function throwExceptionIfUrlIsInvalid($outputFile, $url) } #[Test] - public function throwExceptionIfEmptyDataProvided() + public function throwExceptionIfEmptyDataProvided(): void { $this->expectException(StreamException::class); $this->expectExceptionMessage('No stream URLs provided.'); new StreamHandler([]); } + /** + * @return iterable> + */ public static function wrongStreamDataProvider(): iterable { yield ["output.html", "https://gist.github"]; } + /** + * @return iterable>> + */ public static function streamDataProvider(): iterable { yield [ diff --git a/tests/unit/CsvFileHandlerTest.php b/tests/unit/CsvFileHandlerTest.php index 3e722db..2ae92f9 100644 --- a/tests/unit/CsvFileHandlerTest.php +++ b/tests/unit/CsvFileHandlerTest.php @@ -11,7 +11,7 @@ class CsvFileHandlerTest extends BaseTest { - private CsvFileHandler|null $csvFileHandler = null; + private CsvFileHandler|null $csvFileHandler; public static function setUpBeforeClass(): void { @@ -27,7 +27,7 @@ public static function tearDownAfterClass(): void protected function setUp(): void { parent::setUp(); - $this->csvFileHandler = self::$containerBuilder->get('csv_file_handler'); + $this->csvFileHandler = $this->setObjectHandler(CsvFileHandler::class, 'csv_file_handler'); } protected function tearDown(): void @@ -37,27 +37,31 @@ protected function tearDown(): void $this->csvFileHandler = null; } + #[Test] - public function findAndReplaceInCsvMethodShouldReplaceTextWithoutColumnOption() + public function findAndReplaceInCsvMethodShouldReplaceTextWithoutColumnOption(): void { $hasReplaced = $this->csvFileHandler->findAndReplaceInCsv("movie.csv", "Twilight", "Inception"); + $data = $this->isFileValid('movie.csv'); + $this->assertTrue($hasReplaced); - $this->assertStringContainsString('Inception', file_get_contents('movie.csv')); + $this->assertStringContainsString('Inception', $data); } #[Test] - public function findAndReplaceInCsvMethodShouldReplaceTextUsingColumnOption() + public function findAndReplaceInCsvMethodShouldReplaceTextUsingColumnOption(): void { $hasReplaced = $this->csvFileHandler->findAndReplaceInCsv("movie.csv", "Inception", "Twilight", "Film"); + $data = $this->isFileValid('movie.csv'); $this->assertTrue($hasReplaced); - $this->assertStringContainsString('Twilight', file_get_contents('movie.csv')); + $this->assertStringContainsString('Twilight', $data); } #[Test] #[DataProvider('provideMovieNames')] - public function searchByKeyword(string $keyword) + public function searchByKeyword(string $keyword): void { $isMovieAvailable = $this->csvFileHandler->searchInCsvFile( filename: "movie.csv", @@ -69,7 +73,7 @@ public function searchByKeyword(string $keyword) #[Test] #[DataProvider('provideStudioNames')] - public function searchBystudioName(string $keyword) + public function searchBystudioName(string $keyword): void { $isStudioFound = $this->csvFileHandler->searchInCsvFile( filename: "movie.csv", @@ -80,7 +84,7 @@ public function searchBystudioName(string $keyword) } #[Test] - public function toArrayMethodReturnsValidArray() + public function toArrayMethodReturnsValidArray(): void { $data = $this->csvFileHandler->toArray("movie.csv"); $expected = [ @@ -99,7 +103,7 @@ public function toArrayMethodReturnsValidArray() } #[Test] - public function searchByKeywordAndReturnArray() + public function searchByKeywordAndReturnArray(): void { $expected = [ 'Film' => 'Zack and Miri Make a Porno', @@ -125,9 +129,12 @@ public function searchByKeywordAndReturnArray() #[Test] - public function toJsonMethodReturnsValidJsonFormat() + public function toJsonMethodReturnsValidJsonFormat(): void { $jsonData = $this->csvFileHandler->toJson("movie.csv"); + if (!$jsonData) { + $this->fail('could not convert to json format'); + } $expectedData = '[{"Film":"Zack and Miri Make a Porno","Genre":"Romance","Lead Studio":"The Weinstein Company","Audience score %":"70","Profitability":"1.747541667","Rotten Tomatoes %":"64","Worldwide Gross":"$41.94 ","Year":"2008"},{"Film":"Youth in Revolt","Genre":"Comedy","Lead Studio":"The Weinstein Company","Audience score %":"52","Profitability":"1.09","Rotten Tomatoes %":"68","Worldwide Gross":"$19.62 ","Year":"2010"},{"Film":"Twilight","Genre":"Romance","Lead Studio":"Independent","Audience score %":"68","Profitability":"6.383363636","Rotten Tomatoes %":"26","Worldwide Gross":"$702.17 ","Year":"2011"}]'; @@ -138,10 +145,12 @@ public function toJsonMethodReturnsValidJsonFormat() #[Test] #[DataProvider('fileProvider')] - public function throwErrorIfFileFormatIsInvalid(string $file) + public function throwErrorIfFileFormatIsInvalid(string $file): void { + $message = ($file === 'file1.txt') ? 'invalid csv file format' : 'could not extract header'; $this->expectException(FileHandlerException::class); - $this->expectExceptionMessage('invalid csv file format'); + $this->expectExceptionMessage($message); + $this->expectExceptionMessage($message); try { $this->csvFileHandler->searchInCsvFile( @@ -154,12 +163,19 @@ public function throwErrorIfFileFormatIsInvalid(string $file) } } + + /** + * @return iterable> + */ public static function provideStudioNames(): iterable { yield ["The Weinstein Company"]; yield ["Independent"]; } + /** + * @return iterable> + */ public static function provideMovieNames(): iterable { yield ["Zack and Miri Make a Porno"]; @@ -167,6 +183,10 @@ public static function provideMovieNames(): iterable yield ["Twilight"]; } + /** + * @return iterable> + */ + public static function fileProvider(): iterable { $file1 = 'file1.txt'; diff --git a/tests/unit/FileEncryptorTest.php b/tests/unit/FileEncryptorTest.php index a3bb983..1db52aa 100644 --- a/tests/unit/FileEncryptorTest.php +++ b/tests/unit/FileEncryptorTest.php @@ -15,7 +15,7 @@ class FileEncryptorTest extends BaseTest protected function setUp(): void { parent::setUp(); - $this->fileEncryptor = self::$containerBuilder->get('file_encryptor'); + $this->fileEncryptor = $this->setObjectHandler(FileEncryptor::class, 'file_encryptor'); } protected function tearDown(): void @@ -37,7 +37,7 @@ public static function tearDownAfterClass(): void #[Test] - public function throwExceptionOnDecryptingNonEncryptedFile() + public function throwExceptionOnDecryptingNonEncryptedFile(): void { $this->expectException(FileEncryptorException::class); $this->expectExceptionMessage('file is not encrypted'); @@ -45,7 +45,7 @@ public function throwExceptionOnDecryptingNonEncryptedFile() } #[Test] - public function canEncryptFile() + public function canEncryptFile(): void { $isFileEncrypted = $this->fileEncryptor->encryptFile(); @@ -53,7 +53,7 @@ public function canEncryptFile() } #[Test] - public function throwExceptionIfAlreadyEncrypted() + public function throwExceptionIfAlreadyEncrypted(): void { $this->expectException(FileEncryptorException::class); $this->expectExceptionMessage('file is already encrypted'); @@ -61,7 +61,7 @@ public function throwExceptionIfAlreadyEncrypted() } #[Test] - public function throwExceptionIfDecryptionFails() + public function throwExceptionIfDecryptionFails(): void { $fileEncryptor = new FileEncryptor('movie.csv', 'wrong'); @@ -71,7 +71,7 @@ public function throwExceptionIfDecryptionFails() } #[Test] - public function canDecryptFile() + public function canDecryptFile(): void { $isFileDecrypted = $this->fileEncryptor->decryptFile(); diff --git a/tests/unit/FileHandlerTest.php b/tests/unit/FileHandlerTest.php index dfdf436..4594944 100644 --- a/tests/unit/FileHandlerTest.php +++ b/tests/unit/FileHandlerTest.php @@ -15,7 +15,7 @@ protected function setUp(): void { parent::setUp(); - $this->fileHandler = self::$containerBuilder->get('file_handler'); + $this->fileHandler = $this->setObjectHandler(FileHandler::class, 'file_handler'); } public static function setUpBeforeClass(): void @@ -38,7 +38,7 @@ protected function tearDown(): void #[Test] - public function fileSuccessfullyWritten() + public function fileSuccessfullyWritten(): void { $this->fileHandler->open(filename: 'file'); @@ -48,7 +48,7 @@ public function fileSuccessfullyWritten() } #[Test] - public function shouldThrowExceptionIfFileIsNotFound() + public function shouldThrowExceptionIfFileIsNotFound(): void { $this->expectException(FileHandlerException::class); $this->expectExceptionMessage('File not found'); @@ -56,7 +56,7 @@ public function shouldThrowExceptionIfFileIsNotFound() } #[Test] - public function shouldThrowExceptionIfFileIsNotWritable() + public function shouldThrowExceptionIfFileIsNotWritable(): void { $this->fileHandler->open(filename: 'file', mode: 'r'); @@ -67,7 +67,7 @@ public function shouldThrowExceptionIfFileIsNotWritable() } #[Test] - public function successfulCompression() + public function successfulCompression(): void { $testFile = 'movie.csv'; $compressedZip = 'compressed.zip'; @@ -81,7 +81,7 @@ public function successfulCompression() } #[Test] - public function getMimeTypeFunctionReturnsCorrectInfo() + public function getMimeTypeFunctionReturnsCorrectInfo(): void { $csvFile = $this->fileHandler->getMimeType("movie.csv"); $zipFile = $this->fileHandler->getMimeType("compressed.zip"); @@ -91,7 +91,7 @@ public function getMimeTypeFunctionReturnsCorrectInfo() } #[Test] - public function successfulDecompression() + public function successfulDecompression(): void { $compressedZip = 'compressed.zip'; $extractPath = 'extracted_contents'; @@ -112,7 +112,7 @@ public function successfulDecompression() } #[Test] - public function fileIsClosedProperly() + public function fileIsClosedProperly(): void { $this->fileHandler->open(filename: 'file'); $this->fileHandler->write(data: "hello world"); @@ -124,7 +124,7 @@ public function fileIsClosedProperly() } #[Test] - public function multipleFileCanBeWrittenSimultaneously() + public function multipleFileCanBeWrittenSimultaneously(): void { $this->fileHandler->open(filename: 'file'); diff --git a/tests/unit/FileHashCheckerTest.php b/tests/unit/FileHashCheckerTest.php index ba8d3d5..dc8ee9e 100644 --- a/tests/unit/FileHashCheckerTest.php +++ b/tests/unit/FileHashCheckerTest.php @@ -4,8 +4,6 @@ use Base\BaseTest; use PHPUnit\Framework\Attributes\Test; -use rcsofttech85\FileHandler\CsvFileHandler; -use rcsofttech85\FileHandler\Exception\HashException; use rcsofttech85\FileHandler\FileHashChecker; use Symfony\Component\Dotenv\Dotenv; @@ -19,7 +17,7 @@ protected function setUp(): void { parent::setUp(); - $this->fileHash = self::$containerBuilder->get('file_hash'); + $this->fileHash = $this->setObjectHandler(FileHashChecker::class, 'file_hash'); } protected function tearDown(): void @@ -44,7 +42,7 @@ public static function tearDownAfterClass(): void } #[Test] - public function shouldGenerateValidHashForDifferentAlgo() + public function shouldGenerateValidHashForDifferentAlgo(): void { $expectedHash = "5923032f7e18edf69e1a3221be3205ce658ec0e4fb274016212a09a804240683"; @@ -60,7 +58,7 @@ public function shouldGenerateValidHashForDifferentAlgo() } #[Test] - public function checkFileIntegrityReturnsTrueIfHashMatch() + public function checkFileIntegrityReturnsTrueIfHashMatch(): void { $isVerified = $this->fileHash->verifyHash(storedHashesFile: self::$file); @@ -68,7 +66,7 @@ public function checkFileIntegrityReturnsTrueIfHashMatch() } #[Test] - public function shouldReturnFalseIfFileIsModified() + public function shouldReturnFalseIfFileIsModified(): void { $backup = file_get_contents("movie.csv"); file_put_contents("movie.csv", "modified", FILE_APPEND); @@ -81,22 +79,10 @@ public function shouldReturnFalseIfFileIsModified() } #[Test] - public function shouldReturnFalseIfDifferentAlgoIsUsedForVerifyHash() + public function shouldReturnFalseIfDifferentAlgoIsUsedForVerifyHash(): void { $isVerified = $this->fileHash->verifyHash(self::$file, FileHashChecker::ALGO_512); $this->assertFalse($isVerified); } - - #[Test] - public function shouldThrowExceptionIfFileIsNotHashed() - { - /** @var CsvFileHandler $csvFile */ - $csvFile = self::$containerBuilder->get('csv_file_handler'); - file_put_contents("sample", "this file is not hashed"); - $this->fileHash = new FileHashChecker("sample", $csvFile); - $this->expectException(HashException::class); - $this->expectExceptionMessage("this file is not hashed"); - $this->fileHash->verifyHash(self::$file, FileHashChecker::ALGO_512); - } } diff --git a/tests/unit/TempFileHandlerTest.php b/tests/unit/TempFileHandlerTest.php index c8cd16a..d658d8f 100644 --- a/tests/unit/TempFileHandlerTest.php +++ b/tests/unit/TempFileHandlerTest.php @@ -64,6 +64,9 @@ public function createTempFileWithHeaders(): void $tempFilePath = $this->tempFileHandler->createTempFileWithHeaders($headers); + if (!$tempFilePath) { + $this->fail('could not generate temp file with header'); + } $fileContents = file_get_contents($tempFilePath); $expectedContents = implode(',', $headers) . PHP_EOL;