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