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