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