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.

LazyOne
  • 158,824
  • 45
  • 388
  • 391
SeaFuzz
  • 1,177
  • 9
  • 28
  • Is $pipe an instance of [\Predis\Pipeline\Pipeline](https://github.com/nrk/predis/blob/v1.1/src/Pipeline/Pipeline.php)? – segFault Sep 01 '16 at 02: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). – LazyOne Sep 01 '16 at 10:45

1 Answers1

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 */
});
SeaFuzz
  • 1,177
  • 9
  • 28
segFault
  • 3,887
  • 1
  • 19
  • 31
  • 2
    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. – SeaFuzz Sep 01 '16 at 02:28