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