3 namespace Org\Mxchange\CoreFramework\Utils\Strings;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
8 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
9 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
10 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
13 use \InvalidArgumentException;
16 * A string utility class
18 * @author Roland Haeder <webmaster@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2023 Core Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.org
24 * This program is free software: you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation, either version 3 of the License, or
27 * (at your option) any later version.
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU General Public License for more details.
34 * You should have received a copy of the GNU General Public License
35 * along with this program. If not, see <http://www.gnu.org/licenses/>.
37 final class StringUtils extends BaseFrameworkSystem {
41 private static $thousands = ''; // German
46 private static $decimals = ''; // German
49 * In-method cache array
51 private static $cache = [];
54 * Array with bitmasks and such for pack/unpack methods to support both
55 * 32-bit and 64-bit systems
57 private static $packingData = [
61 'right' => 0x0000ffff,
67 'left' => 0xffffffff00000000,
68 'right' => 0x00000000ffffffff,
75 * Hexadecimal->Decimal translation array
77 private static $hexdec = [
97 * Decimal->hexadecimal translation array
99 private static $dechex = [
119 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
121 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
123 private static $archArrayElement = 0;
126 * Private constructor, no instance needed. If PHP would have a static initializer ...
130 private function __construct () {
131 // Call parent constructor
132 parent::__construct(__CLASS__);
135 if (empty(self::$archArrayElement)) {
137 self::$archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
139 // Init from configuration
140 self::$thousands = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('thousands_separator');
141 self::$decimals = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals_separator');
146 * Converts dashes to underscores, e.g. useable for configuration entries
148 * @param $str The string with maybe dashes inside
149 * @return $str The converted string with no dashed, but underscores
150 * @throws NullPointerException If $str is null
151 * @throws InvalidArgumentException If $str is empty
153 public static function convertDashesToUnderscores (string $str) {
154 // Validate parameter
157 throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
161 $str = str_replace('-', '_', $str);
163 // Return converted string
168 * Encodes raw data (almost any type) by "serializing" it and then pack it
169 * into a "binary format".
171 * @param $rawData Raw data (almost any type)
172 * @return $encoded Encoded data
173 * @throws InvalidArgumentException If $rawData has a non-serializable data type
175 public static function encodeData ($rawData) {
176 // Make sure no objects or resources pass through
177 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: rawData[]=%s - CALLED!', gettype($rawData)));
178 if (is_object($rawData) || is_resource($rawData)) {
179 // Not all variable types should be serialized here
180 throw new InvalidArgumentException(sprintf('rawData[]=%s cannot be serialized.', gettype($rawData)));
184 $dummyInstance = new StringUtils();
186 // First "serialize" it (json_encode() is faster than serialize())
187 $encoded = self::packString(json_encode($rawData));
190 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: encoded()=%d - EXIT!', strlen($encoded)));
195 * Converts e.g. a command from URL to a valid class by keeping out bad characters
197 * @param $str The string, what ever it is needs to be converted
198 * @return $className Generated class name
199 * @throws InvalidArgumentException If a paramter is invalid
201 public static final function convertToClassName (string $str) {
202 // Is the parameter valid?
203 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - CALLED!', $str));
205 // No empty strings, please
206 throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT);
207 } elseif (!isset(self::$cache[$str])) {
211 // Convert all dashes in underscores
212 $str = self::convertDashesToUnderscores($str);
214 // Now use that underscores to get classname parts for hungarian style
215 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - AFTER!', $str));
216 foreach (explode('_', $str) as $strPart) {
217 // Make the class name part lower case and first upper case
218 $className .= ucfirst(strtolower($strPart));
222 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: self[%s]=%s - SET!', $str, $className));
223 self::$cache[$str] = $className;
227 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: self[%s]=%s - EXIT!', $str, $className));
228 return self::$cache[$str];
232 * Formats computer generated price values into human-understandable formats
233 * with thousand and decimal separators.
235 * @param $value The in computer format value for a price
236 * @param $currency The currency symbol (use HTML-valid characters!)
237 * @param $decNum Number of decimals after commata
238 * @return $price The for the current language formated price string
239 * @throws MissingDecimalsThousandsSeparatorException If decimals or thousands separator is missing
241 public static function formatCurrency (float $value, string $currency = '€', int $decNum = 2) {
243 $dummyInstance = new StringUtils();
245 // Reformat the US number
246 $price = number_format($value, $decNum, self::$decimals, self::$thousands) . $currency;
248 // Return as string...
253 * Converts a hexadecimal string, even with negative sign as first string to
254 * a decimal number using BC functions.
256 * This work is based on comment #86673 on php.net documentation page at:
257 * <http://de.php.net/manual/en/function.dechex.php#86673>
259 * @param $hex Hexadecimal string
260 * @return $dec Decimal number
262 public static function hex2dec (string $hex) {
263 // Convert to all lower-case
264 $hex = strtolower($hex);
266 // Detect sign (negative/positive numbers)
268 if (substr($hex, 0, 1) == '-') {
270 $hex = substr($hex, 1);
273 // Decode the hexadecimal string into a decimal number
275 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
276 $factor = self::$hexdec[substr($hex, $i, 1)];
277 $dec = bcadd($dec, bcmul($factor, $e));
280 // Return the decimal number
285 * Converts even very large decimal numbers, also signed, to a hexadecimal
288 * This work is based on comment #97756 on php.net documentation page at:
289 * <http://de.php.net/manual/en/function.hexdec.php#97756>
291 * @param $dec Decimal number, even with negative sign
292 * @param $maxLength Optional maximum length of the string
293 * @return $hex Hexadecimal string
295 public static function dec2hex (string $dec, int $maxLength = 0) {
296 // maxLength can be zero or devideable by 2
297 assert(($maxLength == 0) || (($maxLength % 2) == 0));
299 // Detect sign (negative/positive numbers)
306 // Encode the decimal number into a hexadecimal string
309 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
314 * Leading zeros are required for hex-decimal "numbers". In some
315 * situations more leading zeros are wanted, so check for both
318 if ($maxLength > 0) {
319 // Prepend more zeros
320 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
321 } elseif ((strlen($hex) % 2) != 0) {
322 // Only make string's length dividable by 2
326 // Return the hexadecimal string
331 * Converts a ASCII string (0 to 255) into a decimal number.
333 * @param $asc The ASCII string to be converted
334 * @return $dec Decimal number
336 public static function asc2dec (string $asc) {
337 // Convert it into a hexadecimal number
338 $hex = bin2hex($asc);
340 // And back into a decimal number
341 $dec = self::hex2dec($hex);
348 * Converts a decimal number into an ASCII string.
350 * @param $dec Decimal number
351 * @return $asc An ASCII string
353 public static function dec2asc (string $dec) {
354 // First convert the number into a hexadecimal string
355 $hex = self::dec2hex($dec);
357 // Then convert it into the ASCII string
358 $asc = self::hex2asc($hex);
365 * Converts a hexadecimal number into an ASCII string. Negative numbers
368 * @param $hex Hexadecimal string
369 * @return $asc An ASCII string
371 public static function hex2asc ($hex) {
372 // Check for length, it must be devideable by 2
373 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
374 assert((strlen($hex) % 2) == 0);
378 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
379 // Get the decimal number of the chunk
380 $part = hexdec(substr($hex, $idx, 2));
382 // Add it to the final string
386 // Return the final string
391 * Pack a string into a "binary format". Please execuse me that this is
392 * widely undocumented. :-(
394 * @param $str Unpacked string
395 * @return $packed Packed string
396 * @todo Improve documentation
398 private static function packString (string $str) {
399 // First compress the string (gzcompress is okay)
400 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - CALLED!', $str));
401 $str = gzcompress($str);
406 // And start the "encoding" loop
407 for ($idx = 0; $idx < strlen($str); $idx += self::$packingData[self::$archArrayElement]['step']) {
409 for ($i = 0; $i < self::$packingData[self::$archArrayElement]['step']; $i++) {
410 $factor = (self::$packingData[self::$archArrayElement]['step'] - 1 - $i);
412 if (($idx + $i) <= strlen($str)) {
413 $ord = ord(substr($str, ($idx + $i), 1));
415 $add = $ord * pow(256, $factor);
419 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
423 // Left/right parts (low/high?)
424 $l = ($big & self::$packingData[self::$archArrayElement]['left']) >>self::$packingData[self::$archArrayElement]['factor'];
425 $r = $big & self::$packingData[self::$archArrayElement]['right'];
428 $chunk = str_pad(pack(self::$packingData[self::$archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
429 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: big=%d,chunk(%d)=%s', $big, strlen($chunk), md5($chunk)));
435 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: packed=%s - EXIT!', $packed));
440 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
442 * @param $num A string consisting only chars between 0 and 9
443 * @param $assertMismatch Whether to assert mismatches
444 * @return $ret The (hopefully) secured hext-numbered value
446 public static function hexval (string $num, bool $assertMismatch = false) {
447 // Filter all numbers out
448 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
450 // Assert only if requested
451 if ($assertMismatch === true) {
452 // Has the whole value changed?
453 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));