5 * @author Roland Haeder <webmaster@ship-simu.org>
7 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
8 * @license GNU GPL 3.0 or any newer version
9 * @link http://www.ship-simu.org
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 class BaseFile extends BaseFrameworkSystem {
26 * The current file we are working in
28 private $fileName = '';
33 private $backBuffer = '';
36 * Currently loaded block (will be returned by current())
38 private $currentBlock = '';
41 * Protected constructor
43 * @param $className Name of the class
46 protected function __construct ($className) {
47 // Call parent constructor
48 parent::__construct($className);
50 // Init counters and gaps array
51 $this->initCountersGapsArray();
55 * Destructor for cleaning purposes, etc
59 public final function __destruct() {
60 // Try to close a file
63 // Call the parent destructor
68 * Getter for the file pointer
70 * @return $filePointer The file pointer which shall be a valid file resource
71 * @throws UnsupportedOperationException If this method is called
73 public final function getPointer () {
74 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
78 * Setter for file name
80 * @param $fileName The new file name
83 protected final function setFileName ($fileName) {
84 $fileName = (string) $fileName;
85 $this->fileName = $fileName;
89 * Getter for file name
91 * @return $fileName The current file name
93 public final function getFileName () {
94 return $this->fileName;
98 * Initializes the back-buffer by setting it to an empty string.
102 private function initBackBuffer () {
103 // Simply call the setter
104 $this->setBackBuffer('');
108 * Setter for backBuffer field
110 * @param $backBuffer Characters to "store" in back-buffer
113 private function setBackBuffer ($backBuffer) {
114 // Cast to string (so no arrays or objects)
115 $backBuffer = (string) $backBuffer;
118 $this->backBuffer = $backBuffer;
122 * Getter for backBuffer field
124 * @return $backBuffer Characters "stored" in back-buffer
126 private function getBackBuffer () {
127 return $this->backBuffer;
131 * Setter for currentBlock field
133 * @param $currentBlock Characters to set a currently loaded block
136 private function setCurrentBlock ($currentBlock) {
137 // Cast to string (so no arrays or objects)
138 $currentBlock = (string) $currentBlock;
141 $this->currentBlock = $currentBlock;
145 * Initializes this file class
147 * @param $fileName Name of this abstract file
150 protected function initFile ($fileName) {
151 // Get a file i/o pointer instance
152 $pointerInstance = ObjectFactory::createObjectByConfiguredName('file_raw_input_output_class', array($fileName));
154 // ... and set it here
155 $this->setPointerInstance($pointerInstance);
159 * Close a file source and set it's instance to null and the file name
165 public function closeFile () {
166 $this->partialStub('Unfinished method.');
169 $this->setFileName('');
173 * Determines seek position
175 * @return $seekPosition Current seek position
177 public function determineSeekPosition () {
178 return $this->getPointerInstance()->determineSeekPosition();
182 * Seek to given offset (default) or other possibilities as fseek() gives.
184 * @param $offset Offset to seek to (or used as "base" for other seeks)
185 * @param $whence Added to offset (default: only use offset to seek to)
186 * @return $status Status of file seek: 0 = success, -1 = failed
188 public function seek ($offset, $whence = SEEK_SET) {
189 return $this->getPointerInstance()->seek($offset, $whence);
195 * @return $size Size (in bytes) of file
196 * @todo Handle seekStatus
198 public function size () {
199 return $this->getPointerInstance()->size();
203 * Read data a file pointer
205 * @return mixed The result of fread()
206 * @throws NullPointerException If the file pointer instance
207 * is not set by setPointer()
208 * @throws InvalidResourceException If there is being set
210 public function readFromFile () {
211 return $this->getPointerInstance()->readFromFile();
215 * Reads given amount of bytes from file.
217 * @param $bytes Amount of bytes to read
218 * @return $data Data read from file
220 public function read ($bytes) {
221 return $this->getPointerInstance()->read($bytes);
225 * Write data to a file pointer
227 * @param $dataStream The data stream we shall write to the file
228 * @return mixed Number of writes bytes or FALSE on error
229 * @throws NullPointerException If the file pointer instance
230 * is not set by setPointer()
231 * @throws InvalidResourceException If there is being set
232 * an invalid file resource
234 public function writeToFile ($dataStream) {
235 return $this->getPointerInstance()->writeToFile($dataStream);
239 * Rewinds to the beginning of the file
241 * @return $status Status of this operation
243 public function rewind () {
244 return $this->getPointerInstance()->rewind();
248 * Determines whether the EOF has been reached
250 * @return $isEndOfFileReached Whether the EOF has been reached
252 public final function isEndOfFileReached () {
253 return $this->isEndOfFileReached();
257 * Analyzes entries in index file. This will count all found (and valid)
258 * entries, mark invalid as damaged and count gaps ("fragmentation"). If
259 * only gaps are found, the file is considered as "virgin" (no entries).
263 public function analyzeFile () {
264 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] CALLED!', __METHOD__, __LINE__));
266 // Make sure the file is initialized
267 assert($this->isFileInitialized());
269 // Init counters and gaps array
270 $this->initCountersGapsArray();
272 // Output message (as this may take some time)
273 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] Analyzing file structure ... (this may take some time)', __METHOD__, __LINE__));
275 // First rewind to the begining
278 // Then try to load all entries
279 while ($this->valid()) {
284 $current = $this->current();
287 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] current=%s', __METHOD__, __LINE__, print_r($current, TRUE)));
290 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:%d:] EXIT!', __METHOD__, __LINE__));
294 * Advances to next "block" of bytes
297 * @todo This method will load large but empty files in a whole
299 public function next () {
300 // Is there nothing to read?
301 if (!$this->valid()) {
306 // Make sure the block instance is set
307 assert($this->getBlockInstance() instanceof CalculatableBlock);
309 // First calculate minimum block length
310 $length = $this->getBlockInstance()->caluclateMinimumBlockLength();
312 // Short be more than zero!
315 // Wait until a entry/block separator has been found
316 $data = $this->getBackBuffer();
317 while ((!$this->isEndOfFileReached()) && (!$this->getBlockInstance()->isBlockSeparatorFound($data))) {
318 // Then read the block
319 $data .= $this->read($length);
320 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('data()=' . strlen($data));
324 if ($this->isEndOfFileReached()) {
325 // Set whole data as current block
326 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('Calling setCurrentBlock(' . strlen($data) . ') ...');
327 $this->setCurrentBlock($data);
329 // Then abort here silently
330 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('EOF reached.');
335 * Init back-buffer which is the data that has been found beyond the
338 $this->initBackBuffer();
341 $dataArray = explode(self::getBlockSeparator(), $data);
343 // This array must contain two elements
344 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('dataArray=' . print_r($dataArray, TRUE));
345 assert(count($dataArray) == 2);
347 // Left part is the actual block, right one the back-buffer data
348 $this->setCurrentBlock($dataArray[0]);
349 $this->setBackBuffer($dataArray[1]);
353 * Checks wether the current entry is valid (not at the end of the file).
354 * This method will return TRUE if an emptied (nulled) entry has been found.
356 * @return $isValid Whether the next entry is valid
358 public function valid () {
359 // Make sure the block instance is set
360 assert($this->getBlockInstance() instanceof CalculatableBlock);
362 // First calculate minimum block length
363 $length = $this->getBlockInstance()->caluclateMinimumBlockLength();
365 // Short be more than zero!
368 // Get current seek position
369 $seekPosition = $this->key();
371 // Then try to read it
372 $data = $this->read($length);
374 // If some bytes could be read, all is fine
375 $isValid = ((is_string($data)) && (strlen($data) > 0));
378 $headerSize = $this->getBlockInstance()->getHeaderSize();
380 // Is the seek position at or beyond the header?
381 if ($seekPosition >= $headerSize) {
382 // Seek back to old position
383 $this->seek($seekPosition);
385 // Seek directly behind the header
386 $this->seek($headerSize);