public static function csv2hops($csv, $stops, $o = array()) { $options = array(); foreach (self::$default_options as $k => $v) { $options[$k] = isset($o[$k]) ? $o[$k] : $v; } extract($options); $csv = Sourcemap_Csv::parse($csv); $raw_headers = array(); if ($headers) { $raw_headers = array_shift($csv); $headers = array(); for ($i = 0; $i < count($raw_headers); $i++) { if (strlen(trim($raw_headers[$i]))) { $headers[] = strtolower($raw_headers[$i]); } } foreach ($headers as $i => $h) { if (is_null($fromcol) && preg_match('/^from(_?stop)?$/i', $h)) { $fromcol = $h; } elseif (is_null($tocol) && preg_match('/^to(_?stop)?$/i', $h)) { $tocol = $h; } } } if (!$fromcol || !$tocol) { throw new Exception('To and from columns required.'); } $data = array(); foreach ($csv as $ri => $row) { if ($headers && is_array($headers)) { $record = array(); foreach ($headers as $hi => $k) { if (isset($row[$hi])) { $record[$k] = $row[$hi]; } } } else { $record = $row; } if ($record) { $data[] = $record; } } $stops_by_id = array(); foreach ($stops as $sti => $st) { $stops_by_id[(int) $st->local_stop_id] = $st; } $hops = array(); foreach ($data as $i => $record) { if (!isset($record[$fromcol]) || !is_numeric($record[$fromcol])) { throw new Exception('Missing or invalid from field at record #' . ($i + 1) . '.'); } if (!isset($record[$tocol]) || !is_numeric($record[$tocol])) { throw new Exception('Missing or invalid to field at record #' . ($i + 1) . '.'); } $from = $record[$fromcol]; $to = $record[$tocol]; if (!isset($stops_by_id[(int) $from])) { throw new Exception('From stop in hop does not exist in record #' . ($i + 1) . '.'); } if (!isset($stops_by_id[(int) $to])) { throw new Exception('To stop in hop does not exist in record #' . ($i + 1) . '.'); } list($type, $fromcoords) = Sourcemap_Wkt::read($stops_by_id[$from]->geometry); list($type, $tocoords) = Sourcemap_Wkt::read($stops_by_id[$to]->geometry); $frompt = new Sourcemap_Proj_Point($fromcoords); $topt = new Sourcemap_Proj_Point($tocoords); $geometry = Sourcemap_Wkt::write(Sourcemap_Wkt::MULTILINESTRING, array($frompt, $topt)); $new_hop = (object) array('from_stop_id' => $from, 'to_stop_id' => $to, 'geometry' => $geometry, 'attributes' => new stdClass()); foreach ($record as $k => $v) { if ($k !== $fromcol && $k !== $tocol) { $new_hop->attributes->{$k} = $v; } } $hops[] = $new_hop; } return $hops; }
protected function _unserialize_csv($csv) { return Sourcemap_Csv::parse($csv); }