2

I am trying to solve an annoying problem with PhpStorm's code validation when it comes to anonymous function. It does not see the passed object's methods.

The code snippet below relies on Predis and the pipeline method.

startCacheClient()

Instantiates and returns an instance of predis.

pipeline()

validates as it should, however

$pipe-set() and $pipe->expire()

Fail to validate and returns "Method 'Set' Not Found in" and "Method 'Expire' Not Found in"

    $this->i = 0;
    $this->startCacheClient()->pipeline(function($pipe) use($values, $jsonEncode, $keepAlive){

        foreach($values as $key => $currentValue){

            if($jsonEncode) {
                $currentValue = gzcompress(json_encode($currentValue), -1);
            }

            $pipe->set($key, $currentValue);
            $pipe->expire($key, $keepAlive);

            $this->i++;
        }
    });

How can I get PhpStorm through PHPDoc to understand that these methods are actually there and available. The code functions as expected, but validation notice is annoying.

2
  • Is $pipe an instance of \Predis\Pipeline\Pipeline? Commented Sep 1, 2016 at 2:11
  • In case if you need an actual PHPDoc solution: /** @var \Predis\ClientContextInterface $pipe */ -- place such line somewhere inside the anonymous function (e.g. just after function body is started -- before any of the code -- before foreach statement in your original code sample) -- should work (not 100% sure though). Commented Sep 1, 2016 at 10:45

1 Answer 1

4

If $pipe is an instance of \Predis\Pipeline\Pipeline, then you could type hint within the anonymous function declaration like:

$this->startCacheClient()->pipeline(function(\Predis\ClientContextInterface $pipe) use($values, $jsonEncode, $keepAlive){
    /* DO STUFF HERE */
});
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Why I didn't think of that, I will never know. Thanks for the help. Ended up pointing to the interface. I updated your code snippet to show the final implementation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.