4

I'm using Respect/Validation class and I have custom rule CustomRule() which works fine:

use Respect\Validation\Validator as v;

// ...

'email' => v::CustomRule()->email()->setName('email');

But this causes PHPStan to throw an error:

Call to an undefined static method Respect\Validation\Validator::CustomRule().

But if I move it after a built-in rule (e.g., email()), PHPStan works fine, no errors:

'email' => v::email()->CustomRule()->setName('email');

To be clear, both code works but PHPStan thinks the first code is invalid.

Any workaround so that PHPStan will accept it even if CustomRule() was set first?

Update:

I've found that if I edit the doc block of Respect\Validation\Validator class and append my custom rule to the list of its built-in rules, it works!

/**
* ...
* @method static Validator CustomRule()
*/
class Validator extends AllOf
...

Of course it's a bad idea to directly modify the doc block from the main class. That said, my question still remains the same. Or, maybe is there a way for PHPStan to honor my own doc block from my CustomRule class?

IMB
  • 15,163
  • 19
  • 82
  • 140
  • I have the same issue on where the file name and class name doesn't match. `phpstan` will prompt errors complaining it can't find the class of the static function. – Jason Liu Oct 02 '21 at 22:21
  • If you were my case, another possible solution is to use `autoload_files` parameter in the `phpstan.neon`. Reference: https://github.com/phpstan/phpstan/issues/2533 – Jason Liu Oct 03 '21 at 01:27

1 Answers1

3

Ran into the same issue. What I did was just to add the custom Validators to phpstan config file (phpstan.neon). It can be done with regex eg:

parameters:
    ignoreErrors:
        - '#Call to an undefined method Respect\\Validation\\Validator::[a-zA-Z0-9\\_]()#'

Docs: https://github.com/phpstan/phpstan#ignore-error-messages-with-regular-expressions

More of a workaround I guess though.

echibi
  • 31
  • 2
  • 1
    This is just hidding the error but not fixing the issue. Personally I don't like this answer unless there is no choice of fixing. I would like to know the root cause of this phenomenon. – Jason Liu Oct 02 '21 at 22:18
  • 1
    @JasonLiu - there is no issue, it's a false positive. You can tell PHPStan in one of the two ways about it: telling it to hide the error, or write a custom rule that will dynamically provide information about this particular method. The second way is "more correct" in a way, but it's a waste of your time. – Davor Mar 26 '23 at 21:10