Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPCS rule for type hinting

Tags:

php-7.1

phpcs

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.

like image 289
Pascal Avatar asked Jul 29 '26 02:07

Pascal


1 Answers

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

  • How to Complete Type Declarations without Docblocks with Rector
  • The Rocket Science Behind Migration of Docblock Types to PHP Typehints

Initial answer:

You can use TypeHintDeclarationSniff from Slevomat/CodingStandard for this.

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

like image 129
Tomas Votruba Avatar answered Aug 02 '26 14:08

Tomas Votruba