3 namespace Org\Mxchange\CoreFramework\Stream\Filesystem;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
7 use Org\Mxchange\CoreFramework\Factory\Object\ObjectFactory;
8 use Org\Mxchange\CoreFramework\Filesystem\FileNotFoundException;
9 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
10 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
11 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
12 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
13 use Org\Mxchange\CoreFramework\Stream\Filesystem\FileInputStreamer;
14 use Org\Mxchange\CoreFramework\Stream\Filesystem\FileOutputStreamer;
17 use \InvalidArgumentException;
18 use \OutOfBoundsException;
22 * An universal class for file input/output streams.
24 * @author Roland Haeder <webmaster@shipsimu.org>
26 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
27 * @license GNU GPL 3.0 or any newer version
28 * @link http://www.shipsimu.org
30 * This program is free software: you can redistribute it and/or modify
31 * it under the terms of the GNU General Public License as published by
32 * the Free Software Foundation, either version 3 of the License, or
33 * (at your option) any later version.
35 * This program is distributed in the hope that it will be useful,
36 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38 * GNU General Public License for more details.
40 * You should have received a copy of the GNU General Public License
41 * along with this program. If not, see <http://www.gnu.org/licenses/>.
43 class FileIoStream extends BaseFrameworkSystem implements FileInputStreamer, FileOutputStreamer {
45 * File header indicator
47 const FILE_IO_FILE_HEADER_ID = '@head';
50 * Data block indicator
52 const FILE_IO_DATA_BLOCK_ID = '@data';
57 const FILE_IO_CHUNKER = ':';
62 const FILE_IO_SEPARATOR = '^';
65 * Protected constructor
67 private function __construct () {
68 // Call parent constructor
69 parent::__construct(__CLASS__);
73 * Create a file IO stream. This is a class for performing all actions
74 * on files like creating, deleting and loading them.
76 * @return $ioInstance An instance of a FileIoStream class
78 public static final function createFileIoStream () {
79 // Create new instance
80 $ioInstance = new FileIoStream();
82 // Return the instance
87 * Saves data to a given local file and create missing directory structures
89 * @param $fileInfoInstance An instance of a SplFileInfo class
90 * @param $dataArray The data we shall store to the file
92 * @see FileOutputStreamer
93 * @throws InvalidArgumentException If an invalid parameter was given
94 * @throws OutOfBoundsException If an expected array element wasn't found
96 public final function saveFile (SplFileInfo $fileInfoInstance, array $dataArray) {
98 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: fileInfoInstance=%s,dataArray()=%d - CALLED!', $fileInfoInstance, count($dataArray)));
99 if (count($dataArray) < 2) {
100 // Not valid array, at least 2 elements must be there!
101 throw new InvalidArgumentException(sprintf('Parameter "dataArray" should have at least 2 elements, has %d', count($dataArray)));
102 } else if (!isset($dataArray[0])) {
103 // Array element 0 not found
104 throw new OutOfBoundsException(sprintf('Array element dataArray[0] not found, dataArray=%s', json_encode($dataArray)));
105 } else if (!isset($dataArray[1])) {
106 // Array element 1 not found
107 throw new OutOfBoundsException(sprintf('Array element dataArray[1] not found, dataArray=%s', json_encode($dataArray)));
111 // Get a file output pointer
112 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', [$fileInfoInstance, 'wb']);
113 } catch (FileNotFoundException $e) {
115 ApplicationEntryPoint::exitApplication('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
118 // Write a header information for validation purposes
119 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Writing header to fileInstance=%s ...', $fileInstance->__toString()));
120 $fileInstance->writeToFile(sprintf('%s%s%s%s%s%s%s%s%s' . PHP_EOL,
121 self::FILE_IO_FILE_HEADER_ID,
122 self::FILE_IO_SEPARATOR,
124 self::FILE_IO_CHUNKER,
126 self::FILE_IO_CHUNKER,
127 strlen($dataArray[1]),
128 self::FILE_IO_CHUNKER,
132 // Encode the (maybe) binary stream with Base64
133 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Encoding %d bytes to BASE64 string ...', strlen($dataArray[1])));
134 $b64Stream = base64_encode($dataArray[1]);
136 // write the data line-by-line
137 $line = str_repeat(' ', 50); $idx = 0;
138 while (strlen($line) == 50) {
139 // Get 50 chars or less
140 $line = substr($b64Stream, $idx, 50);
142 // Save it to the stream
143 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Writing %d bytes to file ...', strlen($line)));
144 $fileInstance->writeToFile(sprintf('%s%s%s%s%s' . PHP_EOL,
145 self::FILE_IO_DATA_BLOCK_ID,
146 self::FILE_IO_SEPARATOR,
148 self::FILE_IO_CHUNKER,
152 // Advance to the next 50-chars block
157 unset($fileInstance);
160 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-IO-STREAM: EXIT!');
164 * Reads from a local file
166 * @param $infoInstance An instance of a SplFileInfo class
167 * @return $array An array with the element 'header' and 'data'
168 * @see FileInputStreamer
170 public final function loadFileContents (SplFileInfo $infoInstance) {
171 // Initialize some variables and arrays
172 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: infoInstance=%s - CALLED!', $infoInstance));
177 $readData = ''; // This will contain our read data
179 // Get a file input handler
180 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
182 // Read all it's contents (we very and transparently decompress it below)
183 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: fileInstance=%s', $fileInstance->__toString()));
184 while ($readRawLine = $fileInstance->readFromFile()) {
185 // Add the read line to the buffer
186 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding %d read bytes to input buffer.', strlen($readRawLine)));
187 $inputBuffer .= $readRawLine;
189 // Break infinite loop maybe caused by the input handler
190 if ($lastBuffer == $inputBuffer) {
191 // Break out of loop, EOF reached?
192 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-IO-STREAM: EOF reached!');
196 // Remember last read line for avoiding possible infinite loops
197 $lastBuffer = $inputBuffer;
200 // Close directory handle
201 unset($fileInstance);
203 // Convert it into an array
204 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Read inputBuffer=%d bytes from infoInstance=%s', strlen($inputBuffer), $infoInstance));
205 $inputArray = explode(chr(10), $inputBuffer);
207 // Now process the read lines and verify it's content
208 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: inputArray()=%d', count($inputArray)));
209 foreach ($inputArray as $rawLine) {
210 // Trim it a little but not the leading spaces/tab-stops
211 $rawLine = rtrim($rawLine);
214 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: rawLine()=%d', strlen($rawLine)));
215 if (substr($rawLine, 0, 5) == self::FILE_IO_FILE_HEADER_ID) {
216 // Header found, so let's extract it
217 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Found header, rawLine=%s', $rawLine));
218 $header = explode(self::FILE_IO_SEPARATOR, $rawLine);
219 $headerLine = trim($header[1]);
221 // Now we must convert it again into an array
222 $header = explode(self::FILE_IO_CHUNKER, $headerLine);
224 // Is the header (maybe) valid?
225 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: header()=%d', count($header)));
226 if (count($header) != 4) {
227 // Throw an exception
228 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
230 } elseif (substr($rawLine, 0, 5) == self::FILE_IO_DATA_BLOCK_ID) {
232 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Data line found rawLine=%s', $rawLine));
233 $data = explode(self::FILE_IO_SEPARATOR, $rawLine);
234 $dataLine = $data[1];
236 // First element is the data, second the MD5 checksum
237 $data = explode(self::FILE_IO_CHUNKER, $dataLine);
239 // Validate the read line
240 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: data()=%d', count($data)));
241 if (count($data) == 2) {
242 // Generate checksum (MD5 is okay here)
243 $checksum = md5($data[0]);
245 // Check if it matches provided one
246 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: checksum=%s,data[1]=%s', $checksum, $data[1]));
247 if ($checksum != $data[1]) {
248 // MD5 hash did not match!
249 throw new InvalidMD5ChecksumException(array($this, $checksum, $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
253 throw new InvalidArrayCountException(array($this, 'data', count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
256 // Add this to the readData string
257 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding %d raw data to input stream', strlen($data[0])));
258 $readData .= $data[0];
260 // Other raw lines than header/data tagged lines and re-add the new-line char
261 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding rawLine=%s(%d) + PHP_EOL to input stream', $rawLine, strlen($rawLine)));
262 $readData .= $rawLine . PHP_EOL;
266 // Was raw lines read and no header/data?
267 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: readData()=%d,header()=%d,data()=%d', strlen($readData), count($header), count($data)));
268 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
269 // Return raw lines back
270 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: readData()=%d - EXIT!', strlen($readData)));
274 // Was a header found?
275 if (count($header) != 4) {
276 // Throw an exception
277 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
280 // Decode all from Base64
281 $decodedData = @base64_decode($readData);
283 // Does the size match?
284 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: decodedData()=%d,header[2]=%d', strlen($decodedData), $header[2]));
285 if (strlen($decodedData) != $header[2]) {
286 // Size did not match
287 throw new InvalidDataLengthException(array($this, strlen($decodedData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
290 // Generate checksum from whole read data
291 $checksum = md5($decodedData);
293 // Validate the decoded data with the final MD5 hash
294 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: checksum=%s,header[3]=%s', $checksum, $header[3]));
295 if ($checksum != $header[3]) {
296 // MD5 hash did not match!
297 throw new InvalidMD5ChecksumException(array($this, $checksum, $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
300 // Return all in an array
301 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: header()=%d,decodedData()=%d - EXIT!', count($header), strlen($decodedData)));
304 'data' => $decodedData,
309 * Streams the data and maybe does something to it
311 * @param $data The data (string mostly) to "stream"
312 * @return $data The data (string mostly) to "stream"
313 * @throws UnsupportedOperationException If this method is called
315 public function streamData (string $data) {
316 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
317 throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
321 * Determines seek position
323 * @return $seekPosition Current seek position
326 public function determineSeekPosition () {
327 DebugMiddleware::getSelfInstance()->partialStub();
331 * Seek to given offset (default) or other possibilities as fseek() gives.
333 * @param $offset Offset to seek to (or used as "base" for other seeks)
334 * @param $whence Added to offset (default: only use offset to seek to)
335 * @return $status Status of file seek: 0 = success, -1 = failed
337 public function seek (int $offset, int $whence = SEEK_SET) {
338 DebugMiddleware::getSelfInstance()->partialStub('offset=' . $offset . ',whence=' . $whence);
344 * @return $size Size (in bytes) of file
346 public function size () {
347 DebugMiddleware::getSelfInstance()->partialStub();