|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace Nextras\MultiQueryParser; |
| 4 | + |
| 5 | +use ArrayIterator; |
| 6 | +use Iterator; |
| 7 | +use Nextras\MultiQueryParser\Exception\RuntimeException; |
| 8 | +use function feof; |
| 9 | +use function fopen; |
| 10 | +use function fread; |
| 11 | + |
| 12 | + |
| 13 | +abstract class BaseMultiQueryParser implements IMultiQueryParser |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @param positive-int $chunkSize |
| 17 | + * @return Iterator<string> |
| 18 | + */ |
| 19 | + public function parseFile(string $path, int $chunkSize = self::DEFAULT_CHUNK_SIZE): Iterator |
| 20 | + { |
| 21 | + $handle = @fopen($path, 'rb'); |
| 22 | + |
| 23 | + if ($handle === false) { |
| 24 | + throw new RuntimeException("Cannot open file '$path'."); |
| 25 | + } |
| 26 | + |
| 27 | + return $this->parseFileStream($handle, $chunkSize); |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + /** |
| 32 | + * @param resource $fileStream |
| 33 | + * @param positive-int $chunkSize |
| 34 | + * @return Iterator<string> |
| 35 | + */ |
| 36 | + public function parseFileStream($fileStream, int $chunkSize = self::DEFAULT_CHUNK_SIZE): Iterator |
| 37 | + { |
| 38 | + return $this->parseStringStream($this->toStringStream($fileStream, $chunkSize)); |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + /** |
| 43 | + * @return Iterator<string> |
| 44 | + */ |
| 45 | + public function parseString(string $s): Iterator |
| 46 | + { |
| 47 | + return $this->parseStringStream(new ArrayIterator([$s])); |
| 48 | + } |
| 49 | + |
| 50 | + |
| 51 | + /** |
| 52 | + * @param Iterator<string> $stream |
| 53 | + * @return Iterator<string> |
| 54 | + */ |
| 55 | + abstract public function parseStringStream(Iterator $stream): Iterator; |
| 56 | + |
| 57 | + |
| 58 | + /** |
| 59 | + * @param resource $fileStream |
| 60 | + * @param positive-int $chunkSize |
| 61 | + * @return Iterator<string> |
| 62 | + */ |
| 63 | + private function toStringStream($fileStream, int $chunkSize): Iterator |
| 64 | + { |
| 65 | + while (!feof($fileStream)) { |
| 66 | + $chunk = fread($fileStream, $chunkSize); |
| 67 | + |
| 68 | + if ($chunk === false) { |
| 69 | + throw new RuntimeException('Error reading file stream.'); |
| 70 | + } |
| 71 | + |
| 72 | + yield $chunk; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments