在php中轻松进行参数验证

Eug*_*rov 5 php validation

每次编写一些php函数或类方法时,最好检查输入参数并抛出异常,或触发错误或警告等...

例如

<?php

function send_email($email, $subject, $body)
{
    if (empty($email)) {
        throw new InvalidArgumentException('Email should not be empty');
    }
    if (!is_string($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        throw new InvalidArgumentException('Email format is invalid');
    }
    if (empty($subject)) {
        throw new InvalidArgumentException('Subject should not be empty');
    }
    if (!is_string($subject)) {
        throw new InvalidArgumentException('Subject must be a string');
    }
    if (empty($body)) {
        throw new InvalidArgumentException('Body should not be empty');
    }
    if (!is_string($body)) {
        throw new InvalidArgumentException('Body must be a string');
    }

    return mail($email, $subject, $body);
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,此示例的大部分内容都包含验证代码,而只有一条有用的行可以执行此任务.如果您想要可靠地保护您的功能,您实际上需要编写大量代码.这很繁琐.

我的问题是 - 有人知道一些很容易验证代码的好方法吗?是否有任何库验证取决于PHP-DOC?例如:

<?php

/**
 * @param email $email
 * @param string $subject
 * @param string $body
 */
function send_email($email, $subject, $body)
{
    return mail($email, $subject, $body);
}
Run Code Online (Sandbox Code Playgroud)

谢谢.

dec*_*eze 7

纯PHP中最简单的方法是使用断言简化检查:

class Assert {

    public static function isString($var) {
        if (!is_string($var)) {
            throw new InvalidArgumentException('Argument is not a string');
        }
    }

}

function foo($string) {
    Assert::isString($string);
    ...
}
Run Code Online (Sandbox Code Playgroud)

您可以通过内省和/或调试回溯来对此进行修改,以在抛出的异常中包含更多信息.