wp-all-import
/
classes
/
XmlStreamReader
/
prewk
/
xml-string-streamer
/
src
/
XmlStringStreamer
/
Stream
/
File.php
wp-all-import
/
classes
/
XmlStreamReader
/
prewk
/
xml-string-streamer
/
src
/
XmlStringStreamer
/
Stream
Last commit date
File.php
1 month ago
Stdin.php
10 years ago
File.php
57 lines
| 1 | <?php |
| 2 | // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen |
| 3 | // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fread |
| 4 | // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fclose |
| 5 | namespace Prewk\XmlStringStreamer\Stream; |
| 6 | |
| 7 | use Prewk\XmlStringStreamer\StreamInterface; |
| 8 | |
| 9 | class File implements StreamInterface |
| 10 | { |
| 11 | private $handle; |
| 12 | private $readBytes = 0; |
| 13 | private $chunkSize; |
| 14 | private $chunkCallback; |
| 15 | |
| 16 | public function __construct($mixed, $chunkSize = 16384, $chunkCallback = null) |
| 17 | { |
| 18 | if (is_string($mixed)) { |
| 19 | // Treat as filename |
| 20 | if (!file_exists($mixed)) { |
| 21 | throw new \Exception(esc_html("File '$mixed' doesn't exist")); |
| 22 | } |
| 23 | $this->handle = fopen($mixed, "rb"); |
| 24 | } else if (get_resource_type($mixed) == "stream") { |
| 25 | // Treat as file handle |
| 26 | $this->handle = $mixed; |
| 27 | } else { |
| 28 | throw new \Exception(esc_html("First argument must be either a filename or a file handle")); |
| 29 | } |
| 30 | |
| 31 | if ($this->handle === false) { |
| 32 | throw new \Exception("Couldn't create file handle"); |
| 33 | } |
| 34 | |
| 35 | $this->chunkSize = $chunkSize; |
| 36 | $this->chunkCallback = $chunkCallback; |
| 37 | } |
| 38 | |
| 39 | public function getChunk() |
| 40 | { |
| 41 | if (is_resource($this->handle) && !feof($this->handle)) { |
| 42 | $buffer = fread($this->handle, $this->chunkSize); |
| 43 | $this->readBytes += strlen($buffer); |
| 44 | |
| 45 | if (is_callable($this->chunkCallback)) { |
| 46 | call_user_func_array($this->chunkCallback, array($buffer, $this->readBytes)); |
| 47 | } |
| 48 | |
| 49 | return $buffer; |
| 50 | } else if (is_resource($this->handle)) { |
| 51 | fclose($this->handle); |
| 52 | return false; |
| 53 | } else { |
| 54 | return false; |
| 55 | } |
| 56 | } |
| 57 | } |