Skip to content

Consider adopting type declarations #1863

@acobster

Description

@acobster

PHP 5.1+ allows for declaring arrays and class/interface names in method signatures, e.g.

class Post {
  public function my_method( Post $post ) {
    return $post->meta('whatever');
  }

  public function other_method( array $data ) {
    return $data['some_index'];
  }
}

This results in much clearer error messages when the caller passes something other than the declared type. For example, Uncaught TypeError: Argument 1 passed to Post::my_method() must be an instance of Post, null given instead of Uncaught Error: Call to a member function meta() on null. Whereas the latter error tells the caller "there's an error happening somewhere in my_method()", which could imply a bug in the library code, the former says definitively "you're doing it wrong."

Another benefit is much greater leverage from PHPStan, which we've already adopted.

We should consider adopting this as much as possible across the Timber codebase for 2.0. A major upgrade is really the only appropriate time to do this, as this is fundamentally a breaking change.

Here are some changes we should consider making:

  • Require PHP 7.3 or 7.4 (7.2 to be EOL'd November 2020)
  • Nullable types in the top-level API/Factories - requires 7.1+, returning null instead of false in "unhappy path" situations, e.g. from ::get_post() when no post found
  • Declare types of object properties
  • Declare object param types in certain Factory methods

All of this would be a pain to do manually, but with Rector we might be able to automate a lot of this as outlined in #2339.

Metadata

Metadata

Assignees

Labels

2.0feature-requesthelp wantedDo you know computer? Then lend a hand and have your code live in infamy!

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions