yiisoft / injector

PSR-11 compatible injector
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
43 stars 18 forks source link

Bug with closure::fromcallable and static scope ? #57

Closed ncou closed 2 years ago

ncou commented 2 years ago

Hi,

nice piece of code. I think i found a small bug during a test using a __callStatic function (but i think it should appen with all statically called functions).

I got this error : Error: Cannot access static:: when no class scope is active when i do the following test :


......
$container = $this->getContainer();
$result = (new Injector($container))->invoke([InvokerTestStaticMagicMethodFixture::class, 'foo']);

$this->assertSame('bar', $result);
......

class InvokerTestStaticMagicMethodFixture
{
    /** @var bool */
    public static $wasCalled = false;
    public static function __callStatic(string $name, array $args): string
    {
        if ($name === 'foo') {
            static::$wasCalled = true;
            return 'bar';
        }
        throw new \Exception('Unknown method');
    }
}

I think it's because the original callable is wrapped around a Closure, but the static scope is not binded. But i am not really sure :-)

Tell me if you need more details. Keep up the good work.

vjik commented 2 years ago

Injector correctly work with method __callStatic(), I'm added test: https://github.com/yiisoft/injector/pull/58.

But you right, reason of error is wrap callable to Closure. Problem in class InvokerTestStaticMagicMethodFixture: static use current scope, but in Closure scope is changed. For fix replace static::$wasCalled = true; to self::$wasCalled = true;.