跳至正文

更新日志 1.8.0 — 2023 年 12 月 26 日

重要变更

规范化服务(序列化)

这个新服务可以使用MapperBuilder实例化。它允许将给定输入转换为标量和数组值,同时保留原始结构。

此功能可用于与使用数据格式(JSON、CSV、XML 等)的其他系统共享信息。规范化器将负责将数据递归地转换为可以序列化的格式。

下面是一个基本示例,显示了对象到标量值数组的转换。

namespace My\App;

$normalizer = (new \CuyZ\Valinor\MapperBuilder())
    ->normalizer(\CuyZ\Valinor\Normalizer\Format::array());

$userAsArray = $normalizer->normalize(
    new \My\App\User(
        name: 'John Doe',
        age: 42,
        country: new \My\App\Country(
            name: 'France',
            countryCode: 'FR',
        ),
    )
);

// `$userAsArray` is now an array and can be manipulated much more
// easily, for instance to be serialized to the wanted data format.
//
// [
//     'name' => 'John Doe',
//     'age' => 42,
//     'country' => [
//         'name' => 'France',
//         'countryCode' => 'FR',
//     ],
// ];

规范化器可以通过使用所谓的变换器来扩展,它可以是特性或任何可调用对象。

在下面的示例中,全局变换器用于格式化规范化器找到的任何日期。

(new \CuyZ\Valinor\MapperBuilder())
    ->registerTransformer(
        fn (\DateTimeInterface $date) => $date->format('Y/m/d')
    )
    ->normalizer(\CuyZ\Valinor\Normalizer\Format::array())
    ->normalize(
        new \My\App\Event(
            eventName: 'Release of legendary album',
            date: new \DateTimeImmutable('1971-11-08'),
        )
    );

// [
//     'eventName' => 'Release of legendary album',
//     'date' => '1971/11/08',
// ]

该日期变换器可能是更精细控制的特性,如下所示。

namespace My\App;

#[\Attribute(\Attribute::TARGET_PROPERTY)]
final class DateTimeFormat
{
    public function __construct(private string $format) {}

    public function normalize(\DateTimeInterface $date): string
    {
        return $date->format($this->format);
    }
}

final readonly class Event
{
    public function __construct(
        public string $eventName,
        #[\My\App\DateTimeFormat('Y/m/d')]
        public \DateTimeInterface $date,
    ) {}
}

(new \CuyZ\Valinor\MapperBuilder())
    ->registerTransformer(\My\App\DateTimeFormat::class)
    ->normalizer(\CuyZ\Valinor\Normalizer\Format::array())
    ->normalize(
        new \My\App\Event(
            eventName: 'Release of legendary album',
            date: new \DateTimeImmutable('1971-11-08'),
        )
    );

// [
//     'eventName' => 'Release of legendary album',
//     'date' => '1971/11/08',
// ]

还有更多功能可用,有关详细信息可以在文档中找到。

新功能

  • 引入标准化服务( 1c9368 )

错误修复

  • 在灵活模式下允许数字字符串中的前导零 ( f000c1 )
  • 允许标量和类的映射并集 ( 4f4af0 )
  • 正确处理单命名空间类( a53ef9 )
  • 正确解析同一个命名空间中的类名( a462fe )