objects = array(); } public function callback($object) { $this->objects[] = $object; } private function parse_and_count_type($code, $type, $fetch_mode = PHPPARSER_FETCH_ALL) { $this->objects = array(); $this->parser = new PHPParser($fetch_mode); $this->parser->registerCallback(array($this, 'callback')); $this->parser->parse($code); $count = 0; foreach ($this->objects as $o) { if ($type == $o['type']) $count++; } return $count; } public function testFetchClassDefinitions() { $code = ''; $this->assertEquals(3, $this->parse_and_count_type($code, PHPPARSER_CLASS_DEF, PHPPARSER_FETCH_CLASSES)); } public function testFetchFunctionDefinitions() { $code = ''; $this->assertEquals(2, $this->parse_and_count_type($code, PHPPARSER_FUNCTION_DEF, PHPPARSER_FETCH_FUNCTIONS)); } public function testFetchMethodDefinitions() { $code = ''; $this->assertEquals(3, $this->parse_and_count_type($code, PHPPARSER_FUNCTION_DEF, PHPPARSER_FETCH_FUNCTIONS)); } public function testFetchFunctionCalls() { $code = ''; $this->assertEquals(3, $this->parse_and_count_type($code, PHPPARSER_FUNCTION_CALL, PHPPARSER_FETCH_CALLS)); } public function testFetchIncludes() { $code = ''; $this->assertEquals(4, $this->parse_and_count_type($code, PHPPARSER_INCLUDE, PHPPARSER_FETCH_INCLUDES)); } public function testFetchConstructs() { $code = ''; $this->assertEquals(3, $this->parse_and_count_type($code, PHPPARSER_LANGUAGE_CONSTRUCT, PHPPARSER_FETCH_CONSTRUCTS)); } public function testFetchAssignments() { /* Function arguments count as an assignment (as they are assigned when the function is called) Variables that are declared are considered assigned, even if no value is actually set. List assignments are counted once for each item in the list The final line here tests nested expressions, which should be solved from the inside out. */ $code = ''; $this->parse_and_count_type($code, PHPPARSER_ASSIGNMENT, PHPPARSER_FETCH_EXPRESSIONS); $assignments = array(); foreach ($this->objects as $object) { if (PHPPARSER_ASSIGNMENT == $object['type']) $assignments[] = $object['name']; } $expected = array( '$array=$array', '$dbconn=$dbconn', '$options=$options', '$foo="bar"', '$a=$array', '$b=$array', '$c=$array', '$hash["answer"]=42', '$data[$index[0]]="complex"', '$index=0', '$data[$index = 0]="nested"', ); $this->assertEquals($expected, $assignments); } public function testCommentedCode() { $code = ''; $this->assertEquals(0, $this->parse_and_count_type($code, PHPPARSER_VARIABLE, PHPPARSER_FETCH_EXPRESSIONS)); } } ?>