PHP code example of jlvn / tree-transform

1. Go to this page and download the library: Download jlvn/tree-transform library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

jlvn / tree-transform example snippets


// 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
)

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, [])     
        ]
    }
}

$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);