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\FileReadProtectedException;
9 use Org\Mxchange\CoreFramework\Filesystem\FileWriteProtectedException;
10 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
11 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
12 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
13 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
16 use \InvalidArgumentException;
18 use \UnexpectedValueException;
21 * A class for reading files
23 * @author Roland Haeder <webmaster@shipsimu.org>
25 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
26 * @license GNU GPL 3.0 or any newer version
27 * @link http://www.shipsimu.org
29 * This program is free software: you can redistribute it and/or modify
30 * it under the terms of the GNU General Public License as published by
31 * the Free Software Foundation, either version 3 of the License, or
32 * (at your option) any later version.
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU General Public License for more details.
39 * You should have received a copy of the GNU General Public License
40 * along with this program. If not, see <http://www.gnu.org/licenses/>.
42 class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputPointer {
44 * Protected constructor
48 protected function __construct () {
49 // Call parent constructor
50 parent::__construct(__CLASS__);
54 * Create a file pointer based on the given file. The file will also
57 * @param $fileInstance An instance of a SplFileInfo class
59 * @throws FileReadProtectedException If PHP cannot read an existing file
60 * @throws FileWriteProtectedException If PHP cannot write an existing file
61 * @throws PathWriteProtectedException If PHP cannot write to an existing path
62 * @throws FileIoException If fopen() returns not a file resource
64 public static final function createFrameworkFileInputOutputPointer (SplFileInfo $fileInstance) {
65 // Some pre-sanity checks...
66 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance));
67 if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
68 // File exists but cannot be read
69 throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
70 } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (file_exists($fileInstance))) {
71 // File exists but cannot be read
72 throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
73 } elseif (!is_writable($fileInstance->getPath())) {
74 // Path is not writable
75 throw new PathWriteProtectedException($fileInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
76 } elseif (($fileInstance->isFile()) && (!$fileInstance->isWritable())) {
77 // File exists but cannot be written
78 throw new FileWriteProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
81 // Try to open a handler
82 $fileObject = $fileInstance->openFile('c+b');
85 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
86 if ((is_null($fileObject)) || ($fileObject === false)) {
87 // Something bad happend
88 throw new FileIoException($fileInstance->getPathname(), self::EXCEPTION_FILE_POINTER_INVALID);
91 // Create new instance
92 $pointerInstance = new FrameworkFileInputOutputPointer();
94 // Set file object and file name
95 $pointerInstance->setFileObject($fileObject);
97 // Return the instance
98 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
99 return $pointerInstance;
103 * Read 1024 bytes data from a file pointer
105 * @return mixed The result of fread()
107 public function readFromFile () {
108 // Read data from the file pointer and return it
109 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
110 $data = $this->read(1024);
113 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
118 * Write data to a file pointer
120 * @param $dataStream The data stream we shall write to the file
121 * @return mixed Number of writes bytes or false on error
123 public function writeToFile (string $dataStream) {
124 // Validate parameter
125 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: dataStream(%d)=%s - CALLED!', strlen($dataStream), $dataStream));
126 if (empty($dataStream)) {
128 throw new InvalidArgumentException('Parameter "dataStream" is empty');
132 $length = strlen($dataStream);
134 // Write data to the file pointer and return written bytes
135 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: Calling this->fileObject->fwrite(%s,%d) ...', $dataStream, $length));
136 $status = $this->getFileObject()->fwrite($dataStream, $length);
139 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
144 * Writes at given position by seeking to it.
146 * @param $seekPosition Seek position in file
147 * @param $dataStream Data to be written
148 * @return mixed Number of writes bytes or false on error
149 * @throws InvalidArgumentException If a parameter is not valid
151 public function writeAtPosition (int $seekPosition, string $dataStream) {
152 // Validate parameter
153 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
154 if ($seekPosition < 0) {
155 // Invalid seek position
156 throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid.', $seekPosition));
157 } elseif (empty($dataStream)) {
159 throw new InvalidArgumentException('Parameter "dataStream" is empty');
160 } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
162 throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
165 // Then write the data at that position
166 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: Calling this->writeToFile(%s) ...', $dataStream));
167 $status = $this->writeToFile($dataStream);
170 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
175 * Rewinds to the beginning of the file
179 public function rewind () {
180 /// Rewind the pointer
181 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
182 $this->getFileObject()->rewind();
185 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: EXIT!');
189 * Seeks to given position
191 * @param $seekPosition Seek position in file
192 * @param $whence "Seek mode" (see http://de.php.net/fseek)
193 * @return $status Status of this operation
194 * @throws InvalidArgumentException If a parameter is not valid
196 public function seek (int $seekPosition, int $whence = SEEK_SET) {
197 // Validate parameter
198 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
199 if ($seekPosition < 0) {
200 // Invalid seek position
201 throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid.', $seekPosition));
204 // Move the file pointer
205 $status = $this->getFileObject()->fseek($seekPosition, $whence);
208 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
213 * Reads a line, maximum 4096 Bytes from current file pointer
215 * @return $data Read data from file
217 public function readLine () {
219 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
220 $data = $this->read();
223 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
228 * Reads given amount of bytes from file.
230 * @param $bytes Amount of bytes to read
231 * @return $data Data read from file
232 * @throws InvalidArgumentException If a parameter is invalid
234 public function read (int $bytes = 0) {
235 // Validatre parameter
236 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
238 // Bytes cannot be lesser than zero
239 throw new InvalidArgumentException(sprintf('bytes=%d is not valid', $bytes));
242 // Is $bytes bigger than zero?
244 // Try to read given characters
245 $data = $this->getFileObject()->fread($bytes);
247 // Try to read whole line
248 $data = $this->getFileObject()->fgets();
252 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
257 * Analyzes entries in index file. This will count all found (and valid)
258 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
259 * only gaps are found, the file is considered as "virgin" (no entries).
262 * @throws UnsupportedOperationException If this method is called
264 public function analyzeFileStructure () {
265 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
269 * Advances to next "block" of bytes
272 * @throws UnsupportedOperationException If this method is called
274 public function next () {
275 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
279 * Checks wether the current entry is valid (not at the end of the file).
280 * This method will return true if an emptied (nulled) entry has been found.
282 * @return $isValid Whether the next entry is valid
283 * @throws UnsupportedOperationException If this method is called
285 public function valid () {
286 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
290 * Gets current seek position ("key").
292 * @return $key Current key in iteration
293 * @throws UnsupportedOperationException If this method is called
295 public function key () {
296 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
300 * "Getter" for file size
302 * @return $fileSize Size of currently loaded file
303 * @throws UnexpectedValueException If $fileData does not contain "size"
305 public function getFileSize () {
307 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
308 $fileData = $this->getFileObject()->fstat();
310 // Make sure the required array key is there
311 if (!isset($fileData['size'])) {
313 throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
317 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
318 return $fileData['size'];