2
votes

I have classes with static methods that I need to change to instance methods for unit testing. However I can not change the code that calls them statically. So I'm trying to implement a facade (similar to what Laravel does) so that I can call the functions both statically and dynamically. My code itself is working, but PHPStorm is complaining about the static calls. Here is my facade class with a test child class and phpunit test:

abstract class Facade
{
    /**
     * Handle dynamic, static calls to the object.
     *
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        $instance = new static;
        return call_user_func_array([$instance, $method], $parameters);
    }
}

class Foo extends Facade
{
    /**
     * @param string $param1
     * @return string
     */
    public function TestMethod1($param1)
    {
        return 'Test: '.$param1;
    }
}

class FooTest extends \PHPUnit_Framework_TestCase
{
    public function testFacade()
    {
        $param1 = 'ok';
        $result = Foo::TestMethod1($param1);
        $this->assertEquals('Test: '.$param1, $result);
    }
}

I have tried using phpdoc @method on Foo and @static on the TestMethod1 method, but neither seems to work. How can I get PHPStorm to stop complaining about the static calls? Is there a way to handle this other than turning off the inspection?

1
"How can I get PHPStorm to stop complaining about the static calls?" Disable that particular inspection.Otherwise I see no other way.LazyOne

1 Answers

2
votes

My code itself is working,

It's only working because you do not use $this within TestMethod1 and don't run the test in strict mode.

__callStatic is never called because Foo::TestMethod1() references an existing method, even if it is not declared static.

Try it out:

https://3v4l.org/rsR71

class T
{
    public static function __callStatic($method, $args)
    {
        echo "__callStatic() called\n";
    }
    public function f()
    {
        echo "f() called\n";
    }
}

T::f();

Output for hhvm-3.6.1 - 3.9.0

f() called

Output for 7.0.0alpha1 - 7.0.0rc3

Deprecated: Non-static method T::f() should not be called statically in /in/rsR71 on line 15
f() called

Output for 5.4.8 - 5.6.13

Strict Standards: Non-static method T::f() should not be called statically in /in/rsR71 on line 15
f() called