Last active
March 25, 2025 17:05
-
-
Save RikudouSage/18defbf1746322a289ae78b2980d0115 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<?php | |
// the function reads the comment added after the function is called using a backtrace and uses them as arguments | |
function add(): float | |
{ | |
$trace = debug_backtrace(); | |
$file = $trace[0]['file']; | |
$line = $trace[0]['line']; | |
$content = file($file); | |
$lineContent = trim($content[$line - 1]); | |
$ast = token_get_all("<?php\n{$lineContent}"); | |
$args = []; | |
foreach ($ast as $token) { | |
if (!is_array($token)) { | |
continue; | |
} | |
if ($token[0] !== T_COMMENT) { | |
continue; | |
} | |
$commentContent = $token[1]; | |
if (str_starts_with($commentContent, '#')) { | |
$commentContent = substr($commentContent, 1); | |
} else { | |
$commentContent = substr($commentContent, 2); | |
} | |
$commentContent = trim($commentContent); | |
$commentContent = preg_replace("@\s+@", " ", $commentContent); | |
$args = explode(" ", $commentContent); | |
$args = array_map(function (string $arg) { | |
if (!is_numeric($arg)) { | |
throw new InvalidArgumentException('Argument must be a number'); | |
} | |
return str_contains($arg, '.') ? (float) $arg : (int) $arg; | |
}, $args); | |
break; | |
} | |
return array_sum($args); | |
} | |
echo add(); // 7 8 9 | |
// the above code prints 24 | |
echo add(); # 1 2 3 | |
// the above code prints 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment