]> git.mxchange.org Git - core.git/blob - framework/main/classes/file_directories/io/class_FrameworkFileInputOutputPointer.php
Rewrites:
[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                 if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
67                         // File exists but cannot be read
68                         throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
69                 } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (file_exists($fileInstance))) {
70                         // File exists but cannot be read
71                         throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
72                 } elseif (!is_writable($fileInstance->getPath())) {
73                         // Path is not writable
74                         throw new PathWriteProtectedException($fileInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
75                 } elseif (($fileInstance->isFile()) && (!$fileInstance->isWritable())) {
76                         // File exists but cannot be written
77                         throw new FileWriteProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
78                 }
79
80                 // Try to open a handler
81                 $fileObject = $fileInstance->openFile('c+b');
82
83                 // Is it valid?
84                 if ((is_null($fileObject)) || ($fileObject === false)) {
85                         // Something bad happend
86                         throw new FileIoException($fileInstance->getPathname(), self::EXCEPTION_FILE_POINTER_INVALID);
87                 }
88
89                 // Create new instance
90                 $pointerInstance = new FrameworkFileInputOutputPointer();
91
92                 // Set file object and file name
93                 $pointerInstance->setFileObject($fileObject);
94
95                 // Return the instance
96                 return $pointerInstance;
97         }
98
99         /**
100          * Read 1024 bytes data from a file pointer
101          *
102          * @return      mixed   The result of fread()
103          */
104         public function readFromFile () {
105                 // Read data from the file pointer and return it
106                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
107                 return $this->read(1024);
108         }
109
110         /**
111          * Write data to a file pointer
112          *
113          * @param       $dataStream             The data stream we shall write to the file
114          * @return      mixed                   Number of writes bytes or false on error
115          */
116         public function writeToFile (string $dataStream) {
117                 // Validate parameter
118                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: dataStream(%d)=%s - CALLED!', strlen($dataStream), $dataStream));
119                 if (empty($dataStream)) {
120                         // Empty dataStream
121                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
122                 }
123
124                 // Write data to the file pointer and return written bytes
125                 $status = $this->getFileObject()->fwrite($dataStream, strlen($dataStream));
126
127                 // Return status
128                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
129                 return $status;
130         }
131
132         /**
133          * Writes at given position by seeking to it.
134          *
135          * @param       $seekPosition   Seek position in file
136          * @param       $dataStream             Data to be written
137          * @return      mixed                   Number of writes bytes or false on error
138          * @throws      InvalidArgumentException        If a parameter is not valid
139          */
140         public function writeAtPosition (int $seekPosition, string $dataStream) {
141                 // Validate parameter
142                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
143                 if ($seekPosition < 0) {
144                         // Invalid seek position
145                         throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid.', $seekPosition));
146                 } elseif (empty($dataStream)) {
147                         // Empty dataStream
148                         throw new InvalidArgumentException('Parameter "dataStream" is empty');
149                 }
150
151                 // First seek to it, if file size is larger than zero
152                 if (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
153                         // Could not seek
154                         throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
155                 }
156
157                 // Then write the data at that position
158                 $status = $this->writeToFile($dataStream);
159
160                 // Return status
161                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
162                 return $status;
163         }
164
165         /**
166          * Rewinds to the beginning of the file
167          *
168          * @return      void
169          */
170         public function rewind () {
171                 // Rewind the pointer
172                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
173                 $this->getFileObject()->rewind();
174
175                 // Trace message
176                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: EXIT!');
177         }
178
179         /**
180          * Seeks to given position
181          *
182          * @param       $seekPosition   Seek position in file
183          * @param       $whence                 "Seek mode" (see http://de.php.net/fseek)
184          * @return      $status                 Status of this operation
185          * @throws      InvalidArgumentException        If a parameter is not valid
186          */
187         public function seek (int $seekPosition, int $whence = SEEK_SET) {
188                 // Validate parameter
189                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
190                 if ($seekPosition < 0) {
191                         // Invalid seek position
192                         throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid.', $seekPosition));
193                 }
194
195                 // Move the file pointer
196                 $status = $this->getFileObject()->fseek($seekPosition, $whence);
197
198                 // Return status
199                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
200                 return $status;
201         }
202
203         /**
204          * Reads a line, maximum 4096 Bytes from current file pointer
205          *
206          * @return      $data   Read data from file
207          */
208         public function readLine () {
209                 // Read whole line
210                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
211                 return $this->read();
212         }
213
214         /**
215          * Reads given amount of bytes from file.
216          *
217          * @param       $bytes  Amount of bytes to read
218          * @return      $data   Data read from file
219          * @throws      InvalidArgumentException        If a parameter is invalid
220          */
221         public function read (int $bytes = 0) {
222                 // Validatre parameter
223                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
224                 if ($bytes < 0) {
225                         // Bytes cannot be lesser than zero
226                         throw new InvalidArgumentException(sprintf('bytes=%d is not valid', $bytes));
227                 }
228
229                 // Is $bytes set?
230                 if ($bytes > 0) {
231                         // Try to read given characters
232                         $data = $this->getFileObject()->fread($bytes);
233                 } else {
234                         // Try to read whole line
235                         $data = $this->getFileObject()->fgets();
236                 }
237
238                 // Then return it
239                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
240                 return $data;
241         }
242
243         /**
244          * Analyzes entries in index file. This will count all found (and valid)
245          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
246          * only gaps are found, the file is considered as "virgin" (no entries).
247          *
248          * @return      void
249          * @throws      UnsupportedOperationException   If this method is called
250          */
251         public function analyzeFile () {
252                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
253         }
254
255         /**
256          * Advances to next "block" of bytes
257          *
258          * @return      void
259          * @throws      UnsupportedOperationException   If this method is called
260          */
261         public function next () {
262                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
263         }
264
265         /**
266          * Checks wether the current entry is valid (not at the end of the file).
267          * This method will return true if an emptied (nulled) entry has been found.
268          *
269          * @return      $isValid        Whether the next entry is valid
270          * @throws      UnsupportedOperationException   If this method is called
271          */
272         public function valid () {
273                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
274         }
275
276         /**
277          * Gets current seek position ("key").
278          *
279          * @return      $key    Current key in iteration
280          * @throws      UnsupportedOperationException   If this method is called
281          */
282         public function key () {
283                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
284         }
285
286         /**
287          * "Getter" for file size
288          *
289          * @return      $fileSize       Size of currently loaded file
290          * @throws      UnexpectedValueException        If $fileData does not contain "size"
291          */
292         public function getFileSize () {
293                 // Get file's data
294                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
295                 $fileData = $this->getFileObject()->fstat();
296
297                 // Make sure the required array key is there
298                 if (!isset($fileData['size'])) {
299                         // Not valid array
300                         throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
301                 }
302
303                 // Return size
304                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
305                 return $fileData['size'];
306         }
307
308 }