Wednesday, August 27, 2014

How to extract function names/method names from a PHP class using bash

As a developer, every one of us needs to document the code. It's very handy to have all of the functions/method names from a class we made to explain what every one of does.
I suppose there are a lot of commercial solutions on the market, however, a developer should always accept new challenges, at least that's what I tend to do. Since we are dealing with PHP, and the most common environment for PHP is LAMP, I decide to use bash. After some research, I found that other people felt the necessity of a list of methods from a class, so after reading this post:
Extract function names and directories from php files

I managed to come up with a shell script that will use the same idea, but will be reusable. The code follows :

#!/bin/bash
IFS='/' read -ra ADDR <<< "$1"
#explode path and get the file name-last substring
tLen=`expr ${#ADDR[@]} - 1`
fName=${ADDR[$tLen]}
#make new filename
newFname="$fName.doc"
#print the current file
echo "*********Class $fName *********" >$newFname
#print the functions
find $1 -name '*.php' | xargs egrep -o 'p[a-zA-Z_]* function[ \t][ \t]*[a-zA-Z_]*([0-9a-zA-Z_]*)' >> $newFname

This will generate a new file with a heading and a list of all of the methods/functions in that file, i.e. if we want to list the NewUser.php file :


class NewUser{
   public function getName(){

   }
   public function getEmail(){

   }
   public function getAddress(){

   }
}


the output would be a new file NewUser.php.doc  :

*********Class NewUser.php *********
function getName
function getEmail
function getAddress


and there you go, you have a list of all of the methods in a PHP class.


 

No comments:

Post a Comment