PHP 静态分析器

dev-master 2015-10-23 17:55 UTC

This package is auto-updated.

Last update: 2024-09-20 00:48:52 UTC


README

Build Status

一个静态分析引擎...

用法

bin/tuli analyze file1 file2 path

安装

将其作为 composer 依赖项安装!!!

$ composer require ircmaxell/tuli dev-master

然后简单地执行 vendor/bin/tuli 如常

或者将其检出为独立项目。然后 composer install 依赖项

$ composer install

然后简单地 bin/tuli 执行。

示例

code.php

<?php

$a = 1.0;
$b = 2;

$c = foo($a, $b);

$d = foo($b, $c);

function foo(int $a, int $b): int {
    if ($a > $b) {
        return $a + $b + 0.5;
    }
}

然后,在 shell 中

$ bin/tuli analyze code.php
Analyzing code.php
Determining Variable Types
Round 1 (15 unresolved variables out of 20)
.
Detecting Type Conversion Issues
Type mismatch on foo() argument 0, found float expecting int code.php:6
Type mismatch on foo() return value, found float expecting int code.php:12
Default return found for non-null type int code.php:10
Done

它找到的三个错误是

  • 在 foo() 参数 0 处类型不匹配,找到 float,期望 int code.php:6

    这意味着在 code.php 的第 6 行,你传递了一个 float 给第一个参数,而它声明的是整数

  • 在 foo() 返回值处类型不匹配,找到 float,期望 int code.php:12

    在第 12 行返回的值是一个 float,但在函数签名中声明为整数。

  • 对于非 null 类型 int 在 code.php:10 找到默认返回值

    对于类型化的函数有一个默认返回语句(未提供)

就是这样!

当前支持的规则

  • 函数参数类型

    它将检查所有类型化的函数参数,并确定对该函数的所有调用是否匹配该类型。

  • 函数返回类型

    如果函数的返回值已类型化,则它将确定函数是否实际上返回该类型。

  • 方法参数类型

    它将检查每个有效类型提示排列的方法调用,以确定是否存在可能的类型不匹配。

待办事项

  • 很多

另一个示例

<?php

class A {
    public function foo(int $a) : int {
        return $a;
    }
}

class B extends A {
    public function foo(float $a) : float {
        return $a;
    }
}

class C extends B {
    public function foo(int $a) : int {
        return $a;
    }
}

function foo(A $a) : int {
    return $a->foo(1.0);
}

运行

$ bin/tuli analyze code.php
Analyzing code.php

Determining Variable Types
Round 1 (5 unresolved variables out of 7)

Round 2 (3 unresolved variables out of 7)

Detecting Type Conversion Issues
Detecting Function Argument Errors
Detecting Function Return Errors
Type mismatch on foo() return value, found float expecting int code.php:22
Detecting Method Argument Errors
Type mismatch on A->foo() argument 0, found float expecting int code.php:22
Type mismatch on C->foo() argument 0, found float expecting int code.php:22
Done

再次,它发现了 3 个错误

  • 在 foo() 返回值处类型不匹配,找到 float,期望 int code.php:22

    它查看所有可能的 A::foo() 方法定义(A::foo,B::foo,C::foo),并确定通用返回类型是 float(因为类型提升允许 int 传递给 float,但不能反过来)。因此,直接返回 ->foo() 可以导致类型错误。

  • 在 A->foo() 参数 0 处类型不匹配,找到 float,期望 int code.php:22

  • 在 C->foo() 参数 0 处类型不匹配,找到 float,期望 int code.php:22

    我们知道如果你使用类型 A 或 C,你是在尝试将 float 传递给声明为整数的对象。