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