Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
86.96% |
20 / 23 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| OfficeDocumentWordCounter | |
86.96% |
20 / 23 |
|
50.00% |
1 / 2 |
9.18 | |
0.00% |
0 / 1 |
| __construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| isSupported | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
3 | |||
| countFromFile | |
80.00% |
12 / 15 |
|
0.00% |
0 / 1 |
5.20 | |||
| 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 OfficeDocumentWordCounter 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)) { |
| 26 | return false; |
| 27 | } |
| 28 | return in_array(strtolower($fileExtension ?? ''), ['xlsx', 'pptx', 'docx']) |
| 29 | || in_array(strtolower($mimeType ?? ''), [ |
| 30 | 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', |
| 31 | 'application/vnd.openxmlformats-officedocument.presentationml.presentation', |
| 32 | 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' |
| 33 | ]); |
| 34 | } |
| 35 | |
| 36 | public static function countFromFile(string $filePath, array $counts = []): array |
| 37 | { |
| 38 | self::$counter++; |
| 39 | try { |
| 40 | $zip = new ZipArchive(); |
| 41 | if (!$zip->open($filePath)) { |
| 42 | throw new \RuntimeException('Could not open ' . $filePath); |
| 43 | } |
| 44 | for ($i = 0; $i < $zip->numFiles; $i++) { |
| 45 | $filename = $zip->getNameIndex($i); |
| 46 | |
| 47 | if (preg_match('/\.(zip|xlsx|pptx|docx)$/i', $filename)) { |
| 48 | continue; |
| 49 | } |
| 50 | // Open a stream to read the file content |
| 51 | $stream = $zip->getStream($filename); |
| 52 | |
| 53 | if (!$stream) { |
| 54 | throw new \LogicException("Failed to open stream for file: $filename\n"); |
| 55 | } |
| 56 | try { |
| 57 | $counts = WordCounter::countFromResource($stream, $counts, null, pathinfo($filename, PATHINFO_EXTENSION)); |
| 58 | } finally { |
| 59 | fclose($stream); |
| 60 | } |
| 61 | } |
| 62 | return $counts; |
| 63 | } finally { |
| 64 | self::$counter--; |
| 65 | } |
| 66 | } |
| 67 | } |