如何快速创建自定义断言方法:Webmozart/Assert扩展开发完全指南

发布时间:2026/5/19 8:21:26

如何快速创建自定义断言方法:Webmozart/Assert扩展开发完全指南 如何快速创建自定义断言方法Webmozart/Assert扩展开发完全指南【免费下载链接】assertAssertions to validate method input/output with nice error messages.项目地址: https://gitcode.com/gh_mirrors/as/assertWebmozart/Assert是一个强大的PHP断言库它提供了超过100种断言方法来验证方法输入输出。但真正的强大之处在于它的可扩展性——你可以轻松创建自己的自定义断言方法为什么选择Webmozart/Assert进行断言验证Webmozart/Assert库相比传统的断言方案有几个关键优势优雅的错误消息提供清晰、一致的错误信息格式静态分析支持与Psalm和PHPStan完美集成类型安全所有断言方法都有完整的类型提示易于扩展支持创建自定义断言方法批量验证提供all*()和nullOr*()前缀方法理解断言库的核心架构在开始创建自定义断言之前让我们先了解库的核心结构主要文件结构src/Assert.php- 包含所有核心断言方法的主类src/Mixin.php- 自动生成nullOr*()和all*()变体的特性tests/static-analysis/- 静态分析测试文件确保类型安全断言方法的基本模式每个断言方法都遵循相同的模式检查条件是否满足如果不满足抛出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; }创建自定义断言方法的3个简单步骤步骤1扩展Assert类首先创建一个继承自Webmozart\Assert\Assert的自定义类namespace YourApp\Assert; use Webmozart\Assert\Assert as BaseAssert; class CustomAssert extends BaseAssert { // 你的自定义断言方法将在这里 }步骤2实现自定义断言逻辑让我们创建一个验证电子邮件域名的自定义断言/** * psalm-pure * * psalm-assert string $value * psalm-assert non-empty-string $value * * throws InvalidArgumentException */ public static function emailDomain(mixed $value, string $allowedDomain, string $message ): string { static::stringNotEmpty($value, $message); $domain substr(strrchr($value, ), 1); if ($domain ! $allowedDomain) { static::reportInvalidArgument(\sprintf( $message ?: Expected email with domain %s. Got: %s, $allowedDomain, $value )); } return $value; }步骤3添加静态分析支持为了让静态分析工具如Psalm理解你的断言需要在测试目录创建对应的静态分析文件// tests/static-analysis/assert-emailDomain.php namespace Webmozart\Assert\Tests\StaticAnalysis; use Webmozart\Assert\Assert; /** * psalm-pure * * param mixed $value */ function emailDomain(mixed $value, string $allowedDomain): string { Assert::emailDomain($value, $allowedDomain); return $value; }高级扩展技巧利用Mixin特性Webmozart/Assert的Mixin特性会自动为你的自定义断言生成nullOrEmailDomain()和allEmailDomain()方法class CustomAssert extends BaseAssert { use Mixin; // 你的自定义方法 public static function emailDomain(mixed $value, string $allowedDomain, string $message ): string { // 实现... } }这样你就可以直接使用CustomAssert::emailDomain($email, example.com)CustomAssert::nullOrEmailDomain($email, example.com)CustomAssert::allEmailDomain($emails, example.com)实用的自定义断言示例示例1验证密码强度public static function strongPassword(mixed $value, string $message ): string { static::stringNotEmpty($value, $message); if (strlen($value) 8) { static::reportInvalidArgument(\sprintf( $message ?: Password must be at least 8 characters long. Got: %d characters, strlen($value) )); } if (!preg_match(/[A-Z]/, $value)) { static::reportInvalidArgument( $message ?: Password must contain at least one uppercase letter ); } if (!preg_match(/[0-9]/, $value)) { static::reportInvalidArgument( $message ?: Password must contain at least one digit ); } return $value; }示例2验证JSON字符串public static function json(mixed $value, string $message ): string { static::string($value, $message); json_decode($value); if (json_last_error() ! JSON_ERROR_NONE) { static::reportInvalidArgument(\sprintf( $message ?: Expected valid JSON. Error: %s, json_last_error_msg() )); } return $value; }示例3验证URL协议public static function secureUrl(mixed $value, string $message ): string { static::stringNotEmpty($value, $message); $parsed parse_url($value); if (!isset($parsed[scheme]) || !in_array($parsed[scheme], [https, wss], true)) { static::reportInvalidArgument(\sprintf( $message ?: Expected secure URL (https:// or wss://). Got: %s, $value )); } return $value; }测试你的自定义断言创建相应的测试用例确保你的断言正常工作// tests/CustomAssertTest.php use YourApp\Assert\CustomAssert; class CustomAssertTest extends TestCase { public function testEmailDomainValid(): void { $email userexample.com; $result CustomAssert::emailDomain($email, example.com); $this-assertSame($email, $result); } public function testEmailDomainInvalid(): void { $this-expectException(InvalidArgumentException::class); $this-expectExceptionMessage(Expected email with domain example.com. Got: userother.com); CustomAssert::emailDomain(userother.com, example.com); } }最佳实践和性能优化1. 错误消息模板使用一致的占位符顺序%s测试的值%2$s,%3$s其他参数2. 类型提示为所有自定义断言添加完整的PHPDoc注解/** * psalm-pure * psalm-assert string $value * psalm-assert non-empty-string $value * psalm-return non-empty-string */3. 重用现有断言在自定义断言中重用基础断言避免重复代码public static function phoneNumber(mixed $value, string $message ): string { static::stringNotEmpty($value, $message); // 自定义验证逻辑 if (!preg_match(/^\?[0-9\s\-\(\)]$/, $value)) { static::reportInvalidArgument( $message ?: Expected valid phone number ); } return $value; }集成到你的项目中通过Composer安装composer require webmozart/assert创建自定义断言类将你的CustomAssert类放在适当的位置并确保自动加载配置正确。在业务逻辑中使用use YourApp\Assert\CustomAssert; class UserService { public function createUser(array $data): User { $email CustomAssert::emailDomain($data[email], company.com); $password CustomAssert::strongPassword($data[password]); // 创建用户逻辑... } }总结为什么自定义断言能提升代码质量创建自定义断言方法不仅能提供更好的输入验证还能提高代码可读性- 方法名明确表达验证意图增强类型安全- 静态分析工具能理解你的断言统一错误处理- 所有验证使用相同的异常机制减少重复代码- 复杂的验证逻辑封装在断言中便于测试- 断言方法本身易于单元测试Webmozart/Assert的强大扩展能力让你可以根据项目需求创建专门的验证规则从而构建更健壮、更易维护的PHP应用程序。立即开始创建你的第一个自定义断言吧【免费下载链接】assertAssertions to validate method input/output with nice error messages.项目地址: https://gitcode.com/gh_mirrors/as/assert创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

相关新闻