]> git.mxchange.org Git - core.git/blob - framework/main/classes/file_directories/io/class_FrameworkFileInputOutputPointer.php
Continued:
[core.git] / framework / main / classes / file_directories / io / class_FrameworkFileInputOutputPointer.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Filesystem\Pointer;
4
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;
15
16 // Import SPL stuff
17 use \InvalidArgumentException;
18 use \SplFileInfo;
19 use \SplFileObject;
20 use \OutOfBoundsException;
21 use \UnexpectedValueException;
22
23 /**
24  * A class for reading files
25  *
26  * @author              Roland Haeder <webmaster@shipsimu.org>
27  * @version             0.0.0
28  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
29  * @license             GNU GPL 3.0 or any newer version
30  * @link                http://www.shipsimu.org
31  *
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.
36  *
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.
41  *
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/>.
44  */
45 class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputPointer {
46         /**
47          * Protected constructor
48          *
49          * @return      void
50          */
51         private function __construct () {
52                 // Call parent constructor
53                 parent::__construct(__CLASS__);
54         }
55
56         /**
57          * Create a file pointer based on the given file. The file will also
58          * be verified here.
59          *
60          * @param       $fileInstance   An instance of a SplFileInfo class
61          * @return      void
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
66          */
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);
82                 }
83
84                 // Try to open a handler
85                 $fileObject = $fileInstance->openFile('c+b');
86
87                 // Is it valid?
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);
92                 }
93
94                 // Create new instance
95                 $pointerInstance = new FrameworkFileInputOutputPointer();
96
97                 // Set file object and file name
98                 $pointerInstance->setFileObject($fileObject);
99
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;
103         }
104
105         /**
106          * Read 1024 bytes data from a file pointer
107          *
108          * @return      mixed   The result of fread()
109          */
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);
114
115                 // Return data
116                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
117                 return $data;
118         }
119
120         /**
121          * Write data to a file pointer
122          *
123          * @param       $dataStream             The data stream we shall write to the file
124          * @return      mixed                   Number of writes bytes or false on error
125          */
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)) {
130                         // Empty dataStream
131                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
132                 }
133
134                 // Get length
135                 $length = strlen($dataStream);
136
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);
140
141                 // Return status
142                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
143                 return $status;
144         }
145
146         /**
147          * Writes at given position by seeking to it.
148          *
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
154          */
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)) {
162                         // Empty dataStream
163                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
164                 } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
165                         // Could not seek
166                         throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
167                 }
168
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);
172
173                 // Return status
174                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
175                 return $status;
176         }
177
178         /**
179          * Rewinds to the beginning of the file
180          *
181          * @return      void
182          */
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();
187
188                 // Trace message
189                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: EXIT!');
190         }
191
192         /**
193          * Seeks to given position
194          *
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
199          */
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));
206                 }
207
208                 // Move the file pointer
209                 $status = $this->getFileObject()->fseek($seekPosition, $whence);
210
211                 // Return status
212                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
213                 return $status;
214         }
215
216         /**
217          * Reads a line, maximum 4096 Bytes from current file pointer
218          *
219          * @return      $data   Read data from file
220          */
221         public function readLine () {
222                 // Read whole line
223                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
224                 $data = $this->read();
225
226                 // Return data
227                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
228                 return $data;
229         }
230
231         /**
232          * Reads given amount of bytes from file.
233          *
234          * @param       $bytes  Amount of bytes to read
235          * @return      $data   Data read from file
236          * @throws      OutOfBoundsException    If the position is not seekable
237          */
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));
241                 if ($bytes < 0) {
242                         // Bytes cannot be lesser than zero
243                         throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
244                 }
245
246                 // Is $bytes bigger than zero?
247                 if ($bytes > 0) {
248                         // Try to read given characters
249                         $data = $this->getFileObject()->fread($bytes);
250                 } else {
251                         // Try to read whole line
252                         $data = $this->getFileObject()->fgets();
253                 }
254
255                 // Then return it
256                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
257                 return $data;
258         }
259
260         /**
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).
264          *
265          * @return      void
266          * @throws      UnsupportedOperationException   If this method is called
267          */
268         public function analyzeFileStructure () {
269                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
270         }
271
272         /**
273          * Advances to next "block" of bytes
274          *
275          * @return      void
276          * @throws      UnsupportedOperationException   If this method is called
277          */
278         public function next () {
279                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
280         }
281
282         /**
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.
285          *
286          * @return      $isValid        Whether the next entry is valid
287          * @throws      UnsupportedOperationException   If this method is called
288          */
289         public function valid () {
290                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
291         }
292
293         /**
294          * Gets current seek position ("key").
295          *
296          * @return      $key    Current key in iteration
297          * @throws      UnsupportedOperationException   If this method is called
298          */
299         public function key () {
300                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
301         }
302
303         /**
304          * "Getter" for file size
305          *
306          * @return      $fileSize       Size of currently loaded file
307          * @throws      UnexpectedValueException        If $fileData does not contain "size"
308          */
309         public function getFileSize () {
310                 // Get file's data
311                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
312                 $fileData = $this->getFileObject()->fstat();
313
314                 // Make sure the required array key is there
315                 if (!isset($fileData['size'])) {
316                         // Not valid array
317                         throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
318                 }
319
320                 // Return size
321                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
322                 return $fileData['size'];
323         }
324
325 }