From 7d0dbc150148eec4a9c7de76edbb68fe891433ec Mon Sep 17 00:00:00 2001 From: =?utf8?q?Roland=20H=C3=A4der?= Date: Sat, 25 Feb 2023 03:27:31 +0100 Subject: [PATCH] Continued: - added more debug message - FrameworkConfiguration cannot invoke methods from StringUtils while debug lines are active: --------------- PHP Fatal error: Uncaught Error: Class 'Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware' not found in /home/.../core/framework/main/classes/class_BaseFrameworkSystem.php:623 --------------- --- .../config/class_FrameworkConfiguration.php | 6 +- .../tools/console/class_ConsoleTools.php | 33 ++++-- .../classes/utils/arrays/class_ArrayUtils.php | 3 + .../utils/crypto/class_CryptoUtils.php | 14 ++- .../utils/numbers/class_NumberUtils.php | 38 ++++++- .../utils/strings/class_StringUtils.php | 105 +++++++++++++++--- 6 files changed, 167 insertions(+), 32 deletions(-) diff --git a/framework/config/class_FrameworkConfiguration.php b/framework/config/class_FrameworkConfiguration.php index e97eb192..531de648 100644 --- a/framework/config/class_FrameworkConfiguration.php +++ b/framework/config/class_FrameworkConfiguration.php @@ -117,7 +117,7 @@ class FrameworkConfiguration implements Registerable { } // Convert dashes to underscore - $configKey = StringUtils::convertDashesToUnderscores($configKey); + $configKey = str_replace('-', '_', $configKey); // Is a valid configuration key provided? //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, $configKey); @@ -152,7 +152,7 @@ class FrameworkConfiguration implements Registerable { } // Cast to string - $configKey = StringUtils::convertDashesToUnderscores($configKey); + $configKey = str_replace('-', '_', $configKey); // Set the configuration value //* NOISY-DEBUG: */ printf('[%s:%d]: Setting configKey=%s,configValue[%s]=%s - EXIT!' . PHP_EOL, __METHOD__, __LINE__, $configKey, gettype($configValue), $configValue); @@ -204,7 +204,7 @@ class FrameworkConfiguration implements Registerable { } // Convert dashes to underscore - $configKey = StringUtils::convertDashesToUnderscores($configKey); + $configKey = str_replace('-', '_', $configKey); // Is the configuration key there? //* NOISY-DEBUG: */ printf('[%s:%d]: configKey=%s - AFTER!' . PHP_EOL, __METHOD__, __LINE__, $configKey); diff --git a/framework/main/classes/tools/console/class_ConsoleTools.php b/framework/main/classes/tools/console/class_ConsoleTools.php index f4c48d2f..1e309d76 100644 --- a/framework/main/classes/tools/console/class_ConsoleTools.php +++ b/framework/main/classes/tools/console/class_ConsoleTools.php @@ -72,6 +72,7 @@ class ConsoleTools extends BaseFrameworkSystem { */ protected function isProxyUsed () { // Do we have cache? + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!'); if (!isset($GLOBALS[__METHOD__])) { // Determine it $GLOBALS[__METHOD__] = ( @@ -84,6 +85,7 @@ class ConsoleTools extends BaseFrameworkSystem { } // Return cache + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: isUsed=%d', $GLOBALS[__METHOD__])); return $GLOBALS[__METHOD__]; } @@ -98,6 +100,7 @@ class ConsoleTools extends BaseFrameworkSystem { */ protected function setupProxyTunnel (string $host, int $port, $socketResource) { // Validate parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: host=%s,port=%d,socketResource=%s - CALLED!', $host, $port, $socketResource)); if (empty($host)) { // Throw IAE throw new InvalidArgumentException('Parameter "host" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); @@ -127,14 +130,16 @@ class ConsoleTools extends BaseFrameworkSystem { // Add last new-line $proxyTunnel .= self::HTTP_EOL; - //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: proxyTunnel=' . $proxyTunnel); // Write request + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Sending %d bytes to socketResource=%s (proxy tunnel) ...', strlen($proxyTunnel), $socketResource)); fwrite($socketResource, $proxyTunnel); // Got response? + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: feof(%s)=%d', $socketResource, intval(feof($socketResource)))); if (feof($socketResource)) { // No response received + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: response()=%d, feof! - EXIT!', count($response))); return $response; } @@ -147,6 +152,7 @@ class ConsoleTools extends BaseFrameworkSystem { } // All fine! + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: respArray()=%d - EXIT!', count($respArray))); return $respArray; } @@ -235,7 +241,7 @@ class ConsoleTools extends BaseFrameworkSystem { throw new InvalidArgumentException('Parameter "hostname" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); } elseif (self::$isQuietResolver !== TRUE) { // Debug message - self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Host name to resolve is: %s', + self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Host name to resolve is: %s', __CLASS__, $hostname )); @@ -270,14 +276,14 @@ class ConsoleTools extends BaseFrameworkSystem { // Quiet? if (self::$isQuietResolver !== TRUE) { // Debug message - self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Resolved IP address is: %s', + self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Resolved IP address is: %s', __CLASS__, $ipAddress )); } } else { // Problem while resolving IP address - self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.', + self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Problem resolving IP address for host %s. Please check your /etc/hosts file.', __CLASS__, $hostname )); @@ -335,7 +341,7 @@ class ConsoleTools extends BaseFrameworkSystem { $hostname = $_SERVER['COMPUTERNAME']; } else { // Could not find our hostname - self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] WARNING: Cannot acquire my own host name.', + self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] WARNING: Cannot acquire my own host name.', $toolsInstance->__toString() )); } @@ -344,7 +350,7 @@ class ConsoleTools extends BaseFrameworkSystem { //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: hostname=%s from _SERVER array', $hostname)); } catch (FrameworkException $e) { // Output debug message - self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s', + self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('[%s:] Problem while resolving own IP address: [%s|%s]:%s', $toolsInstance->__toString(), $e->__toString(), $e->getHexCode(), @@ -414,6 +420,7 @@ class ConsoleTools extends BaseFrameworkSystem { */ public static function determineExternalAddress () { // Get helper instance + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!'); $toolsInstance = new ConsoleTools(); // First get a socket @@ -425,6 +432,7 @@ class ConsoleTools extends BaseFrameworkSystem { $ipAddress = self::resolveIpAddress(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_host')); // Connect to host through proxy connection + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: ipAddress=%s', $ipAddress)); $socketResource = fsockopen($ipAddress, FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('proxy_port'), $errorNo, $errorStr, 30); } else { // Connect to host directly @@ -432,9 +440,10 @@ class ConsoleTools extends BaseFrameworkSystem { } // Check if there was an error else + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: socketResource[%s]=%s,errorNo=%d,errorStr=%s', gettype($socketResource), $socketResource, $errorNo, $errorStr)); if ($errorNo > 0) { // Then throw again - throw new InvalidSocketException(array($toolsInstance, $socketResource, $errorNo, $errorStr), BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET); + throw new InvalidSocketException([$toolsInstance, $socketResource, $errorNo, $errorStr], BaseFrameworkSystem::EXCEPTION_INVALID_SOCKET); } // Prepare the GET request @@ -465,6 +474,7 @@ class ConsoleTools extends BaseFrameworkSystem { $request .= self::HTTP_EOL; // Send it to the socket + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: Writing %d bytes to socketResource=%s ...', strlen($request), $socketResource)); fwrite($socketResource, $request); // Init IP (this will always be the last line) @@ -473,11 +483,14 @@ class ConsoleTools extends BaseFrameworkSystem { // And read the reply while (!feof($socketResource)) { // Get line + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: feof()=%d', intval(feof($socketResource)))); $externalAddress = trim(fgets($socketResource, 128)); // Detect HTTP response + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CONSOLE-TOOLS: externalAddress=%s', $externalAddress)); if ((substr($externalAddress, 0, 7) == 'HTTP/1.') && (substr($externalAddress, -6, 6) != '200 OK')) { // Stop processing + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CONSOLE-TOOLS: BREAK!'); break; } } @@ -486,7 +499,7 @@ class ConsoleTools extends BaseFrameworkSystem { fclose($socketResource); // Return determined external address - /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('CONSOLE-TOOLS: Resolved external address: ' . $externalAddress); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: externalAddress=%s - EXIT!', $externalAddress)); return $externalAddress; } @@ -499,6 +512,7 @@ class ConsoleTools extends BaseFrameworkSystem { */ public static function analyzeEnvironmentForType () { // Default is the console + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!'); $type = 'console'; // Now, do we have a request method, or query string set? @@ -508,6 +522,7 @@ class ConsoleTools extends BaseFrameworkSystem { } // Return it + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: type=%s - EXIT!', $type)); return $type; } @@ -526,6 +541,7 @@ class ConsoleTools extends BaseFrameworkSystem { */ public static function analyzeEnvironmentForClassType () { // Default is the console + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CONSOLE-TOOLS: CALLED!'); $type = 'console'; // Now, do we have a request method, or query string set? @@ -535,6 +551,7 @@ class ConsoleTools extends BaseFrameworkSystem { } // Return it + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CONSOLE-TOOLS: type=%s - EXIT!', $type)); return $type; } diff --git a/framework/main/classes/utils/arrays/class_ArrayUtils.php b/framework/main/classes/utils/arrays/class_ArrayUtils.php index 6d77c2a7..48b0c581 100644 --- a/framework/main/classes/utils/arrays/class_ArrayUtils.php +++ b/framework/main/classes/utils/arrays/class_ArrayUtils.php @@ -55,6 +55,7 @@ final class ArrayUtils extends BaseFrameworkSystem { */ public static function mapNumericKeysToAssociative (array $numericArray, array $mapping) { // Validate parameters + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('ARRAY-UTILS: numericArray()=%d,mapping()=%d - CALLED!', count($numericArray), count($mapping))); if (count($numericArray) == 0) { // Throw IAE throw new InvalidArgumentException('Array "numericArray" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); @@ -72,6 +73,7 @@ final class ArrayUtils extends BaseFrameworkSystem { // "Walk" over the mapping array foreach ($mapping as $sourceIndex => $targetName) { // Is the source index not there? + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('ARRAY-UTILS: sourceIndex=%d,targetName=%s', $sourceIndex, $targetName)); if (!array_key_exists($sourceIndex, $numericArray)) { // Should always be there! throw new OutOfBoundsException(sprintf('numericArray[%d] does not exist.', $sourceIndex)); @@ -82,6 +84,7 @@ final class ArrayUtils extends BaseFrameworkSystem { } // Return fully mapped array + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('ARRAY-UTILS: mappedArray()=%d - EXIT!', count($mappedArray))); return $mappedArray; } diff --git a/framework/main/classes/utils/crypto/class_CryptoUtils.php b/framework/main/classes/utils/crypto/class_CryptoUtils.php index a90d6500..69885f9b 100644 --- a/framework/main/classes/utils/crypto/class_CryptoUtils.php +++ b/framework/main/classes/utils/crypto/class_CryptoUtils.php @@ -60,13 +60,18 @@ final class CryptoUtils extends BaseFrameworkSystem { */ private static function staticInitializer () { // Is $hashFunction set? + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPRO-UTILS: self::hashFunction[]=%s - CALLED!', gettype(self::$hashFunction))); if (empty(self::$hashFunction)) { // Get instance $dummyInstance = new CryptoUtils(); // Set hash function from configuration + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage('CRYPRO-UTILS: Setting self::hashFunction from configuration entry ...'); self::$hashFunction = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('crypto_hash_function_name'); } + + // Trace message + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPRO-UTILS: EXIT!'); } /** @@ -80,7 +85,7 @@ final class CryptoUtils extends BaseFrameworkSystem { */ public static final function hash (string $str) { // Validate parameter/mhash extension - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CRYPTO-UTILS: str=%s - CALLED!', $str)); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-UTILS: str=%s - CALLED!', $str)); if (empty($str)) { // Throw IAE throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); @@ -90,13 +95,15 @@ final class CryptoUtils extends BaseFrameworkSystem { } // Invoke static initializer + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPRO-UTILS: Invoking self::staticInitializier() ...'); self::staticInitializer(); // Hash given string with (better secure) hasher + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPRO-UTILS: Invoking hash(self::%s,%s,true) ...', $hashFunction, $str)); $hash = hash(self::$hashFunction, $str, true); // Return it - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('CRYPTO-UTILS: hash{}=0x%s - EXIT!', bin2hex($hash))); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPTO-UTILS: hash{}=0x%s - EXIT!', bin2hex($hash))); return $hash; } @@ -108,15 +115,18 @@ final class CryptoUtils extends BaseFrameworkSystem { */ public static final function getHashLength () { // Invoke static initializer + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('CRYPRO-UTILS: Invoking self::staticInitializer() ... - CALLED!'); self::staticInitializer(); // Is it cashed? + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('CRYPRO-UTILS: self::hashLength[%s]=%d', gettype(self::$hashLength), self::$hashLength)); if (is_null(self::$hashLength)) { // No, then hash a string and save its length. self::$hashLength = strlen(self::hash('abc123')); } // Return it + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('CRYPRO-UTILS: self::hashLength=%d - EXIT!', self::$hashLength)); return self::$hashLength; } diff --git a/framework/main/classes/utils/numbers/class_NumberUtils.php b/framework/main/classes/utils/numbers/class_NumberUtils.php index 8e349015..264b17ee 100644 --- a/framework/main/classes/utils/numbers/class_NumberUtils.php +++ b/framework/main/classes/utils/numbers/class_NumberUtils.php @@ -6,6 +6,9 @@ namespace Org\Mxchange\CoreFramework\Utils\Numbers; use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap; use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem; +// Import SPL stuff +use \InvalidArgumentException; + /** * A number utility class * @@ -42,10 +45,18 @@ final class NumberUtils extends BaseFrameworkSystem { /** * Filter a given number into a localized number * - * @param $value The raw value from e.g. database + * @param $value The raw float value from e.g. database * @return $localized Localized value + * @throws InvalidArgumentException If a parameter has an invalid value */ - public static function doFilterFormatNumber ($value) { + public static function doFilterFormatNumber (float $value) { + // Check value + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: value=%s - CALLED!', $value)); + if ($value < 0) { + // Not valid value + throw new InvalidArgumentException(sprintf('value=%s cannot be below zero', $value)); + } + // Generate it from config and localize dependencies switch (FrameworkBootstrap::getLanguageInstance()->getLanguageCode()) { case 'de': // German format is a bit different to default @@ -58,6 +69,7 @@ final class NumberUtils extends BaseFrameworkSystem { } // Return it + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: localized=%s - CALLED!', $localized)); return $localized; } @@ -68,8 +80,16 @@ final class NumberUtils extends BaseFrameworkSystem { * * @param $timestamp Timestamp to prepare (filter) for display * @return $readable A readable timestamp + * @throws InvalidArgumentException If a parameter has an invalid value */ - public static function doFilterFormatTimestamp ($timestamp) { + public static function doFilterFormatTimestamp (string $timestamp = NULL) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: timestamp[%s]=%s - CALLED!', gettype($timestamp), $timestamp)); + if (empty($timestamp)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "timestamp" is empty'); + } + // Default value to return $readable = '???'; @@ -103,6 +123,7 @@ final class NumberUtils extends BaseFrameworkSystem { } // Return the stamp + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: readable=%s - EXIT!', $readable)); return $readable; } @@ -113,24 +134,35 @@ final class NumberUtils extends BaseFrameworkSystem { * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes. * @param $assertMismatch Whether to assert mismatches * @return $formatted The (hopefully) secured numbered value + * @throws InvalidArgumentException If a parameter has an invalid value */ public static function bigintval (string $num, bool $castValue = true, bool $assertMismatch = false) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: num=%s,castValue=%d,assertMismatch=%d - CALLED!', $num, intval($castValue), intval($assertMismatch))); + if ($num === '') { + // Throw IAE + throw new InvalidArgumentException('Parameter "num" is empty'); + } + // Filter all numbers out $formatted = preg_replace('/[^0123456789]/', '', $num); // Shall we cast? + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('NUMBER-UTILS: formatted=%s', $formatted)); if ($castValue === true) { // Cast to biggest numeric type, int is not enough for this cast $formatted = (double) $formatted; } // Assert only if requested + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('NUMBER-UTILS: formatted[%s]=%s', gettype($formatted), $formatted)); if ($assertMismatch === true) { // Has the whole value changed? assert(('' . $formatted . '' != '' . $num . '') && (!is_null($num))); } // Return result + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('NUMBER-UTILS: formatted[%s]=%s - EXIT!', gettype($formatted), $formatted)); return $formatted; } diff --git a/framework/main/classes/utils/strings/class_StringUtils.php b/framework/main/classes/utils/strings/class_StringUtils.php index 2d5861e3..7c6eb7bd 100644 --- a/framework/main/classes/utils/strings/class_StringUtils.php +++ b/framework/main/classes/utils/strings/class_StringUtils.php @@ -129,9 +129,11 @@ final class StringUtils extends BaseFrameworkSystem { */ private function __construct () { // Call parent constructor + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STRING-UTILS: CONSTRUCTED!'); parent::__construct(__CLASS__); // Is one not set? + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: self::archArrayElement=%d', self::$archArrayElement)); if (empty(self::$archArrayElement)) { // Set array element self::$archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32); @@ -140,6 +142,9 @@ final class StringUtils extends BaseFrameworkSystem { self::$thousands = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('thousands_separator'); self::$decimals = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('decimals_separator'); } + + // Trace message + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage('STRING-UTILS: EXIT!'); } /** @@ -152,6 +157,7 @@ final class StringUtils extends BaseFrameworkSystem { */ public static function convertDashesToUnderscores (string $str) { // Validate parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - CALLED!', $str)); if (empty($str)) { // Entry is empty throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); @@ -161,6 +167,7 @@ final class StringUtils extends BaseFrameworkSystem { $str = str_replace('-', '_', $str); // Return converted string + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - EXIT!', $str)); return $str; } @@ -174,7 +181,7 @@ final class StringUtils extends BaseFrameworkSystem { */ public static function encodeData ($rawData) { // Make sure no objects or resources pass through - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: rawData[]=%s - CALLED!', gettype($rawData))); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: rawData[]=%s - CALLED!', gettype($rawData))); if (is_object($rawData) || is_resource($rawData)) { // Not all variable types should be serialized here throw new InvalidArgumentException(sprintf('rawData[]=%s cannot be serialized.', gettype($rawData))); @@ -187,7 +194,7 @@ final class StringUtils extends BaseFrameworkSystem { $encoded = self::packString(json_encode($rawData)); // And return it - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: encoded()=%d - EXIT!', strlen($encoded))); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: encoded()=%d - EXIT!', strlen($encoded))); return $encoded; } @@ -200,7 +207,7 @@ final class StringUtils extends BaseFrameworkSystem { */ public static final function convertToClassName (string $str) { // Is the parameter valid? - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - CALLED!', $str)); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - CALLED!', $str)); if (empty($str)) { // No empty strings, please throw new InvalidArgumentException('Parameter "str" is empty', FrameworkInterface::EXCEPTION_INVALID_ARGUMENT); @@ -212,19 +219,19 @@ final class StringUtils extends BaseFrameworkSystem { $str = self::convertDashesToUnderscores($str); // Now use that underscores to get classname parts for hungarian style - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - AFTER!', $str)); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: str=%s - AFTER!', $str)); foreach (explode('_', $str) as $strPart) { // Make the class name part lower case and first upper case $className .= ucfirst(strtolower($strPart)); } // Set cache - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: self[%s]=%s - SET!', $str, $className)); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: self[%s]=%s - SET!', $str, $className)); self::$cache[$str] = $className; } // Return class name - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: self[%s]=%s - EXIT!', $str, $className)); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: self[%s]=%s - EXIT!', $str, $className)); return self::$cache[$str]; } @@ -240,12 +247,14 @@ final class StringUtils extends BaseFrameworkSystem { */ public static function formatCurrency (float $value, string $currency = '€', int $decNum = 2) { // Init instance + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: value=%s,currency=%s,decNum=%d - CALLED!', $value, $currency, $decNum)); $dummyInstance = new StringUtils(); // Reformat the US number $price = number_format($value, $decNum, self::$decimals, self::$thousands) . $currency; // Return as string... + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: price=%s - EXIT!', $price)); return $price; } @@ -258,8 +267,16 @@ final class StringUtils extends BaseFrameworkSystem { * * @param $hex Hexadecimal string * @return $dec Decimal number + * @throws InvalidArgumentException If a paramter is invalid */ public static function hex2dec (string $hex) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: hex=%s - CALLED!', $hex)); + if (empty($hex)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "hex" is empty'); + } + // Convert to all lower-case $hex = strtolower($hex); @@ -278,6 +295,7 @@ final class StringUtils extends BaseFrameworkSystem { } // Return the decimal number + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: sign=%s,dec=%s - EXIT!', $sign, $dec)); return $sign . $dec; } @@ -291,10 +309,18 @@ final class StringUtils extends BaseFrameworkSystem { * @param $dec Decimal number, even with negative sign * @param $maxLength Optional maximum length of the string * @return $hex Hexadecimal string + * @throws InvalidArgumentException If a paramter is invalid */ - public static function dec2hex (string $dec, int $maxLength = 0) { - // maxLength can be zero or devideable by 2 - assert(($maxLength == 0) || (($maxLength % 2) == 0)); + public static function dec2hex (int $dec, int $maxLength = 0) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: dec=%d,maxLength=%d - CALLED!', $dec, $maxLength)); + if (empty($dec)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "dec" is empty'); + } elseif ($maxLength != 0 && ($maxLength % 2) != 0) { + // Throw it again + throw new InvalidArgumentException(sprintf('maxLength=%d is not dividable by 2 or zero', $maxLength)); + } // Detect sign (negative/positive numbers) $sign = ''; @@ -324,6 +350,7 @@ final class StringUtils extends BaseFrameworkSystem { } // Return the hexadecimal string + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: sign=%s,hex=%s - EXIT!', $sign, $hex)); return $sign . $hex; } @@ -332,15 +359,25 @@ final class StringUtils extends BaseFrameworkSystem { * * @param $asc The ASCII string to be converted * @return $dec Decimal number + * @throws InvalidArgumentException If a paramter is invalid */ public static function asc2dec (string $asc) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: asc=%s - CALLED!', $asc)); + if (empty($asc)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "asc" is empty'); + } + // Convert it into a hexadecimal number $hex = bin2hex($asc); // And back into a decimal number + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: hex=%s', $hex)); $dec = self::hex2dec($hex); // Return it + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: dec=%d - EXIT!', $dec)); return $dec; } @@ -349,15 +386,25 @@ final class StringUtils extends BaseFrameworkSystem { * * @param $dec Decimal number * @return $asc An ASCII string + * @throws InvalidArgumentException If a paramter is invalid */ - public static function dec2asc (string $dec) { + public static function dec2asc (int $dec) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: dec=%d - CALLED!', $dec)); + if (empty($dec)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "dec" is empty'); + } + // First convert the number into a hexadecimal string $hex = self::dec2hex($dec); // Then convert it into the ASCII string + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: hex=%s', $hex)); $asc = self::hex2asc($hex); // Return it + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: asc=%s - EXIT!', $asc)); return $asc; } @@ -367,11 +414,18 @@ final class StringUtils extends BaseFrameworkSystem { * * @param $hex Hexadecimal string * @return $asc An ASCII string + * @throws InvalidArgumentException If a paramter is invalid */ - public static function hex2asc ($hex) { + public static function hex2asc (string $hex) { // Check for length, it must be devideable by 2 - //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex); - assert((strlen($hex) % 2) == 0); + /* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: hex=%s - CALLED!', $hex)); + if (empty($hex)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "hex" is empty'); + } elseif ((strlen($hex) % 2) != 0) { + // Throw it again + throw new InvalidArgumentException(sprintf('hex=%s length not dividable by 2', $hex)); + } // Walk the string $asc = ''; @@ -384,6 +438,7 @@ final class StringUtils extends BaseFrameworkSystem { } // Return the final string + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: asc=%s - EXIT!', $asc)); return $asc; } @@ -393,17 +448,25 @@ final class StringUtils extends BaseFrameworkSystem { * * @param $str Unpacked string * @return $packed Packed string + * @throws InvalidArgumentException If a paramter is invalid * @todo Improve documentation */ private static function packString (string $str) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: str=%s - CALLED!', $str)); + if (empty($str)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "str" is empty'); + } + // First compress the string (gzcompress is okay) - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: str=%s - CALLED!', $str)); $str = gzcompress($str); // Init variable $packed = ''; // And start the "encoding" loop + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: Looping through str()=%d ...', strlen($str))); for ($idx = 0; $idx < strlen($str); $idx += self::$packingData[self::$archArrayElement]['step']) { $big = 0; for ($i = 0; $i < self::$packingData[self::$archArrayElement]['step']; $i++) { @@ -426,13 +489,13 @@ final class StringUtils extends BaseFrameworkSystem { // Create chunk $chunk = str_pad(pack(self::$packingData[self::$archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT); - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: big=%d,chunk(%d)=%s', $big, strlen($chunk), md5($chunk))); + //* N NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: big=%d,chunk(%d)=%s', $big, strlen($chunk), md5($chunk))); $packed .= $chunk; } // Return it - //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('STRING-UTILS: packed=%s - EXIT!', $packed)); + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: packed=%s - EXIT!', $packed)); return $packed; } @@ -442,18 +505,28 @@ final class StringUtils extends BaseFrameworkSystem { * @param $num A string consisting only chars between 0 and 9 * @param $assertMismatch Whether to assert mismatches * @return $ret The (hopefully) secured hext-numbered value + * @throws InvalidArgumentException If a paramter is invalid */ public static function hexval (string $num, bool $assertMismatch = false) { + // Check parameter + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: num=%s,assertMismatch=%d - CALLED!', $num, intval($assertMismatch))); + if (empty($num)) { + // Throw IAE + throw new InvalidArgumentException('Parameter "num" is empty'); + } + // Filter all numbers out $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num); // Assert only if requested + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugMessage(sprintf('STRING-UTILS: ret=%s', $ret)); if ($assertMismatch === true) { // Has the whole value changed? assert(('' . $ret . '' != '' . $num . '') && (!is_null($num))); } // Return result + //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->traceMessage(sprintf('STRING-UTILS: ret=%s - EXIT!', $ret)); return $ret; } -- 2.39.5