+
+ /**
+ * Perform a custom function on a text after having escaped blocks matched by the provided regular expressions.
+ * Only full matches are used, capturing group are ignored.
+ *
+ * To change the provided text, the callback function needs to return it and this function will return the modified
+ * version as well after having restored the escaped blocks.
+ *
+ * @param string $text
+ * @param string $regex
+ * @param callable $callback
+ *
+ * @return string
+ */
+ public static function performWithEscapedBlocks(string $text, string $regex, callable $callback): string
+ {
+ // Enables nested use
+ $executionId = random_int(PHP_INT_MAX / 10, PHP_INT_MAX);
+
+ $blocks = [];
+
+ $return = preg_replace_callback($regex,
+ function ($matches) use ($executionId, &$blocks) {
+ $return = '«block-' . $executionId . '-' . count($blocks) . '»';
+
+ $blocks[] = $matches[0];
+
+ return $return;
+ },
+ $text
+ );
+
+ if (is_null($return)) {
+ Logger::notice('Received null value from preg_replace_callback', ['text' => $text, 'regex' => $regex, 'blocks' => $blocks, 'executionId' => $executionId, 'callstack' => System::callstack(10)]);
+ }
+
+ $text = $callback($return ?? $text) ?? '';
+
+ // Restore code blocks
+ $text = preg_replace_callback('/«block-' . $executionId . '-([0-9]+)»/iU',
+ function ($matches) use ($blocks) {
+ $return = $matches[0];
+ if (isset($blocks[intval($matches[1])])) {
+ $return = $blocks[$matches[1]];
+ }
+ return $return;
+ },
+ $text
+ );
+
+ return $text;
+ }
+
+ /**
+ * This function converts a PHP's shorhand notation string for file sizes into an integer number of total bytes.
+ * For example: The string for shorthand notation of '2M' (which is 2,097,152 Bytes) is converted to 2097152
+ * @see https://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
+ * @param string $shorthand
+ * @return int
+ */
+ public static function getBytesFromShorthand(string $shorthand): int
+ {
+ $shorthand = trim($shorthand);
+
+ if (is_numeric($shorthand)) {
+ return $shorthand;
+ }
+
+ $last = strtolower($shorthand[strlen($shorthand)-1]);
+ $shorthand = substr($shorthand, 0, -1);
+
+ switch($last) {
+ case 'g':
+ $shorthand *= 1024;
+ case 'm':
+ $shorthand *= 1024;
+ case 'k':
+ $shorthand *= 1024;
+ }
+
+ return $shorthand;
+ }
+