PHPDoc 处理
Kuiper 反射模块提供了强大的 PHPDoc 注解处理功能,基于 PHPStan/phpdoc-parser 实现了完整的 PHPDoc 解析支持。
PHPDoc 概述
PHPDoc 是一种文档注释标准,用于为 PHP 代码添加结构化的文档信息。Kuiper 反射模块可以解析以下 PHPDoc 标签:
@var- 变量类型@param- 参数类型@return- 返回值类型@throws- 异常类型@inheritdoc- 继承文档
ReflectionDocBlockFactory
ReflectionDocBlockFactory 是 PHPDoc 解析的核心类,提供文档块创建和缓存功能。
获取工厂实例
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
// 创建实例(指定缓存大小和 UseStatementCache)
$factory = new ReflectionDocBlockFactory(
1000, // LRU 缓存,最多 1000 个条目
new UseStatementCache()
);缓存管理
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\resolution\UseStatementCache;
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
// 获取缓存统计
$stats = $factory->getCacheStats();
echo $stats['mode']; // "lru"
echo $stats['size']; // 当前缓存条目数
echo $stats['max_size']; // 最大缓存条目数
// 清除缓存
$factory->clearCache();解析类 PHPDoc
获取类文档块
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionClass;
/**
* 用户服务类
*
* @author John Doe <john@example.com>
* @version 1.0.0
*/
class UserService
{
// 类实现
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$class = new ReflectionClass('UserService');
// 获取类文档块(如果需要)
// 注意:当前实现主要关注方法和属性的文档块解析方法 PHPDoc
创建方法文档块
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\ReflectionMethodDocBlockInterface;
use ReflectionMethod;
/**
* 用户仓储类
*/
class UserRepository
{
/**
* 根据用户 ID 查找用户
*
* @param int $userId 用户 ID
* @return User|null 用户对象,未找到时返回 null
* @throws InvalidArgumentException 如果用户 ID 无效
*/
public function findById(int $userId): ?User
{
return null;
}
/**
* 创建新用户
*
* @param array{string name, string email, int age} $data 用户数据
* @return User 创建的用户对象
*/
public function create(array $data): User
{
return new User();
}
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$method = new ReflectionMethod('UserRepository', 'findById');
// 创建方法文档块
$docBlock = $factory->createMethodDocBlock($method);
// 获取参数类型
$paramType = $docBlock->getParameterTypes()['userId'];
echo $paramType->getName(); // "int"
// 获取返回值类型
$returnType = $docBlock->getReturnType();
echo $returnType; // "?User"
// 获取所有参数类型
$paramTypes = $docBlock->getParameterTypes();
foreach ($paramTypes as $name => $type) {
echo "$name: " . $type->getName() . "\n";
}
// 输出: userId: int解析复杂参数类型
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionMethod;
class ExampleService
{
/**
* 处理用户数据
*
* @param array<string, mixed> $data 数据数组
* @param array<int, User> $users 用户列表
* @param array{name: string, age: int, active: bool} $profile 用户配置
* @return array<int, array{name: string, age: int}>
*/
public function process(array $data, array $users, array $profile): array
{
return [];
}
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$method = new ReflectionMethod('ExampleService', 'process');
$docBlock = $factory->createMethodDocBlock($method);
// 解析泛型数组类型
$dataType = $docBlock->getParameterTypes()['data'];
echo $dataType->getName(); // "array<string, mixed>"
echo $dataType->getKeyType()->getName(); // "string"
echo $dataType->getValueType()->getName(); // "mixed"
// 解析类型化数组
$usersType = $docBlock->getParameterTypes()['users'];
echo $usersType->getName(); // "array<int, User>"
echo $usersType->getValueType()->getName(); // "User"处理 @inheritdoc
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionMethod;
interface UserRepositoryInterface
{
/**
* 根据用户 ID 查找用户
*
* @param int $userId 用户 ID
* @return User|null 用户对象
*/
public function findById(int $userId): ?User;
}
class UserRepository implements UserRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function findById(int $userId): ?User
{
return null;
}
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$method = new ReflectionMethod('UserRepository', 'findById');
$docBlock = $factory->createMethodDocBlock($method);
// 会从接口继承文档块
$paramType = $docBlock->getParameterTypes()['userId'];
echo $paramType->getName(); // "int"
$returnType = $docBlock->getReturnType();
echo $returnType; // "?User"解析属性 PHPDoc
创建属性文档块
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\ReflectionPropertyDocBlockInterface;
use ReflectionProperty;
class User
{
/**
* 用户 ID
*
* @var int
*/
private int $id;
/**
* 用户名
*
* @var string
*/
public string $name;
/**
* 用户元数据
*
* @var array<string, mixed>
*/
private array $metadata;
/**
* 用户状态
*
* @var 'active'|'inactive'|'suspended'
*/
private string $status;
/**
* 关联的用户组
*
* @var array<int, Group>
*/
private array $groups;
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
// 解析属性文档块
$property = new ReflectionProperty('User', 'id');
$docBlock = $factory->createPropertyDocBlock($property);
// 获取属性类型
$type = $docBlock->getType();
echo $type->getName(); // "int"
echo $type->allowsNull(); // false
// 解析数组类型
$metadataProperty = new ReflectionProperty('User', 'metadata');
$metadataDocBlock = $factory->createPropertyDocBlock($metadataProperty);
$metadataType = $metadataDocBlock->getType();
echo $metadataType->getName(); // "array<string, mixed>"
// 解析联合类型
$statusProperty = new ReflectionProperty('User', 'status');
$statusDocBlock = $factory->createPropertyDocBlock($statusProperty);
$statusType = $statusDocBlock->getType();
echo $statusType->getName(); // "'active'|'inactive'|'suspended'"从 PHPDoc 获取类型
当属性没有原生类型声明时,可以从 PHPDoc 获取类型:
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionProperty;
class LegacyModel
{
/**
* @var string
*/
private $name;
/**
* @var array<int, int>
*/
private $ids;
/**
* @var DateTime|null
*/
private $createdAt;
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
// 从 PHPDoc 解析类型
$property = new ReflectionProperty('LegacyModel', 'name');
$docBlock = $factory->createPropertyDocBlock($property);
$type = $docBlock->getType();
echo $type->getName(); // "string"
// 解析可空类型
$createdAtProperty = new ReflectionProperty('LegacyModel', 'createdAt');
$createdAtDocBlock = $factory->createPropertyDocBlock($createdAtProperty);
$createdAtType = $createdAtDocBlock->getType();
echo $createdAtType; // "?DateTime"
echo $createdAtType->allowsNull(); // truePhpstanTypeParser
PhpstanTypeParser 是基于 PHPStan/phpdoc-parser 的类型解析器,支持复杂的类型注解。
使用类型解析器
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
use kuiper\reflection\TypeParserInterface;
// 设置自定义类型解析器
ReflectionType::setParser(new CustomTypeParser());
// 使用默认的 PHPStan 解析器
$parser = ReflectionType::getParser();
// 解析类型字符串
$type = $parser->parse('array<string, int>');
echo $type->getName(); // "array<string, int>"支持的类型注解
PHPStan 类型解析器支持以下类型注解:
基本类型
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
// 简单类型
echo ReflectionType::parse('string')->getName(); // "string"
echo ReflectionType::parse('int')->getName(); // "int"
echo ReflectionType::parse('float')->getName(); // "float"
echo ReflectionType::parse('bool')->getName(); // "bool"
// 可空类型
echo ReflectionType::parse('?string')->allowsNull(); // true
echo ReflectionType::parse('string|null')->allowsNull(); // true
// 联合类型
echo ReflectionType::parse('string|int')->isComposite(); // true
echo ReflectionType::parse('string|int|float|null')->allowsNull(); // true泛型数组类型
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
// 列表类型
$listType = ReflectionType::parse('array<int>');
echo $listType->getValueType()->getName(); // "int"
// 映射类型
$mapType = ReflectionType::parse('array<string, int>');
echo $mapType->getKeyType()->getName(); // "string"
echo $mapType->getValueType()->getName(); // "int"
// 嵌套泛型
$nestedType = ReflectionType::parse('array<string, array<int, bool>>');
echo $nestedType->getValueType()->getValueType()->getName(); // "bool"数组形状
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
// 数组形状
$shapeType = ReflectionType::parse('array{name: string, age: int, active: ?bool}');
echo $shapeType->isArray(); // true
// 获取字段
$fields = $shapeType->getFields();
foreach ($fields as $name => $type) {
echo "$name: " . $type->getName() . "\n";
}
// 列表形状
$listShape = ReflectionType::parse('list{int, string}');
echo $listShape->isList(); // true
// 密封形状
$sealedShape = ReflectionType::parse('array{name: string, ...}');
echo $sealedShape->isSealed(); // true对象形状
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
// 对象形状
$objectShape = ReflectionType::parse('object{name: string, age: int}');
echo $objectShape->isObject(); // true
// 获取属性
$properties = $objectShape->getProperties();
foreach ($properties as $name => $type) {
echo "$name: " . $type->getName() . "\n";
}类类型
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionType;
// 完全限定类名
$classType = ReflectionType::parse('DateTime');
echo $classType->getName(); // "DateTime"
// 相对类名(在命名空间上下文中解析)
$classType = ReflectionType::parse('User');
// 会被解析为当前命名空间中的 User 类
// 可空类类型
$nullableClass = ReflectionType::parse('?DateTime');
echo $nullableClass->allowsNull(); // true类型注解标签
@var
@var 标签用于指定变量或属性的类型:
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionProperty;
class Example
{
/**
* @var array<string, int>
*/
private array $counts;
/**
* @var 'read'|'write'|'execute'
*/
private string $permission;
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$property = new ReflectionProperty('Example', 'counts');
$docBlock = $factory->createPropertyDocBlock($property);
$type = $docBlock->getType();
echo $type->getName(); // "array<string, int>"@param
@param 标签用于指定方法参数的类型:
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionMethod;
class Service
{
/**
* @param array<string, mixed> $options 配置选项
* @param bool $enabled 是否启用
* @return void
*/
public function configure(array $options, bool $enabled): void
{
}
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$method = new ReflectionMethod('Service', 'configure');
$docBlock = $factory->createMethodDocBlock($method);
// 获取参数类型
$optionsType = $docBlock->getParameterTypes()['options'];
echo $optionsType->getName(); // "array<string, mixed>"
$enabledType = $docBlock->getParameterTypes()['enabled'];
echo $enabledType->getName(); // "bool"@return
@return 标签用于指定方法返回值的类型:
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionMethod;
class Repository
{
/**
* @return array<int, User>
*/
public function findAll(): array
{
return [];
}
/**
* @return User|null
*/
public function findFirst(): ?User
{
return null;
}
}
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
// 获取返回值类型
$method1 = new ReflectionMethod('Repository', 'findAll');
$docBlock1 = $factory->createMethodDocBlock($method1);
$returnType1 = $docBlock1->getReturnType();
echo $returnType1->getName(); // "array<int, User>"
$method2 = new ReflectionMethod('Repository', 'findFirst');
$docBlock2 = $factory->createMethodDocBlock($method2);
$returnType2 = $docBlock2->getReturnType();
echo $returnType2; // "?User"完整示例
验证器生成器
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use kuiper\reflection\ReflectionTypeInterface;
use ReflectionMethod;
class ValidatorGenerator
{
public static function generate(string $className, string $methodName): string
{
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$method = new ReflectionMethod($className, $methodName);
$docBlock = $factory->createMethodDocBlock($method);
$code = "function validate(mixed \$args): array {\n";
$code .= " \$errors = [];\n\n";
foreach ($docBlock->getParameterTypes() as $name => $type) {
$code .= self::generateValidation($name, $type);
}
$code .= " return \$errors;\n";
$code .= "}\n";
return $code;
}
private static function generateValidation(string $name, ReflectionTypeInterface $type): string
{
$code = " // 验证 {$name}\n";
$code .= " if (!isset(\$args['{$name}'])) {\n";
$code .= " if (!{$type->allowsNull()}) {\n";
$code .= " \$errors['{$name}'] = 'Required';\n";
$code .= " }\n";
$code .= " } else {\n";
if ($type->isClass()) {
$code .= " if (!is_a(\$args['{$name}'], '{$type->getName()}')) {\n";
$code .= " \$errors['{$name}'] = 'Invalid type';\n";
$code .= " }\n";
} elseif ($type->getName() === 'string') {
$code .= " if (!is_string(\$args['{$name}'])) {\n";
$code .= " \$errors['{$name}'] = 'Must be string';\n";
$code .= " }\n";
}
$code .= " }\n\n";
return $code;
}
}
// 使用
echo ValidatorGenerator::generate('UserService', 'createUser');文档生成器
php
<?php
declare(strict_types=1);
use kuiper\reflection\ReflectionDocBlockFactory;
use ReflectionMethod;
use ReflectionClass;
class DocGenerator
{
public static function generateMethodDoc(string $className, string $methodName): string
{
$factory = new ReflectionDocBlockFactory(1000, new UseStatementCache());
$method = new ReflectionMethod($className, $methodName);
$docBlock = $factory->createMethodDocBlock($method);
$doc = "### {$method->getName()}\n\n";
// 参数文档
foreach ($docBlock->getParameterTypes() as $name => $type) {
$doc .= "- **\${$name}**: `{$type}`\n";
}
// 返回值文档
$returnType = $docBlock->getReturnType();
$doc .= "\n**返回值**: `{$returnType}`\n";
return $doc;
}
}
// 使用
echo DocGenerator::generateMethodDoc('UserService', 'findById');最佳实践
1. 使用 PHPDoc 补充类型信息
php
// ✅ 为没有类型声明的代码添加 PHPDoc
class LegacyService
{
/**
* @param array<string, mixed> $data
* @return array<int, User>
*/
public function process($data)
{
return [];
}
}
// ❌ 避免没有类型信息的代码
class LegacyService
{
public function process($data)
{
return [];
}
}2. 使用具体类型而非通用类型
php
// ✅ 使用具体的类型
/**
* @param array<string, int> $counts
*/
public function sum(array $counts): int
{
return array_sum($counts);
}
// ❌ 避免使用通用类型
/**
* @param array $data
*/
public function sum(array $data): int
{
return array_sum($data);
}3. 记录可空性
php
// ✅ 明确标记可空类型
/**
* @return User|null
*/
public function findById(int $id): ?User
{
return null;
}
// ❌ 不要遗漏可空性信息
/**
* @return User
*/
public function findById(int $id): ?User
{
return null;
}