-
-
Notifications
You must be signed in to change notification settings - Fork 513
Consider adopting type declarations #1863
Description
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
nullinstead offalsein "unhappy path" situations, e.g. from::get_post()when no post found - Declare types of object properties
- Declare
objectparam 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.