1 package SL::Helper::Csv;
 
   8 use Params::Validate qw(:all);
 
  10 use Rose::Object::MakeMethods::Generic scalar => [ qw(
 
  11   file encoding sep_char quote_char escape_char header profile class
 
  12   numberformat dateformat ignore_unknown_columns strict_profile _io _csv
 
  13   _objects _parsed _data _errors all_cvar_configs case_insensitive_header
 
  16 use SL::Helper::Csv::Dispatcher;
 
  17 use SL::Helper::Csv::Error;
 
  23   my %params = validate(@_, {
 
  24     sep_char               => { default => ';' },
 
  25     quote_char             => { default => '"' },
 
  26     escape_char            => { default => '"' },
 
  27     header                 => { type    => ARRAYREF, optional => 1 },
 
  28     profile                => { type    => HASHREF,  optional => 1 },
 
  34     ignore_unknown_columns => 0,
 
  36     case_insensitive_header => 0,
 
  38   my $self = bless {}, $class;
 
  40   $self->$_($params{$_}) for keys %params;
 
  42   $self->_io(IO::File->new);
 
  43   $self->_csv(Text::CSV_XS->new({
 
  45     sep_char    => $self->sep_char,
 
  46     quote_char  => $self->quote_char,
 
  47     escape_char => $self->escape_char,
 
  56   my ($self, %params) = @_;
 
  59   return if ! $self->_check_header;
 
  60   return if ! $self->dispatcher->parse_profile;
 
  61   return if ! $self->_parse_data;
 
  72   my ($self, %params) = @_;
 
  73   croak 'no class given'   unless $self->class;
 
  74   croak 'must parse first' unless $self->_parsed;
 
  76   $self->_make_objects unless $self->_objects;
 
  77   return wantarray ? @{ $self->_objects } : $self->_objects;
 
  91   my ($self, %params) = @_;
 
  93   $self->encoding($self->_guess_encoding) if !$self->encoding;
 
  95   $self->_io->open($self->file, '<' . $self->_encode_layer)
 
  96     or die "could not open file " . $self->file;
 
 102   my ($self, %params) = @_;
 
 103   my $header = $self->header;
 
 106     $header = $self->_csv->getline($self->_io);
 
 109       $self->_csv->error_input,
 
 110       $self->_csv->error_diag,
 
 115   # Special case: utf8 BOM.
 
 116   # certain software (namely MS Office and notepad.exe insist on prefixing
 
 117   # data with a discouraged but valid byte order mark
 
 118   # if not removed, the first header field will not be recognized
 
 119   if ($header && $header->[0] && $self->encoding =~ /utf-?8/i) {
 
 120     $header->[0] =~ s/^\x{FEFF}//;
 
 123   return unless $header;
 
 125   # Special case: human stupidity
 
 126   # people insist that case sensitivity doesn't exist and try to enter all
 
 127   # sorts of stuff. at this point we've got a profile (with keys that represent
 
 128   # valid methods), and a header full of strings. if two of them match, the user
 
 129   # mopst likely meant that field, so rewrite the header
 
 130   if ($self->case_insensitive_header) {
 
 131     die 'case_insensitive_header is only possible with profile' unless $self->profile;
 
 133       keys %{ $self->profile || {} },
 
 135     for my $name (@names) {
 
 136       for my $i (0..$#$header) {
 
 137         $header->[$i] = $name if lc $header->[$i] eq lc $name;
 
 142   return $self->header($header);
 
 146   my ($self, %params) = @_;
 
 149   $self->_csv->column_names(@{ $self->header });
 
 152     my $row = $self->_csv->getline($self->_io);
 
 155       @hr{@{ $self->header }} = @$row;
 
 158       last if $self->_csv->eof;
 
 160         $self->_csv->error_input,
 
 161         $self->_csv->error_diag,
 
 162         $self->_io->input_line_number,
 
 165     last if $self->_csv->eof;
 
 168   $self->_data(\@data);
 
 169   $self->_push_error(@errors);
 
 175   ':encoding(' . $_[0]->encoding . ')';
 
 179   my ($self, %params) = @_;
 
 182   eval "require " . $self->class;
 
 183   local $::myconfig{numberformat} = $self->numberformat if $self->numberformat;
 
 184   local $::myconfig{dateformat}   = $self->dateformat   if $self->dateformat;
 
 186   for my $line (@{ $self->_data }) {
 
 187     my $tmp_obj = $self->class->new;
 
 188     $self->dispatcher->dispatch($tmp_obj, $line);
 
 189     push @objs, $tmp_obj;
 
 192   $self->_objects(\@objs);
 
 196   my ($self, %params) = @_;
 
 198   $self->{_dispatcher} ||= $self->_make_dispatcher;
 
 201 sub _make_dispatcher {
 
 202   my ($self, %params) = @_;
 
 204   die 'need a header to make a dispatcher' unless $self->header;
 
 206   return SL::Helper::Csv::Dispatcher->new($self);
 
 209 sub _guess_encoding {
 
 215   my ($self, @errors) = @_;
 
 216   my @new_errors = ($self->errors, map { SL::Helper::Csv::Error->new(@$_) } @errors);
 
 217   $self->_errors(\@new_errors);
 
 229 SL::Helper::Csv - take care of csv file uploads
 
 235   my $csv = SL::Helper::Csv->new(
 
 236     file        => \$::form->{upload_file},
 
 237     encoding    => 'utf-8', # undef means utf8
 
 238     sep_char    => ',',     # default ';'
 
 239     quote_char  => '\'',    # default '"'
 
 240     escape_char => '"',     # default '"'
 
 241     header      => [qw(id text sellprice word)], # see later
 
 242     profile     => { sellprice => 'sellprice_as_number' },
 
 243     class       => 'SL::DB::CsvLine',   # if present, map lines to this
 
 246   my $status  = $csv->parse;
 
 247   my $hrefs   = $csv->get_data;
 
 248   my @objects = $csv->get_objects;
 
 250   my @errors  = $csv->errors;
 
 256 Text::CSV offeres already good functions to get lines out of a csv file, but in
 
 257 most cases you will want those line to be parsed into hashes or even objects,
 
 258 so this model just skips ahead and gives you objects.
 
 260 Its basic assumptions are:
 
 264 =item You do know what you expect to be in that csv file.
 
 266 This means first and foremost you have knowledge about encoding, number and
 
 267 date format, csv parameters such as quoting and separation characters. You also
 
 268 know what content will be in that csv and what L<Rose::DB> is responsible for
 
 269 it. You provide valid header columns and their mapping to the objects.
 
 271 =item You do NOT know if the csv provider yields to your expectations.
 
 273 Stuff that does not work with what you expect should not crash anything, but
 
 274 give you a hint what went wrong. As a result, if you remeber to check for
 
 275 errors after each step, you should be fine.
 
 277 =item Data does not make sense. It's just data.
 
 279 Almost all data imports have some type of constraints. Some data needs to be
 
 280 unique, other data needs to be connected to existing data sets. This will not
 
 281 happen here. You will receive a plain mapping of the data into the class tree,
 
 292 Standard constructor. You can use this to set most of the data.
 
 296 Do the actual work. Will return true ($self actually) if success, undef if not.
 
 300 Parse the data into objects and return those.
 
 302 This method will return list or arrayref depending on context.
 
 306 Returns an arrayref of the raw lines as hashrefs.
 
 310 Return all errors that came up during parsing. See error handling for detailed
 
 321 The file which contents are to be read. Can be a name of a physical file or a
 
 322 scalar ref for memory data.
 
 326 Encoding of the CSV file. Note that this module does not do any encoding
 
 327 guessing. Know what your data is. Defaults to utf-8.
 
 335 Same as in L<Text::CSV>
 
 337 =item C<header> \@FIELDS
 
 339 Can be an array of columns, in this case the first line is not used as a
 
 340 header. Empty header fields will be ignored in objects.
 
 342 =item C<profile> \%ACCESSORS
 
 344 May be used to map header fields to custom accessors. Example:
 
 346   { listprice => listprice_as_number }
 
 348 In this case C<listprice_as_number> will be used to read in values from the
 
 351 In case of a One-To-One relationsship these can also be set over
 
 352 relationsships by sparating the steps with a dot (C<.>). This will work:
 
 354   { customer => 'customer.name' }
 
 356 And will result in something like this:
 
 358   $obj->customer($obj->meta->relationship('customer')->class->new);
 
 359   $obj->customer->name($csv_line->{customer})
 
 361 But beware, this will not try to look up anything in the database. You will
 
 362 simply receive objects that represent what the profile defined. If some of
 
 363 these information are unique, and should be connected to preexisting data, you
 
 364 will have to do that for yourself. Since you provided the profile, it is
 
 365 assumed you know what to do in this case.
 
 367 If no profile is given, any header field found will be taken as is.
 
 369 If the path in a profile entry is empty, the field will be subjected to
 
 370 C<strict_profile> and C<case_insensitive_header> checking, will be parsed into
 
 371 C<get_data>, but will not be attempted to be dispatched into objects.
 
 375 If present, the line will be handed to the new sub of this class,
 
 376 and the return value used instead of the line itself.
 
 378 =item C<ignore_unknown_columns>
 
 380 If set, the import will ignore unkown header columns. Useful for lazy imports,
 
 381 but deactivated by default.
 
 383 =item C<case_insensitive_header>
 
 385 If set, header columns will be matched against profile entries case
 
 386 insensitive, and on match the profile name will be taken.
 
 388 Only works if a profile is given, will die otherwise.
 
 390 If both C<case_insensitive_header> and C<strict_profile> is set, matched header
 
 391 columns will be accepted.
 
 393 =item C<strict_profile>
 
 395 If set, all columns to be parsed must be specified in C<profile>. Every header
 
 396 field not listed there will be treated like an unknown column.
 
 398 If both C<case_insensitive_header> and C<strict_profile> is set, matched header
 
 399 columns will be accepted.
 
 403 =head1 ERROR HANDLING
 
 405 After parsing a file all errors will be accumulated into C<errors>.
 
 406 Each entry is an object with the following attributes:
 
 408  raw_input:  offending raw input,
 
 409  code:   Text::CSV error code if Text:CSV signalled an error, 0 else,
 
 410  diag:   error diagnostics,
 
 411  line:   position in line,
 
 412  col:    estimated line in file,
 
 414 Note that the last entry can be off, but will give an estimate.
 
 422 sep_char, quote_char, and escape_char are passed to Text::CSV on creation.
 
 423 Changing them later has no effect currently.
 
 427 Encoding errors are not dealt with properly.
 
 433 Dispatch to child objects, like this:
 
 435  $csv = SL::Helper::Csv->new(
 
 437    class => SL::DB::Part,
 
 452 Sven Schöling E<lt>s.schoeling@linet-services.deE<gt>