Skip to content

Instantly share code, notes, and snippets.

@tonylegrone
Last active July 1, 2020 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tonylegrone/8742453 to your computer and use it in GitHub Desktop.
Save tonylegrone/8742453 to your computer and use it in GitHub Desktop.
<?php
/**
* Returns an array of function names in a file.
*
* @param (string) $file
* The path to the file.
*
* @param (bool) $sort
* If TRUE, sorts results by funciton name.
*/
function get_functions_in_file($file, $sort = FALSE) {
$file = file($file);
$functions = array();
foreach ($file as $line) {
$line = trim($line);
if (substr($line, 0, 8) == 'function') {
$functions[] = substr($line, 9, strpos($line, '(') - 9);
}
}
if ($sort) {
asort($functions);
$functions = array_values($functions);
}
return $functions;
}
@miradnan
Copy link

This fails in cases where we use access property types like public, protected, private and static etc.

Here is the fix to that

function get_functions_in_file($file, $sort = FALSE) {
    $file = file($file);
    $functions = array();
    foreach ($file as $line) {
        $line = trim($line);
        if (stripos($line, ' function ') !== false) {
            $function_name = str_ireplace([
                'public', 'private', 'protected',
                'static'
                    ], '', $line);

            if (!in_array($function_name, ['__construct', '__destruct'])) {
                $functions[] = trim(substr($function_name, 9, strpos($function_name, '(') - 9));
            }
        }
    }
    if ($sort) {
        asort($functions);
        $functions = array_values($functions);
    }
    return $functions;
}

@Parviz-Elite
Copy link

Parviz-Elite commented Jul 1, 2020

a little fixe's :

function getFileFunctions (string $filePath, bool $sort = false) : array {
	$file      = file($filePath);
	$functions = [];

	foreach ( $file as $line ) {
		$line = trim($line);

		if ( stripos($line, 'function ') !== false ) {
			$function_name = trim(str_ireplace([
				'public',
				'private',
				'protected',
				'static'
			], '', $line));

			$function_name = trim(substr($function_name, 9, strpos($function_name, '(') - 9));

			if ( !in_array($function_name, ['__construct', '__destruct', '__get', '__set', '__isset', '__unset']) ) {
				$functions[] = $function_name;
			}
		}
	}

	if ( $sort ) {
		asort($functions);
		$functions = array_values($functions);
	}

	return $functions;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment