1 package SL::Helper::Csv::Dispatcher;
7 use Scalar::Util qw(weaken);
8 use Rose::Object::MakeMethods::Generic scalar => [ qw(
12 use SL::Helper::Csv::Error;
15 my ($class, $parent) = @_;
16 my $self = bless { }, $class;
18 weaken($self->{_csv} = $parent);
25 my ($self, $line) = @_;
27 eval "require " . $self->_csv->profile->{class};
28 my $obj = $self->_csv->profile->{class}->new;
30 for my $spec (@{ $self->_specs }) {
31 $self->apply($obj, $spec, $line->{$spec->{key}});
38 my ($self, $obj, $spec, $value) = @_;
41 for my $step (@{ $spec->{steps} }) {
42 my ($acc, $class, $index) = @$step;
47 if (! $obj->$acc || !$obj->$acc->[$index]) {
48 my @objects = $obj->$acc;
49 $obj->$acc(@objects, map { $class->new } 0 .. $index - @objects);
51 $obj = $obj->$acc->[$index];
54 $obj->$acc($class->new);
66 my ($self, $col) = @_;
67 return grep { $col eq $_->{key} } $self->_specs;
71 my ($self, %params) = @_;
73 my $header = $self->_csv->header;
74 my $profile = $self->_csv->profile->{profile};
77 for my $col (@$header) {
79 if ($self->_csv->strict_profile) {
80 if (exists $profile->{$col}) {
81 push @specs, $self->make_spec($col, $profile->{$col});
83 $self->unknown_column($col, undef);
86 if (exists $profile->{$col}) {
87 push @specs, $self->make_spec($col, $profile->{$col});
89 push @specs, $self->make_spec($col, $col);
94 $self->_specs(\@specs);
95 $self->_csv->_push_error($self->errors);
96 return ! $self->errors;
100 my ($self, $col, $path) = @_;
102 my $spec = { key => $col, steps => [] };
106 my $cur_class = $self->_csv->profile->{class};
108 return unless $cur_class;
110 for my $step_index ( split /\.(?!\d)/, $path ) {
111 my ($step, $index) = split /\./, $step_index;
112 if ($cur_class->can($step)) {
113 if (my $rel = $cur_class->meta->relationship($step)) { #a
114 if ($index && ! $rel->isa('Rose::DB::Object::Metadata::Relationship::OneToMany')) {
118 "Profile path error. Indexed relationship is not OneToMany around here: '$step_index'",
124 my $next_class = $cur_class->meta->relationship($step)->class;
125 push @{ $spec->{steps} }, [ $step, $next_class, $index ];
126 $cur_class = $next_class;
127 eval "require $cur_class; 1" or die "could not load class '$cur_class'";
129 } else { # simple dispatch
130 push @{ $spec->{steps} }, [ $step ];
134 $self->unknown_column($col, $path);
142 my ($self, $col, $path) = @_;
143 return if $self->_csv->ignore_unknown_columns;
148 "header field '$col' is not recognized",
163 my ($self, @errors) = @_;
164 my @new_errors = ($self->errors, map { SL::Helper::Csv::Error->new(@$_) } @errors);
165 $self->_errors(\@new_errors);