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