]> git.mxchange.org Git - core.git/blobdiff - framework/main/classes/file_directories/binary/stack/class_StackFile.php
Continued:
[core.git] / framework / main / classes / file_directories / binary / stack / class_StackFile.php
index 444302ba74e7daa317816b0546a2ebe96cb325ab..4f3c5b5ebd2cc85f097dcf7f059a15c09310518b 100644 (file)
@@ -1,13 +1,20 @@
 <?php
 // Own namespace
-namespace Org\Mxchange\CoreFramework\Filesystem\Stack;
+namespace Org\Mxchange\CoreFramework\Stack\File;
 
 // Import framework stuff
-use Org\Mxchange\CoreFramework\Filesystem\Block;
+use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
+use Org\Mxchange\CoreFramework\Filesystem\Stack\FileStacker;
 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
+use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
+use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
+use Org\Mxchange\CoreFramework\Utils\Crypto\CryptoUtils;
+use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
 
 // Import SPL stuff
+use \BadMethodCallException;
+use \InvalidArgumentException;
 use \SplFileInfo;
 
 /**
@@ -15,7 +22,7 @@ use \SplFileInfo;
  *
  * @author             Roland Haeder <webmaster@ship-simu.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.ship-simu.org
  *
@@ -32,13 +39,13 @@ use \SplFileInfo;
  * You should have received a copy of the GNU General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  */
-class StackFile extends BaseBinaryFile implements Block {
+class StackFile extends BaseBinaryFile implements FileStacker {
        /**
         * Protected constructor
         *
         * @return      void
         */
-       protected function __construct () {
+       private function __construct () {
                // Call parent constructor
                parent::__construct(__CLASS__);
        }
@@ -47,60 +54,193 @@ class StackFile extends BaseBinaryFile implements Block {
         * Creates an instance of this File class and prepares it for usage
         *
         * @param       $infoInstance   An instance of a SplFileInfo class
-        * @param       $blockInstance  An instance of a Block class
-        * @return      $fileInstance   An instance of this File class
+        * @param       $stackInstance  An instance of a StackableFile class
+        * @return      $stackFileInstance      An instance of this File class
         */
-       public final static function createStackFile (SplFileInfo $infoInstance, Block $blockInstance) {
+       public final static function createStackFile (SplFileInfo $infoInstance, StackableFile $stackInstance) {
                // Get a new instance
-               $fileInstance = new StackFile();
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: infoInstance[%s]=%s,stackInstance=%s - CALLED!', get_class($infoInstance), $infoInstance, $stackInstance->__toString()));
+               $stackFileInstance = new StackFile();
 
-               // Set block instance here for callbacks
-               $fileInstance->setBlockInstance($blockInstance);
+               // Set stack instance here for callbacks
+               $stackFileInstance->setStackInstance($stackInstance);
 
                // Init this abstract file
-               $fileInstance->initFile($infoInstance);
+               $stackFileInstance->initFile($infoInstance);
+
+               // Init counters and gaps array
+               $stackFileInstance->initCountersGapsArray();
 
                // Return the prepared instance
-               return $fileInstance;
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: stackFileInstance=%s - EXIT!', $stackFileInstance->__toString()));
+               return $stackFileInstance;
+       }
+
+       /**
+        * Flushes the file header
+        *
+        * @return      void
+        * @throws      BadMethodCallException  If this->stackInstance is not properly set
+        */
+       public function flushFileHeader () {
+               // Validate call
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: CALLED!');
+               if (!($this->getStackInstance() instanceof StackableFIle)) {
+                       // Index instance not set
+                       throw new BadMethodCallException('this->stackInstance[] is not properly set.');
+               }
+
+               // Call block instance
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->indexInstance->flushFileHeader() ...');
+               $this->getStackInstance()->flushFileHeader();
+
+               // Trace message
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
+       }
+
+       /**
+        * Pre-allocates file (if enabled) with some space for later faster write access.
+        *
+        * @param       $type   Type of the file
+        * @return      void
+        * @throws      InvalidArgumentException        If a parameter is empty
+        * @throws      BadMethodCallException  If this->stackInstance is not properly set
+        */
+       public function preAllocateFile (string $type) {
+               // Is it enabled?
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: type=%s - CALLED!', $type));
+               if (empty($type)) {
+                       // Empty type
+                       throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+               } elseif (!($this->getStackInstance() instanceof StackableFile) && !($this->getStackInstance() instanceof StackableFile)) {
+                       // Index instance not set
+                       throw new BadMethodCallException('this->stackInstance[] and this->pointerInstance are not properly set.');
+               }
+
+               // Message to user
+               self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('STACK-FILE: Pre-allocating file ...');
+
+               // Calculate minimum block length and get file size
+               $minimumBlockLength = $this->getStackInstance()->calculateMinimumBlockLength();
+
+               // Call protected method
+               $this->preAllocateFileByTypeLength($type, $minimumBlockLength);
+
+               // Trace message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
+       }
+
+       /**
+        * Checks wether the current entry is valid (not at the end of the file).
+        * This method will return true if an emptied (nulled) entry has been found.
+        *
+        * @return      $isValid        Whether the next entry is valid
+        * @throws      BadMethodCallException  If this->stackInstance is not properly set
+        */
+       public function isValid () {
+               // Validate call
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: CALLED!');
+               if (!($this->getStackInstance() instanceof StackableFile)) {
+                       // Index instance not set
+                       throw new BadMethodCallException('this->stackInstance[] is not properly set.');
+               }
+
+               // Get length from index
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->stackInstance->calculateMinimumBlockLength() ...');
+               $length = $this->getStackInstance()->calculateMinimumBlockLength();
+
+               // Call protected method
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STACK-FILE: Invoking this->isValidByLength(%d) ...', $length));
+               $isValid = $this->isValidByLength($length);
+
+               // Return result
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: isValid=%d - EXIT!', intval($isValid)));
+               return $isValid;
+       }
+
+       /**
+        * Reads the file header
+        *
+        * @return      void
+        * @throws      LogicException  If both instances are not set
+        */
+       public function readFileHeader () {
+               // Call stacke instance
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->stackInstance->readStackHeader() - CALLED!');
+               $this->getStackInstance()->readStackHeader();
+
+               // Trace message
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
+       }
+
+       /**
+        * Reads next "block" of bytes into $currentBlock field. THis method loads
+        * the whole file into memory when the file is just freshly initialized
+        * (only zeros in it).
+        *
+        * @return      void
+        */
+       protected function readNextBlock () {
+               // First calculate minimum block length
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: this->seekPosition=%d - CALLED!', $this->getSeekPosition()));
+               $length = $this->getStackInstance()->calculateMinimumBlockLength();
+
+               // Call protected method
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking parent::readNextBlockByLength(%d) ...', $length));
+               parent::readNextBlockByLength($length);
+
+               // Trace message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
        }
 
        /**
         * Writes given value to the file and returns a hash and gap position for it
         *
-        * @param       $groupId        Group identifier
+        * @param       $stackName      Group identifier
         * @param       $value          Value to be added to the stack
         * @return      $data           Hash and gap position
+        * @throws      InvalidArgumentException        If a parameter is not valid
         */
-       public function writeValueToFile ($groupId, $value) {
-               // Make sure no objects/resources are added as the serialization may fail
-               assert(!is_object($value));
-               assert(!is_resource($value));
+       public function writeValueToFile (string $stackName, $value) {
+               // Validate parameter
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: stackName=%s,value[]=%s - CALLED!', $stackName, gettype($value)));
+               if (empty($stackName)) {
+                       // Throw IAE
+                       throw new InvalidArgumentException('Parameter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
+               } elseif (is_object($value) || is_resource($value)) {
+                       // Not wanted here
+                       throw new InvalidArgumentException(sprintf('value[]=%s is not stackable in files', gettype($value)));
+               }
 
                // Encode/convert the value into a "binary format"
-               $encoded = $this->encodeData($value);
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking StringUtils::encodeData(value[]=%s) ...', gettype($value)));
+               $encoded = StringUtils::encodeData($value);
 
                // Get a strong hash for the "encoded" data
-               $hash = self::hash($encoded);
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking CryptoUtils::hash(%s) ...', $encoded));
+               $hash = CryptoUtils::hash($encoded);
 
                // Then write it to the next free gap
-               $data = $this->getBlockInstance()->writeDataToFreeGap($groupId, $hash, $encoded);
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking this->stackInstance->writeDataToFreeGap(%s,%s,%s) ...', $stackName, $hash, $encoded));
+               $data = $this->getStackInstance()->writeDataToFreeGap($stackName, $hash, $encoded);
 
                // Return info
+               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: data[]=%s - EXIT!', gettype($data)));
                return $data;
        }
 
        /**
         * Writes given raw data to the file and returns a gap position and length
         *
-        * @param       $groupId        Group identifier
+        * @param       $stackName      Group identifier
         * @param       $hash           Hash from encoded value
         * @param       $encoded        Encoded value to be written to the file
         * @return      $data           Gap position and length of the raw data
         * @throws      UnsupportedOperationException   If this method is called
         */
-       public function writeDataToFreeGap ($groupId, $hash, $encoded) {
-               self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . '] groupId=' . $groupId . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
-               throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
+       public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
+               self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: stackName=' . $stackName . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
+               throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
        }
 
 }