Continued:
[core.git] / framework / main / classes / file_directories / binary / stack / class_StackFile.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Stack\File;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Filesystem\Stack\FileStacker;
8 use Org\Mxchange\CoreFramework\Filesystem\File\BaseBinaryFile;
9 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
10 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
11 use Org\Mxchange\CoreFramework\Stack\File\StackableFile;
12 use Org\Mxchange\CoreFramework\Utils\Crypto\CryptoUtils;
13 use Org\Mxchange\CoreFramework\Utils\Strings\StringUtils;
14
15 // Import SPL stuff
16 use \BadMethodCallException;
17 use \InvalidArgumentException;
18 use \SplFileInfo;
19
20 /**
21  * A stack file class
22  *
23  * @author              Roland Haeder <webmaster@ship-simu.org>
24  * @version             0.0.0
25  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
26  * @license             GNU GPL 3.0 or any newer version
27  * @link                http://www.ship-simu.org
28  *
29  * This program is free software: you can redistribute it and/or modify
30  * it under the terms of the GNU General Public License as published by
31  * the Free Software Foundation, either version 3 of the License, or
32  * (at your option) any later version.
33  *
34  * This program is distributed in the hope that it will be useful,
35  * but WITHOUT ANY WARRANTY; without even the implied warranty of
36  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37  * GNU General Public License for more details.
38  *
39  * You should have received a copy of the GNU General Public License
40  * along with this program. If not, see <http://www.gnu.org/licenses/>.
41  */
42 class StackFile extends BaseBinaryFile implements FileStacker {
43         /**
44          * Protected constructor
45          *
46          * @return      void
47          */
48         private function __construct () {
49                 // Call parent constructor
50                 parent::__construct(__CLASS__);
51         }
52
53         /**
54          * Creates an instance of this File class and prepares it for usage
55          *
56          * @param       $infoInstance   An instance of a SplFileInfo class
57          * @param       $stackInstance  An instance of a StackableFile class
58          * @return      $stackFileInstance      An instance of this File class
59          */
60         public final static function createStackFile (SplFileInfo $infoInstance, StackableFile $stackInstance) {
61                 // Get a new instance
62                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: infoInstance[%s]=%s,stackInstance=%s - CALLED!', get_class($infoInstance), $infoInstance, $stackInstance->__toString()));
63                 $stackFileInstance = new StackFile();
64
65                 // Set stack instance here for callbacks
66                 $stackFileInstance->setStackInstance($stackInstance);
67
68                 // Init this abstract file
69                 $stackFileInstance->initFile($infoInstance);
70
71                 // Init counters and gaps array
72                 $stackFileInstance->initCountersGapsArray();
73
74                 // Return the prepared instance
75                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: stackFileInstance=%s - EXIT!', $stackFileInstance->__toString()));
76                 return $stackFileInstance;
77         }
78
79         /**
80          * Flushes the file header
81          *
82          * @return      void
83          * @throws      BadMethodCallException  If this->stackInstance is not properly set
84          */
85         public function flushFileHeader () {
86                 // Validate call
87                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: CALLED!');
88                 if (!($this->getStackInstance() instanceof StackableFIle)) {
89                         // Index instance not set
90                         throw new BadMethodCallException('this->stackInstance[] is not properly set.');
91                 }
92
93                 // Call block instance
94                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->indexInstance->flushFileHeader() ...');
95                 $this->getStackInstance()->flushFileHeader();
96
97                 // Trace message
98                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
99         }
100
101         /**
102          * Pre-allocates file (if enabled) with some space for later faster write access.
103          *
104          * @param       $type   Type of the file
105          * @return      void
106          * @throws      InvalidArgumentException        If a parameter is empty
107          * @throws      BadMethodCallException  If this->stackInstance is not properly set
108          */
109         public function preAllocateFile (string $type) {
110                 // Is it enabled?
111                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: type=%s - CALLED!', $type));
112                 if (empty($type)) {
113                         // Empty type
114                         throw new InvalidArgumentException('Parameter "type" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
115                 } elseif (!($this->getStackInstance() instanceof StackableFile) && !($this->getStackInstance() instanceof StackableFile)) {
116                         // Index instance not set
117                         throw new BadMethodCallException('this->stackInstance[] and this->pointerInstance are not properly set.');
118                 }
119
120                 // Message to user
121                 self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('STACK-FILE: Pre-allocating file ...');
122
123                 // Calculate minimum block length and get file size
124                 $minimumBlockLength = $this->getStackInstance()->calculateMinimumBlockLength();
125
126                 // Call protected method
127                 $this->preAllocateFileByTypeLength($type, $minimumBlockLength);
128
129                 // Trace message
130                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
131         }
132
133         /**
134          * Checks wether the current entry is valid (not at the end of the file).
135          * This method will return true if an emptied (nulled) entry has been found.
136          *
137          * @return      $isValid        Whether the next entry is valid
138          * @throws      BadMethodCallException  If this->stackInstance is not properly set
139          */
140         public function isValid () {
141                 // Validate call
142                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: CALLED!');
143                 if (!($this->getStackInstance() instanceof StackableFile)) {
144                         // Index instance not set
145                         throw new BadMethodCallException('this->stackInstance[] is not properly set.');
146                 }
147
148                 // Get length from index
149                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->stackInstance->calculateMinimumBlockLength() ...');
150                 $length = $this->getStackInstance()->calculateMinimumBlockLength();
151
152                 // Call protected method
153                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STACK-FILE: Invoking this->isValidByLength(%d) ...', $length));
154                 $isValid = $this->isValidByLength($length);
155
156                 // Return result
157                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: isValid=%d - EXIT!', intval($isValid)));
158                 return $isValid;
159         }
160
161         /**
162          * Reads the file header
163          *
164          * @return      void
165          * @throws      LogicException  If both instances are not set
166          */
167         public function readFileHeader () {
168                 // Call stacke instance
169                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: Invoking this->stackInstance->readStackHeader() - CALLED!');
170                 $this->getStackInstance()->readStackHeader();
171
172                 // Trace message
173                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
174         }
175
176         /**
177          * Reads next "block" of bytes into $currentBlock field. THis method loads
178          * the whole file into memory when the file is just freshly initialized
179          * (only zeros in it).
180          *
181          * @return      void
182          */
183         protected function readNextBlock () {
184                 // First calculate minimum block length
185                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: this->seekPosition=%d - CALLED!', $this->getSeekPosition()));
186                 $length = $this->getStackInstance()->calculateMinimumBlockLength();
187
188                 // Call protected method
189                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking parent::readNextBlockByLength(%d) ...', $length));
190                 parent::readNextBlockByLength($length);
191
192                 // Trace message
193                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: EXIT!');
194         }
195
196         /**
197          * Writes given value to the file and returns a hash and gap position for it
198          *
199          * @param       $stackName      Group identifier
200          * @param       $value          Value to be added to the stack
201          * @return      $data           Hash and gap position
202          * @throws      InvalidArgumentException        If a parameter is not valid
203          */
204         public function writeValueToFile (string $stackName, $value) {
205                 // Validate parameter
206                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: stackName=%s,value[]=%s - CALLED!', $stackName, gettype($value)));
207                 if (empty($stackName)) {
208                         // Throw IAE
209                         throw new InvalidArgumentException('Parameter "stackName" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
210                 } elseif (is_object($value) || is_resource($value)) {
211                         // Not wanted here
212                         throw new InvalidArgumentException(sprintf('value[]=%s is not stackable in files', gettype($value)));
213                 }
214
215                 // Encode/convert the value into a "binary format"
216                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking StringUtils::encodeData(value[]=%s) ...', gettype($value)));
217                 $encoded = StringUtils::encodeData($value);
218
219                 // Get a strong hash for the "encoded" data
220                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking CryptoUtils::hash(%s) ...', $encoded));
221                 $hash = CryptoUtils::hash($encoded);
222
223                 // Then write it to the next free gap
224                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: Invoking this->stackInstance->writeDataToFreeGap(%s,%s,%s) ...', $stackName, $hash, $encoded));
225                 $data = $this->getStackInstance()->writeDataToFreeGap($stackName, $hash, $encoded);
226
227                 // Return info
228                 /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STACK-FILE: data[]=%s - EXIT!', gettype($data)));
229                 return $data;
230         }
231
232         /**
233          * Writes given raw data to the file and returns a gap position and length
234          *
235          * @param       $stackName      Group identifier
236          * @param       $hash           Hash from encoded value
237          * @param       $encoded        Encoded value to be written to the file
238          * @return      $data           Gap position and length of the raw data
239          * @throws      UnsupportedOperationException   If this method is called
240          */
241         public function writeDataToFreeGap (string $stackName, string $hash, string $encoded) {
242                 self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STACK-FILE: stackName=' . $stackName . ',hash=' . $hash . ',encoded()=' . strlen($encoded));
243                 throw new UnsupportedOperationException([$this, __FUNCTION__], FrameworkInterface::EXCEPTION_UNSPPORTED_OPERATION);
244         }
245
246 }