phpstan-drupal icon indicating copy to clipboard operation
phpstan-drupal copied to clipboard

Detect when Form API #ajax callback is invoked statically but the method is not static

Open mglaman opened this issue 4 years ago • 1 comments

In PHP 7 calling a non-static method statically only threw a notice or warning. In PHP 8 it will cause EXPLOSIONS 🤯 .

Example code:

class MyForm extends BaseForm {
    
    public function buildForm() {
        $form['foo']['#ajax']['callback'] = [static::class, 'ajaxCallback'];
    }
    
    // This will error
    public function ajaxCallback() {
        
    }

    // This will not.
    public static function ajaxCallback() {

    }
    
}

Since the callback is nested in a Form API structure, PHPStan will not detect that we're eventually going to call this method. So we need a custom rule to make sure the AJAX callback is static if invoked statically.

mglaman avatar Oct 14 '21 20:10 mglaman

For this we just need to read #ajax.callback and check if isCallable. That will find out if it has been statically called or not once https://github.com/phpstan/phpstan/issues/5782 lands.

mglaman avatar Jan 05 '22 22:01 mglaman