Skip to content

Instantly share code, notes, and snippets.

@mortenscheel
Last active June 14, 2024 07:31
Show Gist options
  • Save mortenscheel/667a162bf5fe8b2aad0be45c9ae9144e to your computer and use it in GitHub Desktop.
Save mortenscheel/667a162bf5fe8b2aad0be45c9ae9144e to your computer and use it in GitHub Desktop.
PHP callable to source code
<?php
public function callableToCode(mixed $callable): ?string
{
if (is_string($callable) && str_contains($callable, '@')) {
$callable = explode('@', $callable);
}
if (is_array($callable) && count($callable) === 2) {
[$class, $method] = $callable;
$instance = app($class);
$callable = $instance->$method(...);
}
try {
$reflection = new ReflectionFunction($callable);
} catch (ReflectionException) {
return null;
}
if ($path = $reflection->getFileName()) {
$file = file($path);
$start = $reflection->getStartLine() - 1;
$end = $reflection->getEndLine();
$length = $end - $start;
$lines = collect(array_slice($file, $start, $length))->map(fn($line) => rtrim($line));
$indent = $lines->filter()->min(fn(string $line) => strlen($line) - strlen(ltrim($line)));
return $lines->map(function(string $line) use ($indent) {
if (preg_match('/\S/', $line)) {
return substr($line, $indent);
}
return $line;
})->join(PHP_EOL);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment