Created
October 5, 2024 12:24
-
-
Save caendesilva/df20f6d1a6b3fa853efa421ad7ecaa4f to your computer and use it in GitHub Desktop.
PHP CLI Function Caller Script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
if ($argc < 2) { | |
echo "Usage: phpf <function_name> [arguments...]\n"; | |
exit(1); | |
} | |
$function_name = $argv[1]; | |
$args = array_slice($argv, 2); | |
if (!function_exists($function_name)) { | |
echo "Error: Function '$function_name' does not exist.\n"; | |
exit(1); | |
} | |
// Process arguments | |
$processed_args = []; | |
$current_arg = ''; | |
$in_quotes = false; | |
foreach ($args as $arg) { | |
if (strpos($arg, '"') === 0 && strrpos($arg, '"') === strlen($arg) - 1) { | |
// Argument is already properly quoted | |
$processed_args[] = substr($arg, 1, -1); | |
} elseif (strpos($arg, '"') === 0) { | |
// Start of a quoted argument | |
$current_arg = substr($arg, 1); | |
$in_quotes = true; | |
} elseif (strrpos($arg, '"') === strlen($arg) - 1 && $in_quotes) { | |
// End of a quoted argument | |
$current_arg .= ' ' . substr($arg, 0, -1); | |
$processed_args[] = $current_arg; | |
$current_arg = ''; | |
$in_quotes = false; | |
} elseif ($in_quotes) { | |
// Middle of a quoted argument | |
$current_arg .= ' ' . $arg; | |
} else { | |
// Regular argument | |
$processed_args[] = $arg; | |
} | |
} | |
// Handle comma-separated arguments | |
$final_args = []; | |
foreach ($processed_args as $arg) { | |
if (strpos($arg, ',') !== false) { | |
$final_args = array_merge($final_args, explode(',', $arg)); | |
} else { | |
$final_args[] = $arg; | |
} | |
} | |
// Convert numeric strings to actual numbers | |
$final_args = array_map(function($arg) { | |
return is_numeric($arg) ? $arg + 0 : $arg; | |
}, $final_args); | |
// Call the function and output the result | |
$result = call_user_func_array($function_name, $final_args); | |
echo $result . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment