Improve format_callable()

This commit is contained in:
Benjamin Renard 2024-09-26 13:52:39 +02:00
parent 0e8009420c
commit d72f45ebb2
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -746,20 +746,76 @@ function dumpFile($file_path, $mime_type=null, $max_age=3600, $force_download=fa
/**
* Format a callable object for logging
* @param callable $callable The callable object
* @param string|array|\ReflectionMethod|\ReflectionFunction $callable The callable object
* @param null|array<int,mixed> $args Optional argument(s)
* @return string The callable object string representation
*/
function format_callable($callable) {
function format_callable($callable, $args=null) {
$formatted_args = format_callable_args($args);
if (is_string($callable))
return $callable."()";
if (is_array($callable) && count($callable)==2)
if (is_string($callable[0]))
return $callable[0]."::".$callable[1]."()";
elseif (is_object($callable[0]))
return get_class($callable[0])."->".$callable[1]."()";
else
return "Unkown->".$callable[1]."()";
return varDump($callable);
return $callable."($formatted_args)";
if (is_array($callable))
if (is_string($callable[0]))
return $callable[0]."::".$callable[1]."($formatted_args)";
elseif (is_object($callable[0]))
return get_class($callable[0])."->".$callable[1]."($formatted_args)";
else
return "Unknown->".$callable[1]."($formatted_args)";
if ($callable instanceof \ReflectionFunction)
return sprintf("%s(%s)", $callable->name, $formatted_args);
if ($callable instanceof \ReflectionMethod)
return sprintf(
"%s::%s(%s)",
$callable->class,
$callable->name,
$formatted_args
);
return sprintf("%s(%s)", varDump($callable), $formatted_args);
}
/**
* Format callable arguments for logging
* @param array<mixed> $args Arguments
* @param string|null $prefix Prefix to append at the beginning of each return lines (optional,
* default: no prefix)
* @param int $arg_max_length Argument export max length: above, it will be truncated (optional,
* default: do not truncate)
* @return string
*/
function format_callable_args($args, $prefix=null, $arg_max_length=null) {
if (!is_array($args) || empty($args))
return "";
$prefix = is_string($prefix)?$prefix:"";
$formatted_args = [];
$new_line = false;
foreach($args as $arg) {
try {
$formatted = preg_replace(
"/\s=>\s+(array|\\\\)/m",
" => $1",
@var_export($arg, true)
);
if ($arg_max_length && mb_strlen($formatted) > $arg_max_length) {
$formatted = rtrim(substr($formatted, 0, $arg_max_length));
$formatted .= strpos($formatted, "\n")?"\n[...]":"[...]";
}
$formatted_args[] = $formatted;
$new_line = $new_line || (strpos($formatted, "\n") !== false);
}
catch (Exception $e) {
$formatted_args[] = "<".gettype($arg).">";
}
}
if ($new_line) {
for($i=0; $i < count($formatted_args); $i++) {
$formatted_args[$i] = implode(
"\n$prefix ",
explode("\n", $formatted_args[$i])
);
}
return "\n$prefix ".implode(",\n$prefix ", $formatted_args)."\n$prefix";
}
return implode(", ", $formatted_args);
}
function is_empty($val) {