lesphp / property-info-typed-array
使用PHP属性从数组类的属性中提取键和值类型。这省去了使用PhpDocExtractor进行类型数组的需求。
6.0.0
2022-04-17 04:08 UTC
Requires
- php: >=8.0.2
- symfony/property-info: ^6.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-17 09:44:16 UTC
README
这是一个提供PHP原生属性,用于symfony/property-info检索数组元素正确类型的包。现在,这只能通过DocBlock注解实现。DocBlocks是PHP的一等公民,但它不是用于类型检查/执行的。在docblock中错误的类名仅是PHP的文本文档,而不是为开发者准备的。然后,文档可以被删除/替换,而程序的行为应该保持不变。
安装
composer require lesphp/property-info-typed-array
兼容性
用法
TypedArray属性是可重复的,多个注解被视为OR子句进行评估。
use LesPhp\PropertyInfo\TypedArray; use LesPhp\PropertyInfo\TypedArrayAttributeExtractor; class FooBar { #[TypedArray(type: Baz::class, nullable: false, keyType: 'int')] private array $baz; #[TypedArray(type: Baz::class, nullable: true)] #[TypedArray(type: 'string', nullable: true)] private array $bazOrString; } $typedArrayExtractor = new TypedArrayAttributeExtractor(); $typedArrayExtractor->getTypes(Foo_Bar::class, 'baz'); $typedArrayExtractor->getTypes(Foo_Bar::class, 'bazOrString');
结合symfony/serializer,这可以是一个强大的注解,并省去了DocBlock注解读者的需求。
use LesPhp\PropertyInfo\TypedArrayAttributeExtractor; use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader; use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Serializer; $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader()); $propertyTypeExtractor = new PropertyInfoExtractor([new ReflectionExtractor()], [new TypedArrayAttributeExtractor()]); $propertyNormalizer = new PropertyNormalizer($classMetadataFactory, null, $propertyTypeExtractor); $serializer = new Serializer( [$propertyNormalizer, new ArrayDenormalizer()], [new JsonEncoder()] );