cakephpphpstan

phpstan undefined (magic?) method


In CakePHP; the ORM supports an SQL function abstraction layer; so you can use functions like "SUM" and "MAX". These functions are defined in the FunctionBuilder. Cake also lets you use custom functions; I don't understand the implementation but the example it gives is below:

    //.. 
    $foo->select([
        'another_field' => $foo->func()->sum('total'), // is a defined method
        'field_name' => $foo->func()->date_format([  // date_format is not defined; but it is a valid function
            'another_field' => 'identifier', 
            "'%M %Y'" => 'literal'
          ]) 
    ]);

phpstan is reporting

235    Call to an undefined method Cake\Database\FunctionsBuilder::date_format().

I understand why phpstan is reporting this; but I don't know enough how to suppress it. It suggests I create the method in the FunctionsBuilder file, but this would be making changes to the vendor files.

The internet would suggest not to ignore this warning; but equally in the current usage, it's not really a problem so one would hope there's a flag to "ignore" the message in phpstan or a /*@var ... override? */


Solution

  • To solve "Call to an undefined method" you have a couple of options:

    1. You can use stub files to override the PHPDoc above FunctionsBuilder class. You can provide magic @method PHPDoc tags to describe these extra methods that exist thanks to __call:
    namespace Cake\Database;
    
    /**
     * @method string dateFormat(array<mixed> $args)
     */
    class FunctionsBuilder
    {
    }
    
    1. You can write a custom class reflection extension that lets you define which magic methods exist on a class in a flexible way - you could list which database functions are valid based on some custom logic.