Webmozart Assert:PHP类型安全的强力守卫

Webmozart Assert

Webmozart Assert 是一个高效的 PHP 断言库,专门用于验证方法的输入和输出。通过使用这个库提供的断言功能,你可以显著减少编写安全实现所需的代码量。

所有在 Assert 类中的断言方法,在验证失败时都会抛出一个 Webmozart\Assert\InvalidArgumentException 异常。

功能特性

  • 丰富的断言方法:提供超过 100 种断言方法,涵盖字符串、整数、数组、对象等各种类型检查
  • 空值和集合验证:每个基础断言都有对应的 nullOr*all*allNullOr* 变体
  • 友好的错误消息:提供一致且可读的错误消息格式,支持自定义消息
  • 类型安全:与 PHPStan 和 Psalm 等静态分析工具良好集成
  • 高性能:专为高效验证设计,减少运行时开销
  • 严格的类型声明:全面支持 PHP 8.2+ 的严格类型模式

安装指南

使用 Composer 进行安装:

composer require webmozart/assert

系统要求:

  • PHP 8.2 或更高版本
  • ext-ctype 扩展

使用说明

基础使用

use Webmozart\Assert\Assert;

class Employee
{
    public function __construct($id)
    {
        Assert::integer($id, 'The employee ID must be an integer. Got: %s');
        Assert::greaterThan($id, 0, 'The employee ID must be a positive integer. Got: %s');
    }
}

如果使用无效的 ID 创建员工,将会抛出异常:

new Employee('abc'); // 抛出 InvalidArgumentException: The employee ID must be an integer. Got: string

自定义错误消息

Assert::string($path, 'The path is expected to be a string. Got: %s');

空值检查变体

// 允许 null 值的字符串检查
Assert::nullOrString($nullableValue);

// 检查数组中的所有元素都是字符串
Assert::allString($stringArray);

核心代码

Assert 类核心方法

/**
 * 验证值是否为字符串
 *
 * @psalm-pure
 * @psalm-assert string $value
 *
 * @throws InvalidArgumentException
 */
public static function string(mixed $value, string $message = ''): string
{
    if (!\is_string($value)) {
        static::reportInvalidArgument(\sprintf(
            $message ?: 'Expected a string. Got: %s',
            static::typeToString($value)
        ));
    }

    return $value;
}

/**
 * 验证值是否为非空字符串
 *
 * @psalm-pure
 * @psalm-assert non-empty-string $value
 * @psalm-return non-empty-string
 *
 * @throws InvalidArgumentException
 */
public static function stringNotEmpty(mixed $value, string $message = ''): string
{
    static::string($value, $message);
    static::notEq($value, '', $message);

    return $value;
}

/**
 * 验证值是否为整数
 *
 * @psalm-pure
 * @psalm-assert int $value
 *
 * @throws InvalidArgumentException
 */
public static function integer(mixed $value, string $message = ''): int
{
    if (!\is_int($value)) {
        static::reportInvalidArgument(\sprintf(
            $message ?: 'Expected an integer. Got: %s',
            static::typeToString($value)
        ));
    }

    return $value;
}

Mixin 特性(提供变体方法)

/**
 * 允许 null 值的字符串检查
 *
 * @psalm-pure
 * @psalm-assert string|null $value
 *
 * @return string|null
 *
 * @throws InvalidArgumentException
 */
public static function nullOrString(mixed $value, string $message = ''): mixed
{
    null === $value || static::string($value, $message);

    return $value;
}

/**
 * 检查可迭代对象中的所有元素都是字符串
 *
 * @psalm-pure
 * @psalm-assert iterable<string> $value
 *
 * @return iterable<string>
 *
 * @throws InvalidArgumentException
 */
public static function allString(iterable $value, string $message = ''): iterable
{
    static::isIterable($value);

    foreach ($value as $entry) {
        static::string($entry, $message);
    }

    return $value;
}

/**
 * 检查可迭代对象中的所有元素都是字符串或 null
 *
 * @psalm-pure
 * @psalm-assert iterable<string|null> $value
 *
 * @return iterable<string|null>
 *
 * @throws InvalidArgumentException
 */
public static function allNullOrString(?iterable $value, string $message = ''): ?iterable
{
    static::isIterable($value);

    foreach ($value as $entry) {
        null === $entry || static::string($entry, $message);
    }

    return $value;
}

自定义异常类

/**
 * 断言失败时抛出的异常类
 */
class InvalidArgumentException extends \InvalidArgumentException
{
}

JbAoGqoaBS++GdInsG1ZjhkQ+XNf4K6cuOFLWlgLc0s=
更多精彩内容 请关注我的个人公众号 公众号(办公AI智能小助手)
对网络安全、黑客技术感兴趣的朋友可以关注我的安全公众号(网络安全技术点滴分享)

公众号二维码

公众号二维码

posted @ 2026-01-01 23:29  qife  阅读(2)  评论(0)    收藏  举报