renamed lib-local.php -> lib-lfdb.php because it really loads the "legendary"
[core.git] / inc / main / classes / file_directories / io / class_FrameworkFileInputOutputPointer.php
1 <?php
2 // Own namespace
3 namespace CoreFramework\Filesystem\Pointer;
4
5 // Import framework stuff
6 use CoreFramework\Generic\NullPointerException;
7 use CoreFramework\Object\BaseFrameworkSystem;
8
9 /**
10  * A class for reading files
11  *
12  * @author              Roland Haeder <webmaster@shipsimu.org>
13  * @version             0.0.0
14  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
15  * @license             GNU GPL 3.0 or any newer version
16  * @link                http://www.shipsimu.org
17  *
18  * This program is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program. If not, see <http://www.gnu.org/licenses/>.
30  */
31 class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputPointer {
32         /**
33          * Protected constructor
34          *
35          * @return      void
36          */
37         protected function __construct () {
38                 // Call parent constructor
39                 parent::__construct(__CLASS__);
40         }
41
42         /**
43          * Create a file pointer based on the given file. The file will also
44          * be verified here.
45          *
46          * @param       $fileName       The file name we shall pass to fopen()
47          * @return      void
48          * @throws      FileIsEmptyException            If the given file name is NULL or empty
49          * @throws      FileReadProtectedException      If PHP cannot read an existing file
50          * @throws      FileWriteProtectedException     If PHP cannot write an existing file
51          * @throws      PathWriteProtectedException     If PHP cannot write to an existing path
52          * @throws      FileIoException                         If fopen() returns not a file resource
53          */
54         public static final function createFrameworkFileInputOutputPointer ($fileName) {
55                 // Some pre-sanity checks...
56                 if ((is_null($fileName)) || (empty($fileName))) {
57                         // No filename given
58                         throw new FileIsEmptyException(NULL, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
59                 } elseif (!BaseFrameworkSystem::isReachableFilePath($fileName)) {
60                         // File exists but cannot be read
61                         throw new FileIoException($fileName, self::EXCEPTION_FILE_NOT_REACHABLE);
62                 } elseif ((!BaseFrameworkSystem::isReadableFile($fileName)) && (file_exists($fileName))) {
63                         // File exists but cannot be read
64                         throw new FileReadProtectedException($fileName, self::EXCEPTION_FILE_CANNOT_BE_READ);
65                 } elseif ((file_exists($fileName)) && (!is_writable($fileName))) {
66                         // File exists but cannot be written
67                         throw new FileWriteProtectedException($fileName, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
68                 } elseif (!is_writable(dirname($fileName))) {
69                         // Path is not writable
70                         throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
71                 }
72
73                 // Try to open a handler
74                 $filePointer = fopen($fileName, 'c+b');
75                 if ((is_null($filePointer)) || ($filePointer === FALSE)) {
76                         // Something bad happend
77                         throw new FileIoException($fileName, self::EXCEPTION_FILE_POINTER_INVALID);
78                 } // END - if
79
80                 // Create new instance
81                 $pointerInstance = new FrameworkFileInputOutputPointer();
82
83                 // Set file pointer and file name
84                 $pointerInstance->setPointer($filePointer);
85                 $pointerInstance->setFileName($fileName);
86
87                 // Return the instance
88                 return $pointerInstance;
89         }
90
91         /**
92          * Validates file pointer and throws exceptions. This method does not return
93          * anything (not reliable) as this method checks the file pointer and on
94          * case of an error it throws an exception. If this method does not throw
95          * any exceptions, the file pointer seems to be fine.
96          *
97          * @return      void
98          * @throws      NullPointerException    If the file pointer instance
99          *                                                                      is not set by setPointer()
100          * @throws      InvalidResourceException        If there is being set
101          */
102         private function validateFilePointer () {
103                 if (is_null($this->getPointer())) {
104                         // Pointer not initialized
105                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
106                 } elseif (!is_resource($this->getPointer())) {
107                         // Pointer is not a valid resource!
108                         throw new InvalidResourceException($this, self::EXCEPTION_INVALID_RESOURCE);
109                 }
110
111                 // All fine here
112         }
113
114         /**
115          * Read 1024 bytes data from a file pointer
116          *
117          * @return      mixed   The result of fread()
118          */
119         public function readFromFile () {
120                 // Validate the pointer
121                 $this->validateFilePointer();
122
123                 // Read data from the file pointer and return it
124                 return $this->read(1024);
125         }
126
127         /**
128          * Write data to a file pointer
129          *
130          * @param       $dataStream             The data stream we shall write to the file
131          * @return      mixed                   Number of writes bytes or FALSE on error
132          */
133         public function writeToFile ($dataStream) {
134                 // Validate the pointer
135                 $this->validateFilePointer();
136
137                 // Write data to the file pointer and return written bytes
138                 return fwrite($this->getPointer(), $dataStream, strlen($dataStream));
139         }
140
141         /**
142          * Writes at given position by seeking to it.
143          *
144          * @param       $seekPosition   Seek position in file
145          * @param       $data                   Data to be written
146          * @return      mixed                   Number of writes bytes or FALSE on error
147          */
148         public function writeAtPosition ($seekPosition, $data) {
149                 // First seek to it
150                 $this->seek($seekPosition);
151
152                 // Then write the data at that position
153                 return $this->writeToFile($data);
154         }
155
156         /**
157          * Rewinds to the beginning of the file
158          *
159          * @return      $status         Status of this operation
160          */
161         public function rewind () {
162                 // Validate the pointer
163                 $this->validateFilePointer();
164
165                 // Rewind the pointer
166                 return rewind($this->getPointer());
167         }
168
169         /**
170          * Seeks to given position
171          *
172          * @param       $seekPosition   Seek position in file
173          * @param       $whence                 "Seek mode" (see http://de.php.net/fseek)
174          * @return      $status                 Status of this operation
175          */
176         public function seek ($seekPosition, $whence = SEEK_SET) {
177                 // Validate the pointer
178                 $this->validateFilePointer();
179
180                 // Move the file pointer
181                 return fseek($this->getPointer(), $seekPosition, $whence);
182         }
183
184         /**
185          * Reads a line, maximum 4096 Bytes from current file pointer
186          *
187          * @return      $data   Read data from file
188          */
189         public function readLine () {
190                 // Read whole line
191                 return $this->read();
192         }
193
194         /**
195          * Reads given amount of bytes from file.
196          *
197          * @param       $bytes  Amount of bytes to read
198          * @return      $data   Data read from file
199          */
200         public function read ($bytes = NULL) {
201                 // Validate the pointer
202                 $this->validateFilePointer();
203
204                 // Is $bytes set?
205                 if (is_int($bytes)) {
206                         // Try to read given characters
207                         $data = fread($this->getPointer(), $bytes);
208                 } else {
209                         // Try to read whole line
210                         $data = fread($this->getPointer());
211                 }
212
213                 // Then return it
214                 return $data;
215         }
216
217         /**
218          * Analyzes entries in index file. This will count all found (and valid)
219          * entries, mark invalid as damaged and count gaps ("fragmentation"). If
220          * only gaps are found, the file is considered as "virgin" (no entries).
221          *
222          * @return      void
223          * @throws      UnsupportedOperationException   If this method is called
224          */
225         public function analyzeFile () {
226                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
227         }
228
229         /**
230          * Advances to next "block" of bytes
231          *
232          * @return      void
233          * @throws      UnsupportedOperationException   If this method is called
234          */
235         public function next () {
236                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
237         }
238
239         /**
240          * Checks wether the current entry is valid (not at the end of the file).
241          * This method will return TRUE if an emptied (nulled) entry has been found.
242          *
243          * @return      $isValid        Whether the next entry is valid
244          * @throws      UnsupportedOperationException   If this method is called
245          */
246         public function valid () {
247                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
248         }
249
250         /**
251          * Gets current seek position ("key").
252          *
253          * @return      $key    Current key in iteration
254          * @throws      UnsupportedOperationException   If this method is called
255          */
256         public function key () {
257                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
258         }
259
260         /**
261          * "Getter" for file size
262          *
263          * @return      $fileSize       Size of currently loaded file
264          */
265         public function getFileSize () {
266                 // Check if the pointer is still valid
267                 $this->validateFilePointer();
268
269                 // Get file's data
270                 $fileData = fstat($this->getPointer());
271
272                 // Make sure the required array key is there
273                 assert(isset($fileData['size']));
274
275                 // Return size
276                 return $fileData['size'];
277         }
278
279 }