tl;dr Download phpdoc-to-typehint, it will automatically add scalar type hints and return type declarations to your PHP project using existing PHPDoc annotations.
PHP 7 will be released soon. Scalar type hints and return type declarations introduced in this new release are very interesting because they enforce the use of stricter types in PHP code. They are less error-prone and ease the maintenance. To quote the RFC: “These type declarations allow the PHP runtime to ensure that correctly-typed arguments are passed to functions, and make function signatures more informative.”
At Les-Tilleuls.coop, we are always looking how we can improve the quality of some of our long running sensitive projects. On the other hand we are a gang of lazy leftists drinking beers late at night. Updating all our code bases to add scalar type hints and return type declarations will be a pain.
Hopefully, we’ve already done a similar work by writing an exhaustive PHPDoc including @param and @return tags describing PHP functions. It allows IDEs and static analysis tools such as Scrutinizr to detect potential bugs early in the development process. Here was born my idea: a tool using existing PHPDoc tags to automatically add scalar type hint and return types.
This command line tool is called phpdoc-to-typehint. You can download it as PHAR file on GitHub.
To use it, just run the following command:
php phpdoc-to-typehint.phar <my-project-directory>
Before:
<?php /* * @param int|null $a * @param string $b * * @return float */ function bar($a, $b, bool $c, callable $d = null) { return 0.0; }
After:
<?php /* * @param int|null $a * @param string $b * * @return float */ function bar(int $a = null, string $b, bool $c, callable $d = null) : float { return 0.0; }
This tool is very experimental and can break your code. Be sure to have a backup of it (but you’re using Git right?) and run your test suite after the conversion. Bug reports are very welcomed.
It supports:
- functions
- methods of classes and traits
- method definitions in interfaces
- PHPDoc inheritance
The tool tries to preserve the existing indentation of source code files but it can create some strange indentations, especially when it adds return types. Run PHP CS Fixer to make your code following PSR-1 and PSR-2 conventions.
We can go back to the pub.
2 thoughts on “Introducing the phpdoc-to-typehint Converter: add scalar type hints and return type declarations to your projects”