ramasdev / simple-collection-transformer
将简单数据转换为 Laravel 集合转换器。
1.0.1
2022-11-24 10:01 UTC
Requires
- php: ^8.0
Requires (Dev)
- ergebnis/phpstan-rules: ^1.0
- orchestra/testbench: ^7.7
- phpstan/phpstan: ^1.8
- phpunit/phpunit: ^9
- squizlabs/php_codesniffer: ^3.7
This package is auto-updated.
Last update: 2024-09-24 13:56:15 UTC
README
将简单数据转换为 Laravel 集合转换器,不再需要编写 Collection 转换器了!
- 通过回调函数使用过滤器。
安装
composer require ramasdev/simple-collection-transformer
用法
创建 DTO/模型类,并通过属性提供需要转换的集合类
use Ramasdev\SimpleCollectionTransformer\Attributes\CollectionAttribute; use Ramasdev\SimpleCollectionTransformer\Tests\Unit\Data\Collections\ChannelCollection; #[CollectionAttribute(ChannelCollection::class)] class Channel { public function __construct( private string $channelId, private string $channelType, private Carbon $lastRegistration ) { } public function getChannelId(): string { return $this->channelId; } public function getChannelType(): string { return $this->channelType; } public function getLastRegistration(): Carbon { return $this->lastRegistration; } }
使用过滤器转换到集合
use Ramasdev\SimpleCollectionTransformer\CollectionTransformer; $actualCollection = $this->collectionTransformer->transform($data, function ($item) { if ($item['channel_id'] === 'b') { return false; } return new Channel($item['channel_id'], $item['channel_type'], new Carbon($item['last_registration'])); }); // Returns ChannelCollection
您还可以与您的反序列化组件一起使用它,例如
use Ramasdev\SimpleCollectionTransformer\CollectionTransformer; $actualCollection = $this->collectionTransformer->transform($data, function ($item) { return $this->decoder->decodeArray((array) $item, Channel::class); }); // Returns ChannelCollection