]> git.mxchange.org Git - core.git/blobdiff - framework/main/classes/file_directories/io/class_FrameworkFileInputOutputPointer.php
Continued:
[core.git] / framework / main / classes / file_directories / io / class_FrameworkFileInputOutputPointer.php
index 03252adbe15feb4ebc577fadbd2a24774c1fe6a5..2a03a01110fb7f2ccf87351440f913d11f966416 100644 (file)
@@ -1,22 +1,32 @@
 <?php
 // Own namespace
-namespace CoreFramework\Filesystem\Pointer;
+namespace Org\Mxchange\CoreFramework\Filesystem\Pointer;
 
 // Import framework stuff
-use CoreFramework\Bootstrap\FrameworkBootstrap;
-use CoreFramework\FileSystem\BaseFileIo;
-use CoreFramework\FileSystem\FileReadProtectedException;
-use CoreFramework\FileSystem\FileWriteProtectedException;
-use CoreFramework\Filesystem\PathWriteProtectedException;
-use CoreFramework\Generic\NullPointerException;
-use CoreFramework\Object\BaseFrameworkSystem;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filesystem\BaseFileIo;
+use Org\Mxchange\CoreFramework\Filesystem\FileIoException;
+use Org\Mxchange\CoreFramework\Filesystem\FileReadProtectedException;
+use Org\Mxchange\CoreFramework\Filesystem\FileWriteProtectedException;
+use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
+use Org\Mxchange\CoreFramework\Generic\NullPointerException;
+use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
+
+// Import SPL stuff
+use \InvalidArgumentException;
+use \SplFileInfo;
+use \SplFileObject;
+use \OutOfBoundsException;
+use \UnexpectedValueException;
 
 /**
  * A class for reading files
  *
  * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
  * @link               http://www.shipsimu.org
  *
@@ -39,7 +49,7 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         *
         * @return      void
         */
-       protected function __construct () {
+       private function __construct () {
                // Call parent constructor
                parent::__construct(__CLASS__);
        }
@@ -48,85 +58,64 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * Create a file pointer based on the given file. The file will also
         * be verified here.
         *
-        * @param       $fileName       The file name we shall pass to fopen()
+        * @param       $fileInstance   An instance of a SplFileInfo class
         * @return      void
-        * @throws      FileIsEmptyException            If the given file name is NULL or empty
         * @throws      FileReadProtectedException      If PHP cannot read an existing file
         * @throws      FileWriteProtectedException     If PHP cannot write an existing file
         * @throws      PathWriteProtectedException     If PHP cannot write to an existing path
         * @throws      FileIoException                         If fopen() returns not a file resource
         */
-       public static final function createFrameworkFileInputOutputPointer ($fileName) {
+       public static final function createFrameworkFileInputOutputPointer (SplFileInfo $fileInstance) {
                // Some pre-sanity checks...
-               if ((is_null($fileName)) || (empty($fileName))) {
-                       // No filename given
-                       throw new FileIsEmptyException(NULL, self::EXCEPTION_UNEXPECTED_EMPTY_STRING);
-               } elseif (!FrameworkBootstrap::isReachableFilePath($fileName)) {
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: fileInstance[%s]=%s - CALLED!', get_class($fileInstance), $fileInstance));
+               if (!FrameworkBootstrap::isReachableFilePath($fileInstance)) {
                        // File exists but cannot be read
-                       throw new FileIoException($fileName, self::EXCEPTION_FILE_NOT_REACHABLE);
-               } elseif ((!FrameworkBootstrap::isReadableFile($fileName)) && (file_exists($fileName))) {
+                       throw new FileIoException($fileInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
+               } elseif ((!FrameworkBootstrap::isReadableFile($fileInstance)) && (file_exists($fileInstance))) {
                        // File exists but cannot be read
-                       throw new FileReadProtectedException($fileName, self::EXCEPTION_FILE_CANNOT_BE_READ);
-               } elseif ((file_exists($fileName)) && (!is_writable($fileName))) {
-                       // File exists but cannot be written
-                       throw new FileWriteProtectedException($fileName, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
-               } elseif (!is_writable(dirname($fileName))) {
+                       throw new FileReadProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_READ);
+               } elseif (!is_writable($fileInstance->getPath())) {
                        // Path is not writable
-                       throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
+                       throw new PathWriteProtectedException($fileInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
+               } elseif (($fileInstance->isFile()) && (!$fileInstance->isWritable())) {
+                       // File exists but cannot be written
+                       throw new FileWriteProtectedException($fileInstance, self::EXCEPTION_FILE_CANNOT_BE_WRITTEN);
                }
 
                // Try to open a handler
-               $filePointer = fopen($fileName, 'c+b');
-               if ((is_null($filePointer)) || ($filePointer === false)) {
+               $fileObject = $fileInstance->openFile('c+b');
+
+               // Is it valid?
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: fileObject[]=%s', gettype($fileObject)));
+               if (!($fileObject instanceof SplFileObject)) {
                        // Something bad happend
-                       throw new FileIoException($fileName, self::EXCEPTION_FILE_POINTER_INVALID);
-               } // END - if
+                       throw new FileIoException($fileInstance->getPathname(), self::EXCEPTION_FILE_POINTER_INVALID);
+               }
 
                // Create new instance
                $pointerInstance = new FrameworkFileInputOutputPointer();
 
-               // Set file pointer and file name
-               $pointerInstance->setPointer($filePointer);
-               $pointerInstance->setFileName($fileName);
+               // Set file object and file name
+               $pointerInstance->setFileObject($fileObject);
 
                // Return the instance
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: pointerInstance=%s - EXIT!', $pointerInstance->__toString()));
                return $pointerInstance;
        }
 
-       /**
-        * Validates file pointer and throws exceptions. This method does not return
-        * anything (not reliable) as this method checks the file pointer and on
-        * case of an error it throws an exception. If this method does not throw
-        * any exceptions, the file pointer seems to be fine.
-        *
-        * @return      void
-        * @throws      NullPointerException    If the file pointer instance
-        *                                                                      is not set by setPointer()
-        * @throws      InvalidResourceException        If there is being set
-        */
-       private function validateFilePointer () {
-               if (is_null($this->getPointer())) {
-                       // Pointer not initialized
-                       throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
-               } elseif (!is_resource($this->getPointer())) {
-                       // Pointer is not a valid resource!
-                       throw new InvalidResourceException($this, self::EXCEPTION_INVALID_RESOURCE);
-               }
-
-               // All fine here
-       }
-
        /**
         * Read 1024 bytes data from a file pointer
         *
         * @return      mixed   The result of fread()
         */
        public function readFromFile () {
-               // Validate the pointer
-               $this->validateFilePointer();
-
                // Read data from the file pointer and return it
-               return $this->read(1024);
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+               $data = $this->read(1024);
+
+               // Return data
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%d - EXIT!', gettype($data), $data));
+               return $data;
        }
 
        /**
@@ -135,40 +124,70 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * @param       $dataStream             The data stream we shall write to the file
         * @return      mixed                   Number of writes bytes or false on error
         */
-       public function writeToFile ($dataStream) {
-               // Validate the pointer
-               $this->validateFilePointer();
+       public function writeToFile (string $dataStream) {
+               // Validate parameter
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: dataStream(%d)=%s - CALLED!', strlen($dataStream), $dataStream));
+               if (empty($dataStream)) {
+                       // Empty dataStream
+                       throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+               }
+
+               // Get length
+               $length = strlen($dataStream);
 
                // Write data to the file pointer and return written bytes
-               return fwrite($this->getPointer(), $dataStream, strlen($dataStream));
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: Invoking this->fileObject->fwrite(%s,%d) ...', $dataStream, $length));
+               $status = $this->getFileObject()->fwrite($dataStream, $length);
+
+               // Return status
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
+               return $status;
        }
 
        /**
         * Writes at given position by seeking to it.
         *
         * @param       $seekPosition   Seek position in file
-        * @param       $data                   Data to be written
+        * @param       $dataStream             Data to be written
         * @return      mixed                   Number of writes bytes or false on error
+        * @throws      OutOfBoundsException    If the position is not seekable
+        * @throws      InvalidArgumentException        If a parameter is not valid
         */
-       public function writeAtPosition ($seekPosition, $data) {
-               // First seek to it
-               $this->seek($seekPosition);
+       public function writeAtPosition (int $seekPosition, string $dataStream) {
+               // Validate parameter
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,dataStream(%d)=%s - CALLED!', $seekPosition, strlen($dataStream), $dataStream));
+               if ($seekPosition < 0) {
+                       // Invalid seek position
+                       throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
+               } elseif (empty($dataStream)) {
+                       // Empty dataStream
+                       throw new InvalidArgumentException('Parameter "dataStream" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+               } elseif (($this->getFileSize() > 0 || $seekPosition > 0) && $this->seek($seekPosition) === -1) {
+                       // Could not seek
+                       throw new InvalidArgumentException(sprintf('Could not seek to seekPosition=%d', $seekPosition));
+               }
 
                // Then write the data at that position
-               return $this->writeToFile($data);
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: Invoking this->writeToFile(%s) ...', $dataStream));
+               $status = $this->writeToFile($dataStream);
+
+               // Return status
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
+               return $status;
        }
 
        /**
         * Rewinds to the beginning of the file
         *
-        * @return      $status         Status of this operation
+        * @return      void
         */
        public function rewind () {
-               // Validate the pointer
-               $this->validateFilePointer();
+               /// Rewind the pointer
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+               $this->getFileObject()->rewind();
 
-               // Rewind the pointer
-               return rewind($this->getPointer());
+               // Trace message
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: EXIT!');
        }
 
        /**
@@ -177,13 +196,25 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * @param       $seekPosition   Seek position in file
         * @param       $whence                 "Seek mode" (see http://de.php.net/fseek)
         * @return      $status                 Status of this operation
+        * @throws      OutOfBoundsException    If the position is not seekable
         */
-       public function seek ($seekPosition, $whence = SEEK_SET) {
-               // Validate the pointer
-               $this->validateFilePointer();
+       public function seek (int $seekPosition, int $whence = SEEK_SET) {
+               // Validate parameter
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: seekPosition=%d,whence=%d - CALLED!', $seekPosition, $whence));
+               if ($seekPosition < 0) {
+                       // Invalid seek position
+                       throw new OutOfBoundsException(sprintf('seekPosition=%d is not valid.', $seekPosition));
+               } elseif ($whence < 0) {
+                       // Invalid seek position
+                       throw new OutOfBoundsException(sprintf('whence=%d is not valid.', $whence));
+               }
 
                // Move the file pointer
-               return fseek($this->getPointer(), $seekPosition, $whence);
+               $status = $this->getFileObject()->fseek($seekPosition, $whence);
+
+               // Return status
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: status[%s]=%d - EXIT!', gettype($status), $status));
+               return $status;
        }
 
        /**
@@ -193,7 +224,12 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         */
        public function readLine () {
                // Read whole line
-               return $this->read();
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+               $data = $this->read();
+
+               // Return data
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
+               return $data;
        }
 
        /**
@@ -201,21 +237,27 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         *
         * @param       $bytes  Amount of bytes to read
         * @return      $data   Data read from file
+        * @throws      OutOfBoundsException    If the position is not seekable
         */
-       public function read ($bytes = NULL) {
-               // Validate the pointer
-               $this->validateFilePointer();
+       public function read (int $bytes = 0) {
+               // Validatre parameter
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: bytes=%d - CALLED!', $bytes));
+               if ($bytes < 0) {
+                       // Bytes cannot be lesser than zero
+                       throw new OutOfBoundsException(sprintf('bytes=%d is not valid', $bytes));
+               }
 
-               // Is $bytes set?
-               if (is_int($bytes)) {
+               // Is $bytes bigger than zero?
+               if ($bytes > 0) {
                        // Try to read given characters
-                       $data = fread($this->getPointer(), $bytes);
+                       $data = $this->getFileObject()->fread($bytes);
                } else {
                        // Try to read whole line
-                       $data = fread($this->getPointer());
+                       $data = $this->getFileObject()->fgets();
                }
 
                // Then return it
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: data[%s]=%s - EXIT!', gettype($data), $data));
                return $data;
        }
 
@@ -227,8 +269,8 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * @return      void
         * @throws      UnsupportedOperationException   If this method is called
         */
-       public function analyzeFile () {
-               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+       public function analyzeFileStructure () {
+               throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
        }
 
        /**
@@ -238,7 +280,7 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * @throws      UnsupportedOperationException   If this method is called
         */
        public function next () {
-               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+               throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
        }
 
        /**
@@ -249,7 +291,7 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * @throws      UnsupportedOperationException   If this method is called
         */
        public function valid () {
-               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+               throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
        }
 
        /**
@@ -259,25 +301,28 @@ class FrameworkFileInputOutputPointer extends BaseFileIo implements InputOutputP
         * @throws      UnsupportedOperationException   If this method is called
         */
        public function key () {
-               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+               throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
        }
 
        /**
         * "Getter" for file size
         *
         * @return      $fileSize       Size of currently loaded file
+        * @throws      UnexpectedValueException        If $fileData does not contain "size"
         */
        public function getFileSize () {
-               // Check if the pointer is still valid
-               $this->validateFilePointer();
-
                // Get file's data
-               $fileData = fstat($this->getPointer());
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('FILE-INPUT-OUTPUT-POINTER: CALLED!');
+               $fileData = $this->getFileObject()->fstat();
 
                // Make sure the required array key is there
-               assert(isset($fileData['size']));
+               if (!isset($fileData['size'])) {
+                       // Not valid array
+                       throw new UnexpectedValueException(sprintf('fileData=%s has no element "size"', print_r($fileData, TRUE)), FrameworkInterface::EXCEPTION_UNEXPECTED_VALUE);
+               }
 
                // Return size
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('FILE-INPUT-OUTPUT-POINTER: fileData[size]=%d - EXIT!', $fileData['size']));
                return $fileData['size'];
        }