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