SeaFuzz SeaFuzz - 3 months ago 17
PHP Question

PHPdoc and Methods Anonymous functions

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.

Answer

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 */
});
Comments