PHP - static type checking a-la PhpStorm

瘦欲@ 提交于 2019-12-02 20:51:41

For static code analysis, specifically helping with type error detection, one can use tools like

PHPCS aka PHP_CodeSniffer is Coding Standard checker, not really helpful with type error detection.

Automatic check for type mismatches

Phantm

If you want to check your code for type mismatches you can use Phantm. You can use this with Jenkins or use with svn hook post-commit.

From official site

Phantm is a tool written in Scala that can be used to detect potential programming errors inside PHP applications. It will both work for small isolated script as well as full-blown applications. phantm stands for “PHp ANalyzer for Type Mistakes”.

Phantm needs

ant
sbt
Java 1.6 or higher
Scala 2.9.1 or higher

Usage

$ ./phantm <target.php>

PHPLint

Another way for checks your php code for type mismatches is PHPLint. You can use it with Jenkins, svn or another tools.

From official site

PHPLint is a validator and documentator for PHP 4 and PHP 5 programs. PHPLint extends the PHP language through transparent meta-code that can drive the parser to a even more strict check of the source. PHPLint is not simply a checker: it implements a new, strong typed, language implemented over the PHP language. You can build your programs from scratch with PHPLint in mind, or you can check and fix existing programs, or you can follow the quick-and-dirty PHP programming way and then add the PHPLint meta-code later once the program is finished. Whatever is the strategy you choose, PHPLint makes your programs safer, more secure, well documented and with drastically less bugs. PHPlint have nice online test tool.

More information about working with types by PHPLint

Usage

  $ phplint <target.php>

Manual check for type mismatches

If you want to check your variables types using PHPStorm, you can use PHPDoc metadata. But much better use php for this: you can enable E_NOTICE for report uninitialized variables for catch variable name misspellings. After that you can use instance check at your functions:

/**
 * @param array $data - highlight for PHPStorm
 * @param MySuperClass $row - highlight for PHPStorm
 */
function(array $data, MySuperClass $row)
{
    // Error if $data is not an array
    // Error if $row is not instance of MySuperClass
    /* do something .... */
}

/**
 * @param array $data - highlight for PHPStorm
 * @param MySuperClass $row - highlight for PHPStorm
 */
function($data, $row)
{
    if (!is_array($data))
    {
        throw new TypeException('$data is must be array');
    }

    if (!($row instanceof MySuperClass))
    {
        throw new TypeException('$data is must be array');
    }
}

I think is the best way for type checking, when developer is writing correct code using TDD method. Very good solution you can read at official php documentation or at PHPUnit official.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!