LithiumPHP nested trees with levels (depth of childrens)

I use nice behavior li3_tree but i need something more. I fight for 24h with calculate depth of childrens flat array. Results of this war:

static function childrens($parent) {
$sql = "SELECT node.*, (COUNT(parent." . self::meta('key') . ") - (sub_tree.depth + 1)) AS depth ";
$sql .= "FROM " . self::meta('source') . " AS node, ";
$sql .= " " . self::meta('source') . " AS parent, ";
$sql .= " " . self::meta('source') . " AS sub_parent, ";
$sql .= " ( ";
$sql .= " SELECT node.*, (COUNT(parent." . self::meta('key') . ") - 1) AS depth ";
$sql .= " FROM " . self::meta('source') . " AS node, ";
$sql .= " " . self::meta('source') . " AS parent ";
$sql .= " WHERE node.lft BETWEEN parent.lft AND parent.rght ";
$sql .= " AND node." . self::meta('key') . " = ". $parent . " ";
$sql .= " GROUP BY node." . self::meta('key') . " ";
$sql .= " ORDER BY node.lft ";
$sql .= " ) AS sub_tree ";
$sql .= "WHERE node.lft BETWEEN parent.lft AND parent.rght ";
$sql .= " AND node.lft BETWEEN sub_parent.lft AND sub_parent.rght ";
$sql .= " AND sub_parent." . self::meta('key') . " = sub_tree." . self::meta('key') . " ";
$sql .= "GROUP BY node." . self::meta('key') . " ";
$sql .= "ORDER BY node.lft; ";
return static::connection()->read($sql);
}