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