Skip to content

Commit

Permalink
[php2cpg] Resolve static method call name when called by self (joerni…
Browse files Browse the repository at this point in the history
…o#3736)

When a static method call is made by referring to `self`, the AST node created for it failed to resolve the proper method full name.

For example:

```
<?php
class Foo {
    static function bar($x) {
        return 0;
    }
    function baz($x) {
        self::bar($x);
    }
}
```

The method full name of the call node for `self::bar($x)` is `self::bar`, but it should be `Foo::bar`.

This PR resolves the method full name of functions called by `self`.
  • Loading branch information
wunused authored Oct 18, 2023
1 parent 407b32f commit 5a970d4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -967,8 +967,10 @@ class AstCreator(filename: String, phpAst: PhpFile)(implicit withSchemaValidatio

val fullName = call.target match {
// Static method call with a known class name
case Some(nameExpr: PhpNameExpr) if call.isStatic =>
s"${nameExpr.name}${StaticMethodDelimiter}$name"
case Some(nameExpr: PhpNameExpr) if call.isStatic => {
if (nameExpr.name == "self") composeMethodFullName(name, call.isStatic)
else s"${nameExpr.name}${StaticMethodDelimiter}$name"
}

case Some(expr) =>
s"$UnresolvedNamespace\\$codePrefix"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,30 @@ class CallTests extends PhpCode2CpgFixture {
}
}

/* This possibly should exist in NamespaceTests.scala */
"static method calls that refer to self" should {
val cpg = code("""
|<?php
|class ClassA {
| function foo($x) {
| return self::bar($x);
| }
| static function bar($param) {
| return 0;
| }
|}
|""".stripMargin)

"resolve the correct method full name" in {
val List(barCall) = cpg.call("bar").take(1).l
barCall.name shouldBe "bar"
barCall.methodFullName shouldBe s"ClassA::bar"
barCall.receiver.isEmpty shouldBe true
barCall.dispatchType shouldBe DispatchTypes.STATIC_DISPATCH
barCall.code shouldBe "self::bar($x)"
}
}

"method calls with simple names should be correct" in {
val cpg = code("<?php\n$f->foo($x);")

Expand Down

0 comments on commit 5a970d4

Please sign in to comment.