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\UnsupportedOperationException;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
11 use Org\Mxchange\CoreFramework\Stream\Filesystem\FileInputStreamer;
12 use Org\Mxchange\CoreFramework\Stream\Filesystem\FileOutputStreamer;
15 use \InvalidArgumentException;
16 use \OutOfBoundsException;
20 * An universal class for file input/output streams.
22 * @author Roland Haeder <webmaster@shipsimu.org>
24 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
25 * @license GNU GPL 3.0 or any newer version
26 * @link http://www.shipsimu.org
28 * This program is free software: you can redistribute it and/or modify
29 * it under the terms of the GNU General Public License as published by
30 * the Free Software Foundation, either version 3 of the License, or
31 * (at your option) any later version.
33 * This program is distributed in the hope that it will be useful,
34 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36 * GNU General Public License for more details.
38 * You should have received a copy of the GNU General Public License
39 * along with this program. If not, see <http://www.gnu.org/licenses/>.
41 class FileIoStream extends BaseFrameworkSystem implements FileInputStreamer, FileOutputStreamer {
43 * File header indicator
45 const FILE_IO_FILE_HEADER_ID = '@head';
48 * Data block indicator
50 const FILE_IO_DATA_BLOCK_ID = '@data';
55 const FILE_IO_CHUNKER = ':';
60 const FILE_IO_SEPARATOR = '^';
63 * Protected constructor
65 private function __construct () {
66 // Call parent constructor
67 parent::__construct(__CLASS__);
71 * Create a file IO stream. This is a class for performing all actions
72 * on files like creating, deleting and loading them.
74 * @return $ioInstance An instance of a FileIoStream class
76 public static final function createFileIoStream () {
77 // Create new instance
78 $ioInstance = new FileIoStream();
80 // Return the instance
85 * Saves data to a given local file and create missing directory structures
87 * @param $fileInfoInstance An instance of a SplFileInfo class
88 * @param $dataArray The data we shall store to the file
90 * @see FileOutputStreamer
91 * @throws InvalidArgumentException If an invalid parameter was given
92 * @throws OutOfBoundsException If an expected array element wasn't found
94 public final function saveFile (SplFileInfo $fileInfoInstance, array $dataArray) {
96 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: fileInfoInstance=%s,dataArray()=%d - CALLED!', $fileInfoInstance, count($dataArray)));
97 if (count($dataArray) < 2) {
98 // Not valid array, at least 2 elements must be there!
99 throw new InvalidArgumentException(sprintf('Parameter "dataArray" should have at least 2 elements, has %d', count($dataArray)));
100 } else if (!isset($dataArray[0])) {
101 // Array element 0 not found
102 throw new OutOfBoundsException(sprintf('Array element dataArray[0] not found, dataArray=%s', json_encode($dataArray)));
103 } else if (!isset($dataArray[1])) {
104 // Array element 1 not found
105 throw new OutOfBoundsException(sprintf('Array element dataArray[1] not found, dataArray=%s', json_encode($dataArray)));
109 // Get a file output pointer
110 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_output_class', [$fileInfoInstance, 'wb']);
111 } catch (FileNotFoundException $e) {
113 ApplicationEntryPoint::exitApplication('The application has made a fatal error. Exception: ' . $e->__toString() . ' with message: ' . $e->getMessage());
116 // Write a header information for validation purposes
117 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Writing header to fileInstance=%s ...', $fileInstance->__toString()));
118 $fileInstance->writeToFile(sprintf('%s%s%s%s%s%s%s%s%s' . PHP_EOL,
119 self::FILE_IO_FILE_HEADER_ID,
120 self::FILE_IO_SEPARATOR,
122 self::FILE_IO_CHUNKER,
124 self::FILE_IO_CHUNKER,
125 strlen($dataArray[1]),
126 self::FILE_IO_CHUNKER,
130 // Encode the (maybe) binary stream with Base64
131 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Encoding %d bytes to BASE64 string ...', strlen($dataArray[1])));
132 $b64Stream = base64_encode($dataArray[1]);
134 // write the data line-by-line
135 $line = str_repeat(' ', 50); $idx = 0;
136 while (strlen($line) == 50) {
137 // Get 50 chars or less
138 $line = substr($b64Stream, $idx, 50);
140 // Save it to the stream
141 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Writing %d bytes to file ...', strlen($line)));
142 $fileInstance->writeToFile(sprintf('%s%s%s%s%s' . PHP_EOL,
143 self::FILE_IO_DATA_BLOCK_ID,
144 self::FILE_IO_SEPARATOR,
146 self::FILE_IO_CHUNKER,
150 // Advance to the next 50-chars block
155 unset($fileInstance);
158 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-IO-STREAM: EXIT!');
162 * Reads from a local file
164 * @param $infoInstance An instance of a SplFileInfo class
165 * @return $array An array with the element 'header' and 'data'
166 * @see FileInputStreamer
168 public final function loadFileContents (SplFileInfo $infoInstance) {
169 // Initialize some variables and arrays
170 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: infoInstance=%s - CALLED!', $infoInstance));
175 $readData = ''; // This will contain our read data
177 // Get a file input handler
178 $fileInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_class', array($infoInstance));
180 // Read all it's contents (we very and transparently decompress it below)
181 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: fileInstance=%s', $fileInstance->__toString()));
182 while ($readRawLine = $fileInstance->readFromFile()) {
183 // Add the read line to the buffer
184 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding %d read bytes to input buffer.', strlen($readRawLine)));
185 $inputBuffer .= $readRawLine;
187 // Break infinite loop maybe caused by the input handler
188 if ($lastBuffer == $inputBuffer) {
189 // Break out of loop, EOF reached?
190 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-IO-STREAM: EOF reached!');
194 // Remember last read line for avoiding possible infinite loops
195 $lastBuffer = $inputBuffer;
198 // Close directory handle
199 unset($fileInstance);
201 // Convert it into an array
202 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Read inputBuffer=%d bytes from infoInstance=%s', strlen($inputBuffer), $infoInstance));
203 $inputArray = explode(chr(10), $inputBuffer);
205 // Now process the read lines and verify it's content
206 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: inputArray()=%d', count($inputArray)));
207 foreach ($inputArray as $rawLine) {
208 // Trim it a little but not the leading spaces/tab-stops
209 $rawLine = rtrim($rawLine);
212 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: rawLine()=%d', strlen($rawLine)));
213 if (substr($rawLine, 0, 5) == self::FILE_IO_FILE_HEADER_ID) {
214 // Header found, so let's extract it
215 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Found header, rawLine=%s', $rawLine));
216 $header = explode(self::FILE_IO_SEPARATOR, $rawLine);
217 $headerLine = trim($header[1]);
219 // Now we must convert it again into an array
220 $header = explode(self::FILE_IO_CHUNKER, $headerLine);
222 // Is the header (maybe) valid?
223 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: header()=%d', count($header)));
224 if (count($header) != 4) {
225 // Throw an exception
226 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
228 } elseif (substr($rawLine, 0, 5) == self::FILE_IO_DATA_BLOCK_ID) {
230 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Data line found rawLine=%s', $rawLine));
231 $data = explode(self::FILE_IO_SEPARATOR, $rawLine);
232 $dataLine = $data[1];
234 // First element is the data, second the MD5 checksum
235 $data = explode(self::FILE_IO_CHUNKER, $dataLine);
237 // Validate the read line
238 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: data()=%d', count($data)));
239 if (count($data) == 2) {
240 // Generate checksum (MD5 is okay here)
241 $checksum = md5($data[0]);
243 // Check if it matches provided one
244 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: checksum=%s,data[1]=%s', $checksum, $data[1]));
245 if ($checksum != $data[1]) {
246 // MD5 hash did not match!
247 throw new InvalidMD5ChecksumException(array($this, $checksum, $data[1]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
251 throw new InvalidArrayCountException(array($this, 'data', count($data), 2), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
254 // Add this to the readData string
255 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding %d raw data to input stream', strlen($data[0])));
256 $readData .= $data[0];
258 // Other raw lines than header/data tagged lines and re-add the new-line char
259 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: Adding rawLine=%s(%d) + PHP_EOL to input stream', $rawLine, strlen($rawLine)));
260 $readData .= $rawLine . PHP_EOL;
264 // Was raw lines read and no header/data?
265 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: readData()=%d,header()=%d,data()=%d', strlen($readData), count($header), count($data)));
266 if ((!empty($readData)) && (count($header) == 0) && (count($data) == 0)) {
267 // Return raw lines back
268 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: readData()=%d - EXIT!', strlen($readData)));
272 // Was a header found?
273 if (count($header) != 4) {
274 // Throw an exception
275 throw new InvalidArrayCountException(array($this, 'header', count($header), 4), self::EXCEPTION_ARRAY_HAS_INVALID_COUNT);
278 // Decode all from Base64
279 $decodedData = @base64_decode($readData);
281 // Does the size match?
282 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: decodedData()=%d,header[2]=%d', strlen($decodedData), $header[2]));
283 if (strlen($decodedData) != $header[2]) {
284 // Size did not match
285 throw new InvalidDataLengthException(array($this, strlen($decodedData), $header[2]), self::EXCEPTION_UNEXPECTED_STRING_SIZE);
288 // Generate checksum from whole read data
289 $checksum = md5($decodedData);
291 // Validate the decoded data with the final MD5 hash
292 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: checksum=%s,header[3]=%s', $checksum, $header[3]));
293 if ($checksum != $header[3]) {
294 // MD5 hash did not match!
295 throw new InvalidMD5ChecksumException(array($this, $checksum, $header[3]), self::EXCEPTION_MD5_CHECKSUMS_MISMATCH);
298 // Return all in an array
299 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-IO-STREAM: header()=%d,decodedData()=%d - EXIT!', count($header), strlen($decodedData)));
302 'data' => $decodedData,
307 * Streams the data and maybe does something to it
309 * @param $data The data (string mostly) to "stream"
310 * @return $data The data (string mostly) to "stream"
311 * @throws UnsupportedOperationException If this method is called
313 public function streamData (string $data) {
314 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
315 throw new UnsupportedOperationException([$this, __FUNCTION__], self::EXCEPTION_UNSPPORTED_OPERATION);
319 * Determines seek position
321 * @return $seekPosition Current seek position
324 public function determineSeekPosition () {
325 $this->partialStub();
329 * Seek to given offset (default) or other possibilities as fseek() gives.
331 * @param $offset Offset to seek to (or used as "base" for other seeks)
332 * @param $whence Added to offset (default: only use offset to seek to)
333 * @return $status Status of file seek: 0 = success, -1 = failed
335 public function seek (int $offset, int $whence = SEEK_SET) {
336 $this->partialStub('offset=' . $offset . ',whence=' . $whence);
342 * @return $size Size (in bytes) of file
344 public function size () {
345 $this->partialStub();