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