Search code examples
php-7.1phpcs

PHPCS rule for type hinting


Is there a rule to check all functions for type hinting?

/**
 * Set the part name.
 *
 * @param   string    $name   The part name.
 */
public function setName(string $name) : void
{
    $this->name = $name;
}

So for example it has to have a type in front of the argument and the function has to have a specified return type.


Solution

  • 2019 update - even Smarter

    In time, my previous answer - TypeHintDeclarationSniff - has shown as very buggy. To be specific:

     public function anotherMethod(int $value)
     {
         // $value is known integer
         $this->someMethod($value);
     }
    
    
     /**
      * @param string $value
      */
    -private function someMethod($value)
    +private function someMethod(string $value)  // here should be "int"
     {
     }
    

    Missed cases:

    public function getItems() // here should be "array"
    {
        return ['Statie', 'EasyCodingStandard', 'Rector'];
    }
    

    Or:

    public function getResult() // here should be "float"
    {
        if (true) {
            return 5.2;
        }
    
        return 5.3;
    }
    

    Or even breaks the code with parent type in /vendor. Why? Because it's based on strings and token, not a static analysis of the code.

    This made many people very angry, after I recommended them this sniff. Obviously.


    How to do it Better?

    I wrote a tool called Rector (https://github.com/rectorphp/rector), that takes into account other variables and other classes and their types.

    That way you can complete type declarations to a code without any @param or @return annotations.


    How to use It?

    Install:

    composer require vendor/bin/rector 
    

    Setup rector.yaml config:

    # rector.yaml
    services:
        Rector\Php\Rector\FunctionLike\ParamTypeDeclarationRector: ~
        Rector\Php\Rector\FunctionLike\ReturnTypeDeclarationRector: ~
    

    Use:

    vendor/bin/rector process src --dry-run # preview
    vendor/bin/rector process src # change
    

    That's it!

    Read Behind the Scenes


    Initial answer:

    You can use TypeHintDeclarationSniff from Slevomat/CodingStandard for this.

    I use it for over a year and it works perfectly.