Add ClassLike::getMethod($name)

To allow getting individual method with a given name.
This commit is contained in:
Nikita Popov 2015-07-14 17:07:45 +02:00
parent 5ede167835
commit d341d94976
2 changed files with 39 additions and 0 deletions

View File

@ -10,6 +10,11 @@ abstract class ClassLike extends Node\Stmt {
/** @var Node[] Statements */
public $stmts;
/**
* Gets all methods defined directly in this class/interface/trait
*
* @return ClassMethod[]
*/
public function getMethods() {
$methods = array();
foreach ($this->stmts as $stmt) {
@ -19,4 +24,21 @@ abstract class ClassLike extends Node\Stmt {
}
return $methods;
}
/**
* Gets method with the given name defined directly in this class/interface/trait.
*
* @param string $name Name of the method (compared case-insensitively)
*
* @return ClassMethod|null Method node or null if the method does not exist
*/
public function getMethod($name) {
$lowerName = strtolower($name);
foreach ($this->stmts as $stmt) {
if ($stmt instanceof ClassMethod && $lowerName === strtolower($stmt->name)) {
return $stmt;
}
}
return null;
}
}

View File

@ -39,4 +39,21 @@ class ClassTest extends \PHPUnit_Framework_TestCase
$this->assertSame($methods, $class->getMethods());
}
public function testGetMethod() {
$methodConstruct = new ClassMethod('__CONSTRUCT');
$methodTest = new ClassMethod('test');
$class = new Class_('Foo', array(
'stmts' => array(
new ClassConst(array()),
$methodConstruct,
new Property(0, array()),
$methodTest,
)
));
$this->assertSame($methodConstruct, $class->getMethod('__construct'));
$this->assertSame($methodTest, $class->getMethod('test'));
$this->assertNull($class->getMethod('nonExisting'));
}
}