diff options
author | Urban Müller | 2020-07-02 15:33:22 +0200 |
---|---|---|
committer | Urban Müller | 2020-07-02 15:34:25 +0200 |
commit | 97cf529601ee2406478fb72ee997e176bf40e203 (patch) | |
tree | 0dec2e8ca6b46d9c3dc8dab06ba7d6af8b7bd041 | |
parent | c4c23f6b0ea5c68e266ad0791a2a22fd3456e643 (diff) | |
download | itools-97cf529601ee2406478fb72ee997e176bf40e203.tar.gz itools-97cf529601ee2406478fb72ee997e176bf40e203.tar.bz2 itools-97cf529601ee2406478fb72ee997e176bf40e203.zip |
csv(): rename var, enable catching errs
-rw-r--r-- | it_pipe.class | 14 |
1 files changed, 10 insertions, 4 deletions
diff --git a/it_pipe.class b/it_pipe.class index 084e03d..d3e4ae0 100644 --- a/it_pipe.class +++ b/it_pipe.class @@ -195,6 +195,7 @@ function cols($collist, $separator = "\t") * Return contents of pipe as associative records. Column titles read from first line, separators can be \t or ; or , * @param $p['forceschema'] ignore schema in file, replace it with this comma separated column list * @param $p['fixcolnames'] replace non-identifier chars in colum names + * @param $p['it_error'] error params */ function csv($p = []) { @@ -202,15 +203,20 @@ function csv($p = []) $counts = count_chars($this->lines[0]); $splitchar = $counts[ord("\t")] ? "\t" : ($counts[ord(";")] > $counts[ord(",")] ? ";" : ","); $csvhead = it::replace(['^\x{FEFF}' => ''], array_shift($this->lines)); // it::replace removes utf8 byte order mark - $cols = $p['forceschema'] ? explode(",", $p['forceschema']) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv') - foreach ($cols as $idx => $col) - $cols[$idx] = it::replace(['^$' => "field$idx", '\W' => $p['fixcolnames'] ? "_" : '$0'], $col); + $schema = $p['forceschema'] ? explode(",", $p['forceschema']) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv') + foreach ($schema as $idx => $col) + $schema[$idx] = it::replace(['^$' => "field$idx", '\W' => $p['fixcolnames'] ? "_" : '$0'], $col); $oldlocale = setlocale(LC_CTYPE, "0"); setlocale(LC_CTYPE, 'de_CH.iso-8859-1'); # this works for utf-8 as well foreach ($this->lines as $line) - $records[] = (object)(($t = array_combine($cols, $t2 = str_getcsv($line, $splitchar, '"'))) ? $t : it::error("schema mismatch: " . count($cols) . " vs " . count($t2))); # NOPHPLINT + { + if (($cols = str_getcsv($line, $splitchar, '"')) && count($schema) == count($cols)) + $records[] = (object)array_combine($schema, $cols); + else + it::error((array)$p['it_error'] + ['title' => "schema mismatch: " . count($schema) . " vs " . count($cols), 'body' => [$schema, $line]]); # NOPHPLINT + } setlocale(LC_CTYPE, $oldlocale); |