]> 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                 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 && !$this->seek($seekPosition)) {
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      $status         Status of this operation
169          */
170         public function rewind () {
171                 // Rewind the pointer
172                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
173                 return $this->getFileObject()->rewind();
174         }
175
176         /**
177          * Seeks to given position
178          *
179          * @param       $seekPosition   Seek position in file
180          * @param       $whence                 "Seek mode" (see http://de.php.net/fseek)
181          * @return      $status                 Status of this operation
182          * @throws      InvalidArgumentException        If a parameter is not valid
183          */
184         public function seek (int $seekPosition, int $whence = SEEK_SET) {
185                 // Validate parameter
186                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
187                 if ($seekPosition < 0) {
188                         // Invalid seek position
189                         throw new InvalidArgumentException(sprintf('seekPosition=%d is not valid.', $seekPosition));
190                 }
191
192                 // Move the file pointer
193                 $status = $this->getFileObject()->fseek($seekPosition, $whence);
194
195                 // Return status
196                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
197                 return $status;
198         }
199
200         /**
201          * Reads a line, maximum 4096 Bytes from current file pointer
202          *
203          * @return      $data   Read data from file
204          */
205         public function readLine () {
206                 // Read whole line
207                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
208                 return $this->read();
209         }
210
211         /**
212          * Reads given amount of bytes from file.
213          *
214          * @param       $bytes  Amount of bytes to read
215          * @return      $data   Data read from file
216          * @throws      InvalidArgumentException        If a parameter is invalid
217          */
218         public function read (int $bytes = 0) {
219                 // Validatre parameter
220                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
221                 if ($bytes < 0) {
222                         // Bytes cannot be lesser than zero
223                         throw new InvalidArgumentException(sprintf('bytes=%d is not valid', $bytes));
224                 }
225
226                 // Is $bytes set?
227                 if ($bytes > 0) {
228                         // Try to read given characters
229                         $data = $this->getFileObject()->fread($bytes);
230                 } else {
231                         // Try to read whole line
232                         $data = $this->getFileObject()->fgets();
233                 }
234
235                 // Then return it
236                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
237                 return $data;
238         }
239
240         /**
241          * Analyzes entries in index file. This will count all found (and valid)
242          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
243          * only gaps are found, the file is considered as "virgin" (no entries).
244          *
245          * @return      void
246          * @throws      UnsupportedOperationException   If this method is called
247          */
248         public function analyzeFile () {
249                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
250         }
251
252         /**
253          * Advances to next "block" of bytes
254          *
255          * @return      void
256          * @throws      UnsupportedOperationException   If this method is called
257          */
258         public function next () {
259                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
260         }
261
262         /**
263          * Checks wether the current entry is valid (not at the end of the file).
264          * This method will return true if an emptied (nulled) entry has been found.
265          *
266          * @return      $isValid        Whether the next entry is valid
267          * @throws      UnsupportedOperationException   If this method is called
268          */
269         public function valid () {
270                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
271         }
272
273         /**
274          * Gets current seek position ("key").
275          *
276          * @return      $key    Current key in iteration
277          * @throws      UnsupportedOperationException   If this method is called
278          */
279         public function key () {
280                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
281         }
282
283         /**
284          * "Getter" for file size
285          *
286          * @return      $fileSize       Size of currently loaded file
287          * @throws      UnexpectedValueException        If $fileData does not contain "size"
288          */
289         public function getFileSize () {
290                 // Get file's data
291                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('FILE-INPUT-OUTPUT-POINTER: CALLED!');
292                 $fileData = $this->getFileObject()->fstat();
293
294                 // Make sure the required array key is there
295                 if (!isset($fileData['size'])) {
296                         // Not valid array
297                         throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)));
298                 }
299
300                 // Return size
301                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
302                 return $fileData['size'];
303         }
304
305 }