Skip to content

Instantly share code, notes, and snippets.

@drupol
Created October 28, 2020 16:18
Show Gist options
  • Select an option

  • Save drupol/67c86cf298c7635d0d15095e4de7efe5 to your computer and use it in GitHub Desktop.

Select an option

Save drupol/67c86cf298c7635d0d15095e4de7efe5 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App;
use drupol\launcher\Launcher;
use loophp\phptree\Builder\Random;
use loophp\phptree\Exporter\Gv;
use loophp\phptree\Exporter\Image;
use loophp\phptree\Exporter\Text;
use loophp\phptree\Node\AttributeNode;
use loophp\phptree\Node\ValueNode;
use loophp\phptree\Tree\Tree;
include __DIR__ . '/vendor/autoload.php';
function randomColor(): string {
return array_reduce(
array('r', 'g', 'b'),
static function(string $carry, string $type): string {
$dechex = dechex(mt_rand(0, 255));
return $carry . (strlen($dechex) < 2 ? '0' : '') . $dechex;
},
'#'
);
}
$tree = new ValueNode('root', 2);
$nodes = [];
foreach (range('A', 'Z') as $v) {
$nodes[] = new AttributeNode(['label' => $v, 'style' => 'filled', 'color'=>randomColor(), 'fillcolor'=>randomColor()], 2);
}
$tree->add(...$nodes);
$textExporter = new Text();
$textExporter->export($tree); // [root[A[C[G[O][P]][H[Q][R]]][D[I[S][T]][J[U][V]]]][B[E[K[W][X]][L[Y][Z]]][F[M][N]]]]⏎
$graphvizExporter = new Gv();
$dotScript = $graphvizExporter->export($tree);
file_put_contents('tree.dot', $dotScript);
$imageExporter = new Image();
$imageContent = $imageExporter->setFormat('png')->export($tree);
file_put_contents('tree.png', $imageContent);
Launcher::open('tree.png');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment