]> 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\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;
14
15 // Import SPL stuff
16 use \InvalidArgumentException;
17 use \SplFileInfo;
18 use \UnexpectedValueException;
19
20 /**
21  * A class for reading files
22  *
23  * @author              Roland Haeder <webmaster@shipsimu.org>
24  * @version             0.0.0
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
28  *
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.
33  *
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.
38  *
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/>.
41  */
42 class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputPointer {
43         /**
44          * Protected constructor
45          *
46          * @return      void
47          */
48         protected function __construct () {
49                 // Call parent constructor
50                 parent::__construct(__CLASS__);
51         }
52
53         /**
54          * Create a file pointer based on the given file. The file will also
55          * be verified here.
56          *
57          * @param       $fileInstance   An instance of a SplFileInfo class
58          * @return      void
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
63          */
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);
79                 }
80
81                 // Try to open a handler
82                 $fileObject = $fileInstance->openFile('c+b');
83
84                 // Is it valid?
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);
89                 }
90
91                 // Create new instance
92                 $pointerInstance = new FrameworkFileInputOutputPointer();
93
94                 // Set file object and file name
95                 $pointerInstance->setFileObject($fileObject);
96
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;
100         }
101
102         /**
103          * Read 1024 bytes data from a file pointer
104          *
105          * @return      mixed   The result of fread()
106          */
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);
111
112                 // Return data
113                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
114                 return $data;
115         }
116
117         /**
118          * Write data to a file pointer
119          *
120          * @param       $dataStream             The data stream we shall write to the file
121          * @return      mixed                   Number of writes bytes or false on error
122          */
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)) {
127                         // Empty dataStream
128                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
129                 }
130
131                 // Get length
132                 $length = strlen($dataStream);
133
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);
137
138                 // Return status
139                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
140                 return $status;
141         }
142
143         /**
144          * Writes at given position by seeking to it.
145          *
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
150          */
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)) {
158                         // Empty dataStream
159                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
160                 } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
161                         // Could not seek
162                         throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
163                 }
164
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);
168
169                 // Return status
170                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
171                 return $status;
172         }
173
174         /**
175          * Rewinds to the beginning of the file
176          *
177          * @return      void
178          */
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();
183
184                 // Trace message
185                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: EXIT!');
186         }
187
188         /**
189          * Seeks to given position
190          *
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
195          */
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));
202                 }
203
204                 // Move the file pointer
205                 $status = $this->getFileObject()->fseek($seekPosition, $whence);
206
207                 // Return status
208                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
209                 return $status;
210         }
211
212         /**
213          * Reads a line, maximum 4096 Bytes from current file pointer
214          *
215          * @return      $data   Read data from file
216          */
217         public function readLine () {
218                 // Read whole line
219                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
220                 $data = $this->read();
221
222                 // Return data
223                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
224                 return $data;
225         }
226
227         /**
228          * Reads given amount of bytes from file.
229          *
230          * @param       $bytes  Amount of bytes to read
231          * @return      $data   Data read from file
232          * @throws      InvalidArgumentException        If a parameter is invalid
233          */
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));
237                 if ($bytes < 0) {
238                         // Bytes cannot be lesser than zero
239                         throw new InvalidArgumentException(sprintf('bytes=%d is not valid', $bytes));
240                 }
241
242                 // Is $bytes bigger than zero?
243                 if ($bytes > 0) {
244                         // Try to read given characters
245                         $data = $this->getFileObject()->fread($bytes);
246                 } else {
247                         // Try to read whole line
248                         $data = $this->getFileObject()->fgets();
249                 }
250
251                 // Then return it
252                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
253                 return $data;
254         }
255
256         /**
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).
260          *
261          * @return      void
262          * @throws      UnsupportedOperationException   If this method is called
263          */
264         public function analyzeFileStructure () {
265                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
266         }
267
268         /**
269          * Advances to next "block" of bytes
270          *
271          * @return      void
272          * @throws      UnsupportedOperationException   If this method is called
273          */
274         public function next () {
275                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
276         }
277
278         /**
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.
281          *
282          * @return      $isValid        Whether the next entry is valid
283          * @throws      UnsupportedOperationException   If this method is called
284          */
285         public function valid () {
286                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
287         }
288
289         /**
290          * Gets current seek position ("key").
291          *
292          * @return      $key    Current key in iteration
293          * @throws      UnsupportedOperationException   If this method is called
294          */
295         public function key () {
296                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
297         }
298
299         /**
300          * "Getter" for file size
301          *
302          * @return      $fileSize       Size of currently loaded file
303          * @throws      UnexpectedValueException        If $fileData does not contain "size"
304          */
305         public function getFileSize () {
306                 // Get file's data
307                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
308                 $fileData = $this->getFileObject()->fstat();
309
310                 // Make sure the required array key is there
311                 if (!isset($fileData['size'])) {
312                         // Not valid array
313                         throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
314                 }
315
316                 // Return size
317                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
318                 return $fileData['size'];
319         }
320
321 }