]> 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\FrameworkInterface;
13 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
14 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
15 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
16
17 // Import SPL stuff
18 use \InvalidArgumentException;
19 use \SplFileInfo;
20 use \SplFileObject;
21 use \OutOfBoundsException;
22 use \UnexpectedValueException;
23
24 /**
25  * A class for reading files
26  *
27  * @author              Roland Haeder <webmaster@shipsimu.org>
28  * @version             0.0.0
29  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2022 Core Developer Team
30  * @license             GNU GPL 3.0 or any newer version
31  * @link                http://www.shipsimu.org
32  *
33  * This program is free software: you can redistribute it and/or modify
34  * it under the terms of the GNU General Public License as published by
35  * the Free Software Foundation, either version 3 of the License, or
36  * (at your option) any later version.
37  *
38  * This program is distributed in the hope that it will be useful,
39  * but WITHOUT ANY WARRANTY; without even the implied warranty of
40  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41  * GNU General Public License for more details.
42  *
43  * You should have received a copy of the GNU General Public License
44  * along with this program. If not, see <http://www.gnu.org/licenses/>.
45  */
46 class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputPointer {
47         /**
48          * Protected constructor
49          *
50          * @return      void
51          */
52         private function __construct () {
53                 // Call parent constructor
54                 parent::__construct(__CLASS__);
55         }
56
57         /**
58          * Create a file pointer based on the given file. The file will also
59          * be verified here.
60          *
61          * @param       $fileInstance   An instance of a SplFileInfo class
62          * @return      void
63          * @throws      FileReadProtectedException      If PHP cannot read an existing file
64          * @throws      FileWriteProtectedException     If PHP cannot write an existing file
65          * @throws      PathWriteProtectedException     If PHP cannot write to an existing path
66          * @throws      FileIoException                         If fopen() returns not a file resource
67          */
68         public static final function createFrameworkFileInputOutputPointer (SplFileInfo $fileInstance) {
69                 // Some pre-sanity checks...
70                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance));
71                 if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
72                         // File exists but cannot be read
73                         throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
74                 } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (file_exists($fileInstance))) {
75                         // File exists but cannot be read
76                         throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
77                 } elseif (!is_writable($fileInstance->getPath())) {
78                         // Path is not writable
79                         throw new PathWriteProtectedException($fileInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
80                 } elseif (($fileInstance->isFile()) && (!$fileInstance->isWritable())) {
81                         // File exists but cannot be written
82                         throw new FileWriteProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
83                 }
84
85                 // Try to open a handler
86                 $fileObject = $fileInstance->openFile('c+b');
87
88                 // Is it valid?
89                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
90                 if (!($fileObject instanceof SplFileObject)) {
91                         // Something bad happend
92                         throw new FileIoException($fileInstance->getPathname(), self::EXCEPTION_FILE_POINTER_INVALID);
93                 }
94
95                 // Create new instance
96                 $pointerInstance = new FrameworkFileInputOutputPointer();
97
98                 // Set file object and file name
99                 $pointerInstance->setFileObject($fileObject);
100
101                 // Return the instance
102                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
103                 return $pointerInstance;
104         }
105
106         /**
107          * Read 1024 bytes data from a file pointer
108          *
109          * @return      mixed   The result of fread()
110          */
111         public function readFromFile () {
112                 // Read data from the file pointer and return it
113                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
114                 $data = $this->read(1024);
115
116                 // Return data
117                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
118                 return $data;
119         }
120
121         /**
122          * Write data to a file pointer
123          *
124          * @param       $dataStream             The data stream we shall write to the file
125          * @return      mixed                   Number of writes bytes or false on error
126          */
127         public function writeToFile (string $dataStream) {
128                 // Validate parameter
129                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: dataStream(%d)=%s - CALLED!', strlen($dataStream), $dataStream));
130                 if (empty($dataStream)) {
131                         // Empty dataStream
132                         throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
133                 }
134
135                 // Get length
136                 $length = strlen($dataStream);
137
138                 // Write data to the file pointer and return written bytes
139                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: Invoking this->fileObject->fwrite(%s,%d) ...', $dataStream, $length));
140                 $status = $this->getFileObject()->fwrite($dataStream, $length);
141
142                 // Return status
143                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
144                 return $status;
145         }
146
147         /**
148          * Writes at given position by seeking to it.
149          *
150          * @param       $seekPosition   Seek position in file
151          * @param       $dataStream             Data to be written
152          * @return      mixed                   Number of writes bytes or false on error
153          * @throws      OutOfBoundsException    If the position is not seekable
154          * @throws      InvalidArgumentException        If a parameter is not valid
155          */
156         public function writeAtPosition (int $seekPosition, string $dataStream) {
157                 // Validate parameter
158                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
159                 if ($seekPosition < 0) {
160                         // Invalid seek position
161                         throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
162                 } elseif (empty($dataStream)) {
163                         // Empty dataStream
164                         throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
165                 } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
166                         // Could not seek
167                         throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
168                 }
169
170                 // Then write the data at that position
171                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: Invoking this->writeToFile(%s) ...', $dataStream));
172                 $status = $this->writeToFile($dataStream);
173
174                 // Return status
175                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
176                 return $status;
177         }
178
179         /**
180          * Rewinds to the beginning of the file
181          *
182          * @return      void
183          */
184         public function rewind () {
185                 /// Rewind the pointer
186                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
187                 $this->getFileObject()->rewind();
188
189                 // Trace message
190                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: EXIT!');
191         }
192
193         /**
194          * Seeks to given position
195          *
196          * @param       $seekPosition   Seek position in file
197          * @param       $whence                 "Seek mode" (see http://de.php.net/fseek)
198          * @return      $status                 Status of this operation
199          * @throws      OutOfBoundsException    If the position is not seekable
200          */
201         public function seek (int $seekPosition, int $whence = SEEK_SET) {
202                 // Validate parameter
203                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
204                 if ($seekPosition < 0) {
205                         // Invalid seek position
206                         throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
207                 }
208
209                 // Move the file pointer
210                 $status = $this->getFileObject()->fseek($seekPosition, $whence);
211
212                 // Return status
213                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
214                 return $status;
215         }
216
217         /**
218          * Reads a line, maximum 4096 Bytes from current file pointer
219          *
220          * @return      $data   Read data from file
221          */
222         public function readLine () {
223                 // Read whole line
224                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
225                 $data = $this->read();
226
227                 // Return data
228                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
229                 return $data;
230         }
231
232         /**
233          * Reads given amount of bytes from file.
234          *
235          * @param       $bytes  Amount of bytes to read
236          * @return      $data   Data read from file
237          * @throws      OutOfBoundsException    If the position is not seekable
238          */
239         public function read (int $bytes = 0) {
240                 // Validatre parameter
241                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
242                 if ($bytes < 0) {
243                         // Bytes cannot be lesser than zero
244                         throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
245                 }
246
247                 // Is $bytes bigger than zero?
248                 if ($bytes > 0) {
249                         // Try to read given characters
250                         $data = $this->getFileObject()->fread($bytes);
251                 } else {
252                         // Try to read whole line
253                         $data = $this->getFileObject()->fgets();
254                 }
255
256                 // Then return it
257                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
258                 return $data;
259         }
260
261         /**
262          * Analyzes entries in index file. This will count all found (and valid)
263          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
264          * only gaps are found, the file is considered as "virgin" (no entries).
265          *
266          * @return      void
267          * @throws      UnsupportedOperationException   If this method is called
268          */
269         public function analyzeFileStructure () {
270                 throw new UnsupportedOperationException([$this, __FUNCTION__], self::EXCEPTION_UNSPPORTED_OPERATION);
271         }
272
273         /**
274          * Advances to next "block" of bytes
275          *
276          * @return      void
277          * @throws      UnsupportedOperationException   If this method is called
278          */
279         public function next () {
280                 throw new UnsupportedOperationException([$this, __FUNCTION__], self::EXCEPTION_UNSPPORTED_OPERATION);
281         }
282
283         /**
284          * Checks wether the current entry is valid (not at the end of the file).
285          * This method will return true if an emptied (nulled) entry has been found.
286          *
287          * @return      $isValid        Whether the next entry is valid
288          * @throws      UnsupportedOperationException   If this method is called
289          */
290         public function valid () {
291                 throw new UnsupportedOperationException([$this, __FUNCTION__], self::EXCEPTION_UNSPPORTED_OPERATION);
292         }
293
294         /**
295          * Gets current seek position ("key").
296          *
297          * @return      $key    Current key in iteration
298          * @throws      UnsupportedOperationException   If this method is called
299          */
300         public function key () {
301                 throw new UnsupportedOperationException([$this, __FUNCTION__], self::EXCEPTION_UNSPPORTED_OPERATION);
302         }
303
304         /**
305          * "Getter" for file size
306          *
307          * @return      $fileSize       Size of currently loaded file
308          * @throws      UnexpectedValueException        If $fileData does not contain "size"
309          */
310         public function getFileSize () {
311                 // Get file's data
312                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
313                 $fileData = $this->getFileObject()->fstat();
314
315                 // Make sure the required array key is there
316                 if (!isset($fileData['size'])) {
317                         // Not valid array
318                         throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
319                 }
320
321                 // Return size
322                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
323                 return $fileData['size'];
324         }
325
326 }