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