3 namespace Org\Mxchange\CoreFramework\Filesystem\Pointer;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
8 use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
9 use Org\Mxchange\CoreFramework\Filesystem\FileReadProtectedException;
10 use Org\Mxchange\CoreFramework\Filesystem\FileWriteProtectedException;
11 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
12 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
13 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
14 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
17 use \InvalidArgumentException;
20 use \OutOfBoundsException;
21 use \UnexpectedValueException;
24 * A class for reading files
26 * @author Roland Haeder <webmaster@shipsimu.org>
28 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
29 * @license GNU GPL 3.0 or any newer version
30 * @link http://www.shipsimu.org
32 * This program is free software: you can redistribute it and/or modify
33 * it under the terms of the GNU General Public License as published by
34 * the Free Software Foundation, either version 3 of the License, or
35 * (at your option) any later version.
37 * This program is distributed in the hope that it will be useful,
38 * but WITHOUT ANY WARRANTY; without even the implied warranty of
39 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
40 * GNU General Public License for more details.
42 * You should have received a copy of the GNU General Public License
43 * along with this program. If not, see <http://www.gnu.org/licenses/>.
45 class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputPointer {
47 * Protected constructor
51 private function __construct () {
52 // Call parent constructor
53 parent::__construct(__CLASS__);
57 * Create a file pointer based on the given file. The file will also
60 * @param $fileInstance An instance of a SplFileInfo class
62 * @throws FileReadProtectedException If PHP cannot read an existing file
63 * @throws FileWriteProtectedException If PHP cannot write an existing file
64 * @throws PathWriteProtectedException If PHP cannot write to an existing path
65 * @throws FileIoException If fopen() returns not a file resource
67 public static final function createFrameworkFileInputOutputPointer (SplFileInfo $fileInstance) {
68 // Some pre-sanity checks...
69 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance));
70 if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
71 // File exists but cannot be read
72 throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
73 } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (file_exists($fileInstance))) {
74 // File exists but cannot be read
75 throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
76 } elseif (!is_writable($fileInstance->getPath())) {
77 // Path is not writable
78 throw new PathWriteProtectedException($fileInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
79 } elseif (($fileInstance->isFile()) && (!$fileInstance->isWritable())) {
80 // File exists but cannot be written
81 throw new FileWriteProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
84 // Try to open a handler
85 $fileObject = $fileInstance->openFile('c+b');
88 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
89 if (!($fileObject instanceof SplFileObject)) {
90 // Something bad happend
91 throw new FileIoException($fileInstance->getPathname(), self::EXCEPTION_FILE_POINTER_INVALID);
94 // Create new instance
95 $pointerInstance = new FrameworkFileInputOutputPointer();
97 // Set file object and file name
98 $pointerInstance->setFileObject($fileObject);
100 // Return the instance
101 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
102 return $pointerInstance;
106 * Read 1024 bytes data from a file pointer
108 * @return mixed The result of fread()
110 public function readFromFile () {
111 // Read data from the file pointer and return it
112 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
113 $data = $this->read(1024);
116 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
121 * Write data to a file pointer
123 * @param $dataStream The data stream we shall write to the file
124 * @return mixed Number of writes bytes or false on error
126 public function writeToFile (string $dataStream) {
127 // Validate parameter
128 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: dataStream(%d)=%s - CALLED!', strlen($dataStream), $dataStream));
129 if (empty($dataStream)) {
131 throw new InvalidArgumentException('Parameter "dataStream" is empty');
135 $length = strlen($dataStream);
137 // Write data to the file pointer and return written bytes
138 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: Calling this->fileObject->fwrite(%s,%d) ...', $dataStream, $length));
139 $status = $this->getFileObject()->fwrite($dataStream, $length);
142 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
147 * Writes at given position by seeking to it.
149 * @param $seekPosition Seek position in file
150 * @param $dataStream Data to be written
151 * @return mixed Number of writes bytes or false on error
152 * @throws OutOfBoundsException If the position is not seekable
153 * @throws InvalidArgumentException If a parameter is not valid
155 public function writeAtPosition (int $seekPosition, string $dataStream) {
156 // Validate parameter
157 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
158 if ($seekPosition < 0) {
159 // Invalid seek position
160 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
161 } elseif (empty($dataStream)) {
163 throw new InvalidArgumentException('Parameter "dataStream" is empty');
164 } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
166 throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
169 // Then write the data at that position
170 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: Calling this->writeToFile(%s) ...', $dataStream));
171 $status = $this->writeToFile($dataStream);
174 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
179 * Rewinds to the beginning of the file
183 public function rewind () {
184 /// Rewind the pointer
185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
186 $this->getFileObject()->rewind();
189 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: EXIT!');
193 * Seeks to given position
195 * @param $seekPosition Seek position in file
196 * @param $whence "Seek mode" (see http://de.php.net/fseek)
197 * @return $status Status of this operation
198 * @throws OutOfBoundsException If the position is not seekable
200 public function seek (int $seekPosition, int $whence = SEEK_SET) {
201 // Validate parameter
202 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
203 if ($seekPosition < 0) {
204 // Invalid seek position
205 throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
208 // Move the file pointer
209 $status = $this->getFileObject()->fseek($seekPosition, $whence);
212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
217 * Reads a line, maximum 4096 Bytes from current file pointer
219 * @return $data Read data from file
221 public function readLine () {
223 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
224 $data = $this->read();
227 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
232 * Reads given amount of bytes from file.
234 * @param $bytes Amount of bytes to read
235 * @return $data Data read from file
236 * @throws OutOfBoundsException If the position is not seekable
238 public function read (int $bytes = 0) {
239 // Validatre parameter
240 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
242 // Bytes cannot be lesser than zero
243 throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
246 // Is $bytes bigger than zero?
248 // Try to read given characters
249 $data = $this->getFileObject()->fread($bytes);
251 // Try to read whole line
252 $data = $this->getFileObject()->fgets();
256 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
261 * Analyzes entries in index file. This will count all found (and valid)
262 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
263 * only gaps are found, the file is considered as "virgin" (no entries).
266 * @throws UnsupportedOperationException If this method is called
268 public function analyzeFileStructure () {
269 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
273 * Advances to next "block" of bytes
276 * @throws UnsupportedOperationException If this method is called
278 public function next () {
279 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
283 * Checks wether the current entry is valid (not at the end of the file).
284 * This method will return true if an emptied (nulled) entry has been found.
286 * @return $isValid Whether the next entry is valid
287 * @throws UnsupportedOperationException If this method is called
289 public function valid () {
290 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
294 * Gets current seek position ("key").
296 * @return $key Current key in iteration
297 * @throws UnsupportedOperationException If this method is called
299 public function key () {
300 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
304 * "Getter" for file size
306 * @return $fileSize Size of currently loaded file
307 * @throws UnexpectedValueException If $fileData does not contain "size"
309 public function getFileSize () {
311 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
312 $fileData = $this->getFileObject()->fstat();
314 // Make sure the required array key is there
315 if (!isset($fileData['size'])) {
317 throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
321 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
322 return $fileData['size'];