jlvn/tree-transform

一个用于对树形结构进行变换的库。

0.0.1 2022-04-18 22:33 UTC

This package is auto-updated.

Last update: 2024-09-22 16:17:02 UTC


README

一个用于对树形结构进行变换的库。

用法

此库暴露了一个名为 TreeTransformer 的主要类。用户可以使用这个类通过数据类型逐个变换树形结构。这是通过所谓的 TreeTransformable 实现的。

TreeTransformables

TreeTransformable 定义了特定数据类型的变换行为。所有 TreeTransformable 必须实现 TreeTransformableInterface

使用 GenericTreeTransformable 类

此库暴露了 GenericTreeTransformable 类。使用这个类,可以动态创建 TreeTransformable,而无需为每种数据类型定义一个类。

// A transformable that transforms a string into an array of strings
$stringTreeTransformable = new GenericTreeTransformable(
    gettype(''), // the tag of the transformable. 'string' in this case.
    fn() => [], // the branches of the current transformable. None in this case.
    fn(string $trunk) => split('', $trunk), // the transform function
)

实现自己的变换器

另一种选择是简单地为自己的特定数据类型实现 TreeTransformableInterface

class Custom {
    public string $name;
    public array $children;
}

class CustomTreeTransformable implements TreeTransformableInterface {
    public function getTag(): string {
        return Custom::class
    }
    
    public function getBranches($trunk): array {
        return $trunk->children;
    }

    public function transform($trunk, ReadOnlyMapInterface $branches) {
        return [
            'name' => $trunk->name,      
            'customChildren' => $branches->getOrDefault(Custom::class, [])     
        ]
    }
}

使用 TreeTransformer

我们已经定义了我们的 TreeTransformable,现在可以在 TreeTransformer 中使用它们。TreeTransformer 使用简单的深度优先算法遍历树。你可以用多种方式与 TreeTransformer 交互。

$transformer = new TreeTransformer;

// Throws a NotFoundException when the transformable with a certain tag is not found.
$transformer->tryTransform($data);

// uses a default transformable (PlaceboTreeTransformer by default) when the transformable
// with a certain tag is not found.
$transformer->transformOrDefault($data);

使用方法提供的变换器

$transformer = new TreeTransformer;

$transformableMap = new TreeTransformableTagReadOnlyMap([
    $stringTreeTransformable,
    new CustomTreeTransformable
]);

try {
    $transformer->tryTransform($data, $transformableMap);
} catch(NotfoundException $e) {
    // thrown if transformable is not found
}

$transformer->transformOrDefault($data, $transformableMap);

//it is also possible to supply a new default transformable
$transformer->transformOrDefault($data, $transformableMap, $stringTreeTransformable);

使用构造函数或默认提供的变换器

$transformableMap = new TreeTransformableTagReadOnlyMap([
    $stringTreeTransformable,
    new CustomTreeTransformable
]);

$transformer = new TreeTransformer($stringTreeTransformable, $transformableMap);

try {
    $transformer->tryTransform($data);
} catch(NotfoundException $e) {
    // thrown if transformable is not found
}

$transformer->transformOrDefault($data);