filecage/creator

Resolve classes if callable has no object-context

Opened this issue · 0 comments

It is unsupported to pass a callable to invoke() that is missing the object context:

if (is_array($callable) && count($callable) === 2) {
// todo: Creator should resolve the object if we know the class name
if (!is_object($callable[0])) {
throw new Unresolvable('Unable to handle invokation of object-context callable: no object given on callable index 0');
}

Creator should resolve the object (if it's non-static) and then call the invokable instead of throwing an exception.

Example test case that should pass:

class Foo {
    function __construct($bar) {
        $this->bar = $bar;
    }
}

class BarTransformer {
    function transform ($bar) {
        return strtoupper($bar);
    }
}

class AnyClass {
    static function bax (Foo $foo, BarTransformer $barTransformer) {
        return $barTransformer->transform($foo->bar);
    }

    function __construct(Foo $foo) {
        $this->foo = $foo;
    }

    function bar (BarTransformer $barTransformer) {
        return $barTransformer->transform($this->foo->bar);
    }
}

$creator = new Creator();
$creator->registerClassResource(new Foo('hello world'));

echo $creator->invoke(['AnyClass', 'bax']);
echo $creator->invoke(['AnyClass', 'bar']);

Should output

HELLO WORLD

twice, the first invocation should not register a class resource as the method is only called statically.