Files
base_web/common/Helper/Tree.php
2020-12-15 17:45:27 -03:00

59 lines
1.3 KiB
PHP

<?php
namespace ProVM\Common\Helper;
class Tree {
protected $merger;
public function __construct($separator) {
$this->merger = new Merger($separator);
}
protected $tree;
public function add($value, $parent = null, $alias = null): Tree {
if ($parent === null) {
if ($alias === null) {
$this->tree []= $value;
return $this;
}
$this->tree[$alias] = $value;
return $this;
}
if (!isset($this->tree[$parent])) {
return $this;
}
if ($alias === null) {
$this->tree []= $this->merger->start()
->add($this->tree[$parent])
->add($value)
->merge();
return $this;
}
$this->tree[$alias] = $this->merger->start()
->add($this->tree[$parent])
->add($value)
->merge();
return $this;
}
public function check_keys($tree) {
$bool = true;
foreach ($tree as $def) {
if (!isset($def[2])) {
continue;
}
$key = $def[2];
$bool &= array_key_exists($key, $this->tree);
}
return $bool;
}
public function addTree($tree) {
while (!$this->check_keys($tree)) {
foreach ($tree as $def) {
$this->add($def[0], $def[1] ?? null, $def[2] ?? null);
}
}
}
public function build($tree) {
$this->tree = [];
$this->addTree($tree);
return (object) $this->tree;
}
}