Skip to content

类型解析 ​

Kuiper 反射模块的类型解析系统提供了完整的 PHP 类型支持,包括基本类型、复合类型、联合类型和 PHPStan 类型注解。

ReflectionType ​

ReflectionType 是类型系统的核心类,提供了类型解析、验证和转换功能。

从类型字符串解析 ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 解析基本类型
$intType = ReflectionType::parse('int');
$stringType = ReflectionType::parse('string');
$boolType = ReflectionType::parse('bool');
$floatType = ReflectionType::parse('float');

// 解析可空类型
$nullableInt = ReflectionType::parse('?int');
echo $nullableInt->allowsNull(); // true

// 解析联合类型
$unionType = ReflectionType::parse('string|int|null');
echo $unionType->isComposite(); // true

从 PHP 反射创建 ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;
use ReflectionMethod;
use ReflectionProperty;
use ReflectionParameter;

class ExampleService
{
    public function process(string|array $data, ?int $count = null): array|false
    {
        return [];
    }

    public ?User $user;
}

// 从参数类型创建
$method = new ReflectionMethod('ExampleService', 'process');
$param = $method->getParameters()[0];
$paramType = ReflectionType::fromPhpType($param->getType());
echo $paramType; // "string|int"

// 从返回值类型创建
$returnType = ReflectionType::fromPhpType($method->getReturnType());
echo $returnType; // "array|false"

// 从属性类型创建
$property = new ReflectionProperty('ExampleService', 'user');
$propertyType = ReflectionType::fromPhpType($property->getType());
echo $propertyType; // "?User"

类型名称获取 ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$type = ReflectionType::parse('string');
echo $type->getName(); // "string"
echo (string) $type; // "string"

$nullableType = ReflectionType::parse('?int');
echo $nullableType->getName(); // "int"
echo (string) $nullableType; // "?int"

$unionType = ReflectionType::parse('string|int');
echo $unionType->getName(); // "string|int"
echo (string) $unionType; // "string|int"

可空性处理 ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 创建可空类型
$type = ReflectionType::parse('string');
echo $type->allowsNull(); // false

// 转换为可空类型
$nullableType = $type->withAllowsNull(true);
echo $nullableType->allowsNull(); // true
echo (string) $nullableType; // "?string"

// 转换为非空类型
$nonNullType = $nullableType->withAllowsNull(false);
echo $nonNullType->allowsNull(); // false

类型系统层次 ​

Kuiper 反射模块实现了完整的类型层次结构:

text
ReflectionTypeInterface
    ├── ReflectionType (抽象基类)
    │   ├── PrimitiveType (基本类型)
    │   │   ├── IntegerType
    │   │   ├── FloatType
    │   │   ├── StringType
    │   │   └── BooleanType
    │   ├── ArrayType (数组类型)
    │   ├── MapType (映射类型)
    │   ├── ClassType (类类型)
    │   ├── ObjectType (对象类型)
    │   ├── CompositeType (联合类型)
    │   └── Special Types (特殊类型)
    │       ├── MixedType
    │       ├── VoidType
    │       ├── NullType
    │       ├── CallableType
    │       ├── IterableType
    │       └── ResourceType

基本类型 ​

IntegerType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$type = ReflectionType::parse('int');

echo $type->getName(); // "int"
echo $type->isPrimitive(); // true
echo $type->isScalar(); // true

// 值验证
echo $type->isValid(123); // true
echo $type->isValid('123'); // false
echo $type->isValid(null); // false

// 值清理
echo $type->sanitize('123'); // 123

FloatType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$type = ReflectionType::parse('float');

echo $type->getName(); // "float"
echo $type->isPrimitive(); // true
echo $type->isScalar(); // true

// 值验证
echo $type->isValid(3.14); // true
echo $type->isValid(123); // true (int 可以转换为 float)

StringType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$type = ReflectionType::parse('string');

echo $type->getName(); // "string"
echo $type->isPrimitive(); // true
echo $type->isScalar(); // true

// 值验证
echo $type->isValid('hello'); // true
echo $type->isValid(123); // false

BooleanType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$type = ReflectionType::parse('bool');

echo $type->getName(); // "bool"
echo $type->isPrimitive(); // true
echo $type->isScalar(); // true

// 值验证
echo $type->isValid(true); // true
echo $type->isValid(false); // true
echo $type->isValid(1); // false

数组类型 ​

ArrayType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 简单数组类型
$arrayType = ReflectionType::parse('array');
echo $arrayType->getName(); // "array"
echo $arrayType->isArray(); // true
echo $arrayType->isUnknown(); // true (元素类型未知)

// 类型化数组
$stringArray = ReflectionType::parse('string[]');
echo $stringArray->isArray(); // true
echo $stringArray->isUnknown(); // false
echo $stringArray->getValueType()->getName(); // "string"

// 多维数组
$multiDimArray = ReflectionType::parse('string[][]');
echo $multiDimArray->getDimension(); // 2

// 获取元素类型
$valueType = $stringArray->getValueType();
echo $valueType->getName(); // "string"

MapType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 映射类型 array<key, value>
$mapType = ReflectionType::parse('array<string, int>');
echo $mapType->isArray(); // true
echo $mapType->getKeyType()->getName(); // "string"

// 获取键类型
$keyType = $mapType->getKeyType();
echo $keyType->getName(); // "string"

// 获取值类型
$valueType = $mapType->getValueType();
echo $valueType->getName(); // "int"

// 嵌套映射
$nestedMap = ReflectionType::parse('array<string, array<int, bool>>');
echo $nestedMap->getValueType()->getName(); // "array<int, bool>"

ShapedArrayType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 数组形状类型(键名语法:array{name: type})
$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";
}
// 输出:
// name: string
// age: int
// active: bool

// 检查字段是否存在
echo $shapeType->hasField('name'); // true
echo $shapeType->hasField('nickname'); // false

// 检查可选字段(形参为字段名)
echo $shapeType->isFieldOptional('active'); // true
echo $shapeType->isFieldOptional('name'); // false

// 列表类型(形状列表:array{type, type})
$listType = ReflectionType::parse('array{int, string}');
echo $listType->isList(); // true

注意:数组形状必须使用带键名的语法 array{name: string}。 旧式的无键名写法 array{string name} 已被 phpstan/phpdoc-parser 2.x 移除, 传入 ReflectionType::parse() 会抛 InvalidArgumentException。

泛型 list&lt;int&gt; 目前不被支持——PhpstanTypeParser 只处理泛型名 array, list&lt;int&gt; 会被解析为 mixed。需要列表语义时请使用形状列表 array{int, string}。

类类型 ​

ClassType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 类类型
$classType = ReflectionType::parse('DateTime');
echo $classType->getName(); // "DateTime"
echo $classType->isClass(); // true
echo $classType->isObject(); // true

// 带命名空间的类
$classType = ReflectionType::parse('App\\Models\\User');
echo $classType->getName(); // "App\\Models\\User"

// 接口类型
$interfaceType = ReflectionType::parse('Countable');
echo $interfaceType->isClass(); // true
echo $interfaceType->isObject(); // true

ObjectType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 通用对象类型
$objectType = ReflectionType::parse('object');
echo $objectType->getName(); // "object"
echo $objectType->isObject(); // true
echo $objectType->isClass(); // false (不是具体类)

ObjectShapeType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 对象形状类型(键名语法:object{name: type})
$objectShape = ReflectionType::parse('object{name: string, age: int, id: string}');
echo $objectShape->isObject(); // true
echo $objectShape->isClass(); // false

// 获取属性
$properties = $objectShape->getProperties();
foreach ($properties as $name => $type) {
    echo "$name: " . $type->getName() . "\n";
}
// 输出:
// name: string
// age: int
// id: string

// 检查属性是否存在
echo $objectShape->hasProperty('name'); // true
echo $objectShape->hasProperty('nickname'); // false

注意:对象形状同样必须使用带键名的语法 object{name: string}; 旧式的无键名写法 object{string name} 会抛 InvalidArgumentException。

联合类型 ​

CompositeType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

// 联合类型
$unionType = ReflectionType::parse('string|int|bool');
echo $unionType->isComposite(); // true
echo $unionType->getName(); // "string|int|bool"

// 获取所有类型
$types = $unionType->getTypes();
foreach ($types as $type) {
    echo $type->getName() . "\n";
}
// 输出:
// string
// int
// bool

// 检查包含某个类型(CompositeType 未提供 containsType,需自行遍历)
$containsString = false;
foreach ($unionType->getTypes() as $type) {
    if ('string' === $type->getName()) {
        $containsString = true;
        break;
    }
}
echo $containsString; // true

// 可空联合类型
$nullableUnion = ReflectionType::parse('string|int|null');
echo $nullableUnion->allowsNull(); // true

特殊类型 ​

MixedType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$mixedType = ReflectionType::parse('mixed');
echo $mixedType->getName(); // "mixed"
echo $mixedType->isPseudo(); // true
echo $mixedType->isUnknown(); // true

// mixed 类型可以接受任何值
echo $mixedType->isValid('hello'); // true
echo $mixedType->isValid(123); // true
echo $mixedType->isValid(null); // true
echo $mixedType->isValid(new stdClass()); // true

VoidType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$voidType = ReflectionType::parse('void');
echo $voidType->getName(); // "void"
echo $voidType->isPseudo(); // true

// void 类型没有返回值
echo $voidType->isValid(null); // true
echo $voidType->isValid('value'); // false

CallableType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$callableType = ReflectionType::parse('callable');
echo $callableType->getName(); // "callable"
echo $callableType->isPseudo(); // true

// 可调用类型验证
echo $callableType->isValid(function() {}); // true
echo $callableType->isValid('strlen'); // true
echo $callableType->isValid([new stdClass(), 'method']); // 取决于方法是否存在

IterableType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$iterableType = ReflectionType::parse('iterable');
echo $iterableType->getName(); // "iterable"
echo $iterableType->isPseudo(); // true

// iterable 类型验证
echo $iterableType->isValid([]); // true
echo $iterableType->isValid(new ArrayIterator()); // true
echo $iterableType->isValid('string'); // false

NullType ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$nullType = ReflectionType::parse('null');
echo $nullType->getName(); // "null"
echo $nullType->isNull(); // true

// null 类型验证
echo $nullType->isValid(null); // true
echo $nullType->isValid(''); // false

类型检查方法 ​

isPrimitive() ​

检查是否为基本类型:

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('int')->isPrimitive(); // true
echo ReflectionType::parse('string')->isPrimitive(); // true
echo ReflectionType::parse('array')->isPrimitive(); // false
echo ReflectionType::parse('DateTime')->isPrimitive(); // false

isScalar() ​

检查是否为标量类型(int, float, string, bool):

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('int')->isScalar(); // true
echo ReflectionType::parse('string')->isScalar(); // true
echo ReflectionType::parse('array')->isScalar(); // false
echo ReflectionType::parse('mixed')->isScalar(); // false

isArray() ​

检查是否为数组类型:

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('array')->isArray(); // true
echo ReflectionType::parse('string[]')->isArray(); // true
echo ReflectionType::parse('array<string, int>')->isArray(); // true
echo ReflectionType::parse('array{}')->isArray(); // true

isClass() ​

检查是否为具体类类型:

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('DateTime')->isClass(); // true
echo ReflectionType::parse('Countable')->isClass(); // true (接口也算)
echo ReflectionType::parse('object')->isClass(); // false
echo ReflectionType::parse('mixed')->isClass(); // false

isObject() ​

检查是否为对象类型(包括具体类和通用 object):

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('DateTime')->isObject(); // true
echo ReflectionType::parse('object')->isObject(); // true
echo ReflectionType::parse('stdClass')->isObject(); // true

isComposite() ​

检查是否为联合类型:

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('string|int')->isComposite(); // true
echo ReflectionType::parse('string')->isComposite(); // false

isPseudo() ​

检查是否为伪类型(mixed, void, callable 等):

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

echo ReflectionType::parse('mixed')->isPseudo(); // true
echo ReflectionType::parse('void')->isPseudo(); // true
echo ReflectionType::parse('callable')->isPseudo(); // true
echo ReflectionType::parse('string')->isPseudo(); // false

类型过滤器 ​

类型过滤器提供类型验证和数据清理功能:

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

$type = ReflectionType::parse('string');

// 验证值
echo $type->isValid('hello'); // true
echo $type->isValid(123); // false

// 清理值
echo $type->sanitize('  hello  '); // "  hello  " (默认不过滤)

// 自定义过滤器可以提供清理逻辑

完整示例 ​

API 参数验证 ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;
use ReflectionMethod;

class UserService
{
    public function createUser(string $name, int $age, ?string $email = null): User
    {
        // 实现逻辑
        return new User();
    }
}

// 自动参数验证
$method = new ReflectionMethod('UserService', 'createUser');
$parameters = $method->getParameters();

$arguments = [
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john@example.com',
];

foreach ($parameters as $param) {
    $name = $param->getName();
    if (!isset($arguments[$name])) {
        if (!$param->isOptional()) {
            throw new InvalidArgumentException("Missing required parameter: {$name}");
        }
        continue;
    }

    $type = ReflectionType::fromPhpType($param->getType());
    if (!$type->isValid($arguments[$name])) {
        throw new InvalidArgumentException("Invalid type for parameter {$name}");
    }
}

类型转换工具 ​

php
<?php

declare(strict_types=1);

use kuiper\reflection\ReflectionType;

class TypeConverter
{
    public static function convert(mixed $value, string $typeName): mixed
    {
        $type = ReflectionType::parse($typeName);

        if ($type->allowsNull() && null === $value) {
            return null;
        }

        if ($type->isValid($value)) {
            return $value;
        }

        // 执行类型转换
        return match ($type->getName()) {
            'int' => (int) $value,
            'float' => (float) $value,
            'string' => (string) $value,
            'bool' => (bool) $value,
            'array' => (array) $value,
            default => $value,
        };
    }
}

// 使用
echo TypeConverter::convert('123', 'int'); // 123
echo TypeConverter::convert('3.14', 'float'); // 3.14

最佳实践 ​

1. 使用类型验证 ​

php
// ✅ 在处理数据前验证类型
if ($type->isValid($value)) {
    // 处理数据
}

// ❌ 不要假设类型正确
// 直接处理可能导致错误

2. 利用类型检查 ​

php
// ✅ 使用类型检查方法
if ($type->isArray()) {
    // 处理数组
} elseif ($type->isClass()) {
    // 处理对象
}

// ❌ 不要只检查名称
if ($type->getName() === 'array') {
    // 不够灵活
}

3. 处理可空类型 ​

php
// ✅ 检查可空性
if ($type->allowsNull()) {
    if (null === $value) {
        // 处理 null 情况
    }
}

// ❌ 不要忘记处理 null

更多资源 ​

基于 MIT 许可发布