Search code examples
phpphpcs

How to get all php member variables with phpcs


I am trying to get a list of class variables using phpcs but can only get a list of all variables in the file. Has anyone got any ideas on achieving this?

Sniff Code

for ($i = $stackPtr; $i < count ($tokens); $i++) {
    $variable = $phpcsFile->findNext(T_VARIABLE, ($i));
    if ($variable !== false) {
        print ($variable);
    } else {
        break;
    }
}

File to analyse

<?PHP
/** 
 * @package     xxxx
 * @subpackage  Pro/System/Classes
 * @copyright   
 * @author      
 * @link        
 */
class Test_Class_AAA {

    const CONSTANT = 'constant value';
    public $var1 = 12;
    const CONSTANT2 = 'constant value 2';

    /**
     * Return record schema details given a LabelIndentifier/LabelNumber or
     * TransactionCode.
     *
     * @param   string  $type             record type
     * @param   string  $myextralongparam   record type
     * @return  array                       record schema details (or null)
     */
    private function func ($type,$myextralongparam) {
        if (true) {
            $x = 10;
            $y = 11;
            $z = $x + $y;
            $f = $x - $y
            $f = $x * $t;
            $f = $x / $y;
            $f = $x % $y;
            $f = $x ** $y;
            $f += 1;
            $f -= 1;
            $f *= 1;
            $f /= 1;
            $f %= 1;
            if ($x === $y) {
            }
            if ($x !== $y) {
            }
            if ($x < $y) {
            }
            if ($x > $y) {
            }
            if ($x <= $y) {
            }
            if ($x >= $y) {
            }

            ++$x;
        } else {
        }

        while (true) {
        }

        do {
        } while (true);

        for ($i = 0; $i < 5; $i++) {
        }
    };

    /**
     * Return record schema details given a LabelIndentifier/LabelNumber or
     * TransactionCode.
     *
     * @return  array                       record schema details (or null)
     */
    public function __construct () {
        print "In BaseClass constructor\n";
    }
}

Solution

  • I have made ClassWrapper exactly for these use cases.

    You can find inspiration here, in getPropertyNames() method:

    /**
     * Inspired by @see TokensAnalyzer.
     *
     * @return string[]
     */
    public function getPropertyNames(): array
    {
        if ($this->propertyNames) {
            return $this->propertyNames;
        }
    
        $classOpenerPosition = $this->classToken['scope_opener'] + 1;
        $classCloserPosition = $this->classToken['scope_closer'] - 1;
    
        $propertyTokens = $this->findClassLevelTokensType($classOpenerPosition, $classCloserPosition, T_VARIABLE);
    
        $this->propertyNames = $this->extractPropertyNamesFromPropertyTokens($propertyTokens);
        $this->propertyNames = array_merge($this->propertyNames, $this->getParentClassPropertyNames());
    
        return $this->propertyNames;
    }