Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
90.00% |
18 / 20 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| ZipArchiveWordCounter | |
90.00% |
18 / 20 |
|
50.00% |
1 / 2 |
9.08 | |
0.00% |
0 / 1 |
| __construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| isSupported | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
4 | |||
| countFromFile | |
84.62% |
11 / 13 |
|
0.00% |
0 / 1 |
4.06 | |||
| 1 | <?php |
| 2 | namespace Apie\CountWords\Strategies; |
| 3 | |
| 4 | use Apie\CountWords\Strategies\Concerns\UseStringForResource; |
| 5 | use Apie\CountWords\Strategies\Concerns\UseTempFileForString; |
| 6 | use Apie\CountWords\WordCounter; |
| 7 | use ZipArchive; |
| 8 | |
| 9 | final class ZipArchiveWordCounter implements WordCounterInterface |
| 10 | { |
| 11 | use UseStringForResource; |
| 12 | use UseTempFileForString; |
| 13 | |
| 14 | private static int $counter = 0; |
| 15 | |
| 16 | /** |
| 17 | * @codeCoverageIgnore |
| 18 | */ |
| 19 | private function __construct() |
| 20 | { |
| 21 | } |
| 22 | |
| 23 | public static function isSupported(?string $fileExtension, ?string $mimeType): bool |
| 24 | { |
| 25 | if (!class_exists(ZipArchive::class) || self::$counter > 6) { |
| 26 | return false; |
| 27 | } |
| 28 | return in_array(strtolower($fileExtension ?? ''), ['zip']) |
| 29 | || in_array(strtolower($mimeType ?? ''), [ |
| 30 | 'application/zip', |
| 31 | 'application/x-zip-compressed', |
| 32 | ]); |
| 33 | } |
| 34 | |
| 35 | public static function countFromFile(string $filePath, array $counts = []): array |
| 36 | { |
| 37 | self::$counter++; |
| 38 | try { |
| 39 | $zip = new ZipArchive(); |
| 40 | if (!$zip->open($filePath)) { |
| 41 | throw new \RuntimeException('Could not open ' . $filePath); |
| 42 | } |
| 43 | for ($i = 0; $i < $zip->numFiles; $i++) { |
| 44 | $filename = $zip->getNameIndex($i); |
| 45 | |
| 46 | // Open a stream to read the file content |
| 47 | $stream = $zip->getStream($filename); |
| 48 | |
| 49 | if (!$stream) { |
| 50 | throw new \LogicException("Failed to open stream for file: $filename\n"); |
| 51 | } |
| 52 | try { |
| 53 | $counts = WordCounter::countFromResource($stream, $counts, null, pathinfo($filename, PATHINFO_EXTENSION)); |
| 54 | } finally { |
| 55 | fclose($stream); |
| 56 | } |
| 57 | } |
| 58 | return $counts; |
| 59 | } finally { |
| 60 | self::$counter--; |
| 61 | } |
| 62 | } |
| 63 | } |