3

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.

Pascal
  • 2,175
  • 4
  • 39
  • 57

1 Answers1

6

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.

Tomas Votruba
  • 23,240
  • 9
  • 79
  • 115
  • 1
    I looked at it and it fits mostly my requirement. But how do you handle long lines like: `public function getUrlForRoute(string $routeName, array $parameters = []) : string` which are longer than the allowed 80 chars? – Pascal May 05 '17 at 09:17
  • There is `PHP_CodeSniffer\Standards\Generic\Sniffs\Files\LineLengthSniff` for that. I set it to 120 chars. 80 is way to strict for me and screen width of today's screen :) – Tomas Votruba May 05 '17 at 11:16
  • 1
    @Pascal, in that case, you should use a multiline method signature. SO won't let me add a multiline code example here as a comment. – Jacob Thomason Aug 01 '17 at 20:58