示例#1
0
 public static function export($db, $forest_name, $fields = NULL, $tree_id = NULL)
 {
     // check if the table exists before doing anything else
     $sql_utils = new sp_SQLUtils($db);
     if (!$sql_utils->table_exists($forest_name)) {
         throw new sp_Error("Table `Baobab_{$forest_name}` does not exist");
     }
     // get all the fields to export or check if the passed fields are valid
     $tree = new Baobab($db, $forest_name, NULL);
     // use a unexistent tree in the right table
     if ($fields !== NULL) {
         $tree->_sql_check_fields($fields);
     } else {
         $fields = array_keys($tree->_get_fields());
     }
     // remove tree_id from $fields to avoid writing it n times
     //   ( we give him a single property in the json format )
     $idx_treeId_field = array_search("tree_id", $fields);
     if (FALSE !== $idx_treeId_field) {
         unset($fields[$idx_treeId_field]);
         $fields = array_values($fields);
         // I want to mantain a correct index sequence
     }
     // get the ids of the trees to export
     $ar_tree_id = array();
     if ($tree_id) {
         if (!is_array($tree_id)) {
             $tree_id = array($tree_id);
         }
         // ensure $tree_id contains numbers
         foreach ($tree_id as $tmp_id) {
             $ar_tree_id[] = intval($tmp_id);
         }
     } else {
         $query = "SELECT DISTINCT tree_id FROM {$forest_name}";
         $result = $db->query($query, MYSQLI_STORE_RESULT);
         if (!$result) {
             throw new sp_MySQL_Error($db);
         }
         while ($row = $result->fetch_row()) {
             $ar_tree_id[] = intval($row[0]);
         }
         $result->close();
     }
     // get the type of the columns mainly to write numbers as ... numbers
     $fieldsFlags = array();
     // each index will have the field flag, to know his type
     $result = $db->query("SELECT " . join(",", $fields) . " FROM {$forest_name} LIMIT 1", MYSQLI_STORE_RESULT);
     if (!$result) {
         throw new sp_MySQL_Error($db);
     }
     // retrieve the column names and their types
     while ($finfo = $result->fetch_field()) {
         $fieldsFlags[] = $finfo->flags;
     }
     $result->close();
     // parse each tree and build an array to jsonize later
     $ar_out = array();
     foreach ($ar_tree_id as $tree_id) {
         $tmp_ar = array("tree_id" => $tree_id, "fields" => $fields, "values" => null);
         // retrieve the data
         $tree = new Baobab($db, $forest_name, $tree_id);
         $root = $tree->getTree();
         if ($root !== NULL) {
             $data = array(array());
             // the inner array emulate a node to gain root as child
             self::_traverse_tree_to_export_data($root, $data, $fieldsFlags, $tmp_ar["fields"]);
             if (!empty($data[0][0])) {
                 $tmp_ar["values"] =& $data[0][0];
             }
             $ar_out[] = $tmp_ar;
         }
     }
     return json_encode($ar_out);
 }