/[cvs]/nfo/perl/libs/Data/Mungle/Transform/Deep.pm
ViewVC logotype

Diff of /nfo/perl/libs/Data/Mungle/Transform/Deep.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1 by joko, Fri Nov 29 04:49:20 2002 UTC revision 1.8 by joko, Sun Feb 9 05:10:56 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.8  2003/02/09 05:10:56  joko
6  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  + minor update
7  #  + initial check-in  ##
8  #  ##  Revision 1.7  2003/01/19 03:26:59  joko
9  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  + added 'sub deep_copy'  -  refactored from libp
10  #  + new  ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
11  #  ##
12  ##############################################  ##  Revision 1.6  2002/12/23 11:27:53  jonen
13    ##  + changed behavior WATCH!
14    ##
15    ##  Revision 1.5  2002/12/16 19:57:54  joko
16    ##  + option 'init'
17    ##
18    ##  Revision 1.4  2002/12/05 13:56:49  joko
19    ##  - var_deref
20    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
21    ##
22    ##  Revision 1.3  2002/12/03 05:34:55  joko
23    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
24    ##
25    ##  Revision 1.2  2002/12/01 04:44:07  joko
26    ##  + code from Data::Transform::OO
27    ##
28    ##  Revision 1.1  2002/11/29 04:49:20  joko
29    ##  + initial check-in
30    ##
31    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
32    ##  + new
33    ## ---------------------------------------------------------------------------
34    
35    
36  package Data::Transform::Deep;  package Data::Transform::Deep;
# Line 19  use warnings; Line 40  use warnings;
40    
41  require Exporter;  require Exporter;
42  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
43  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
44    &var_NumericalHashToArray    &var_NumericalHashToArray
45    &var_deref    &var_mixin
46    &var_mixin    &object2hash
47    &getStructSlotByStringyAddress    &hash2object
48      &refexpr2perlref
49      &expand
50      &deep_copy
51      &merge
52  );  );
53    #  &var_deref
54    #  &getStructSlotByStringyAddress
55    
56  use attributes;  use attributes;
57    use Data::Dumper;
58    use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );
59    
60    use Hash::Merge qw( merge );
61    use Iterate;
62    
63  sub var_NumericalHashToArray {  sub var_NumericalHashToArray {
64    my $vref = shift;    my $vref = shift;
# Line 57  sub var_NumericalHashToArray { Line 88  sub var_NumericalHashToArray {
88    
89  sub var_deref {  sub var_deref {
90    my $obj = shift;    my $obj = shift;
91      my $options = shift;
92    my $result;    my $result;
93    if ((ref $obj) eq 'ARRAY') {    if ((ref $obj) eq 'ARRAY') {
94      foreach (@{$obj}) {      foreach (@{$obj}) {
95        my $ref = ref $_;        my $ref = ref $_;
96        if ($ref) {        if ($ref) {
97          push(@{$result}, var_deref($_));          push(@{$result}, var_deref($_, $options));
98            #undef $_;
99        } else {        } else {
100          push(@{$result}, $_);          #push(@{$result}, $_);
101            push(@{$result}, deep_copy($_));
102        }        }
103          #undef $_ if $options->{destroy};
104          #$options->{destroy}->($_) if $options->{destroy};
105      }      }
106      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
107    } else {    } else {
108      foreach (keys %{$obj}) {      foreach (keys %{$obj}) {
109        my $key = $_;        my $key = $_;
110        my $ref = ref $obj->{$_};        my $ref = ref $obj->{$_};
111        if ($ref) {        if ($ref) {
112          $result->{$_} = var_deref($obj->{$_});          $result->{$_} = var_deref($obj->{$_}, $options);
113            #undef $obj->{$_};
114        } else {        } else {
115          $result->{$_} = $obj->{$_};          #$result->{$_} = $obj->{$_};
116            $result->{$_} = deep_copy($obj->{$_});
117        }        }
118          #undef $obj->{$_} if $options->{destroy};
119          #$options->{destroy}->($obj->{$_}) if $options->{destroy};
120      }      }
121    }    }
122      #undef $obj if $options->{destroy};
123      $options->{cb_destroy}->($obj) if $options->{cb_destroy};
124    return $result;    return $result;
125  }  }
126    
127    
128    sub expand {
129    
130      my $obj = shift;
131      my $options = shift;
132      my $result;
133    
134      if ((ref $obj) eq 'ARRAY') {
135    
136        IterArray @$obj, sub {
137          my $item;
138          # if current item is a reference ...
139          if (ref $_[0]) {
140            # ... expand structure recursively
141            $item = expand($_[0], $options);
142            # destroy item via seperate callback method (a POST) if requested
143            #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
144    
145          # ... assume plain scalar
146          } else {
147            #$item = deep_copy($_[0]);
148            $item = $_[0];
149            # conversions/encodings
150            $item = scalar2utf8($item) if ($item && $options->{utf8});
151          }
152          #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
153          push(@{$result}, $item);                 # use item in any case
154    
155        }
156    
157      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
158      } else {
159    
160        IterHash %$obj, sub {
161          my $item;
162          
163          # if current item is a reference ...
164          if (ref $_[1]) {
165            # ... expand structure recursively
166            $item = expand($_[1], $options);
167            # destroy item via seperate callback method (a POST) if requested
168            #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
169          
170          # ... assume plain scalar
171          } else {
172            #$item = deep_copy($_[1]);
173            $item = $_[1];
174            # conversions/encodings
175            $item = scalar2utf8($item) if ($item && $options->{utf8});
176          }
177          #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
178          $result->{$_[0]} = $item;               # use item in any case
179        }
180    
181      }
182    
183      # convert all values to utf8 (inside complex struct)
184        # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
185        # var2utf8($result) if ($options->{utf8});
186    
187      # destroy persistent object from memory to be sure to get a fresh one next time
188      #undef $obj if $options->{destroy};
189      #$options->{cb_destroy}->($obj) if $options->{cb_destroy};
190      #$options->{cb}->{destroy}->($obj) if $options->{destroy};
191      
192      return $result;
193    }
194    
195    
196    
197  my @indexstack;  my @indexstack;
# Line 129  sub var_traverse_mixin_update { Line 239  sub var_traverse_mixin_update {
239    #return $result;    #return $result;
240  }  }
241    
242    sub object2hash {
243      my $object = shift;
244      my $options = shift;
245      #my $deref = var_deref($object);
246      my $deref = expand($object, $options);
247      #var2utf8($deref) if ($options->{utf8});
248      return $deref;
249    }
250    
251    # todo: maybe do diff(s) here sometimes!?
252    sub hash2object {
253      my $object = shift;
254      my $data = shift;
255      my $options = shift;
256    
257      #print "hash2object", "\n";
258      
259      # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
260      # this method corrects this
261      var_NumericalHashToArray($data) if ($options->{php});
262    
263      # utf8-conversion/-encoding (essential for I18N)
264      var_utf2iso($data) if ($options->{utf8});
265    
266      # get fresh object from database
267      # todo:
268      #   - handle "locked" objects !!!
269      #   - check if already another update occoured (object-revisioning needed!)
270      #my $obj = $self->getObject($oid);
271    
272      # mix changes into fresh object and save it back
273      hash2object_traverse_mixin($object, $data, 0, $options);
274    
275      # done in core mixin function?
276      #$self->{storage}->update($obj);
277    
278      # we should "undef" some objects here to destroy them in memory and enforce reloading when used next time
279      # simulate:
280      #$self->{storage}->disconnect();
281    
282    }
283    
284    # ------------------------------------
285    #   core mixin function
286    # TODO-FEATURE: make this possible in a reverse way: object is empty (no fields) and gets filled up by mixin-data
287    
288    # remember keys of structures we are traversing
289    # this is a HACK:
290    #  - don't (!!!) "packageglobal" @indexstack
291    #  - it will lead to problems with parallelism!
292    
293    #my @indexstack;
294    
295    # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object
296    sub hash2object_traverse_mixin {
297      my $object = shift;
298      my $data = shift;
299      my $bool_recursion = shift;
300      my $options = shift;
301    
302      # clear our key - stack if we are called from user-code (non-recursively)
303      @indexstack = () if (!$bool_recursion);
304    
305      my $classname = ref $object;
306    #  if ($classname) {
307    #    print STDERR "*****************", Dumper(Class::Tangram::attribute_types($classname)), "\n";
308    #  }
309    
310      # parser: detected OBJECT (a Tangram one?)   (reftype == HASH) (assume)
311      # what's exactly done here? hmmm.... it works ;)
312      # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!
313      # extend! check!
314      if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
315    
316    #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
317            
318        my @fields;
319        # loop through fields of object (Tangram-object)
320        @fields = keys %{$object};
321    
322        # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
323        @fields = keys %{$data} if $options->{init};
324    #    @fields = keys %{$data} if $options->{mixin};
325        
326        foreach (@fields) {
327          my $field = $_;
328          push @indexstack, $field;
329                
330          # determine type of object
331          my $ref = ref $object->{$field};
332    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
333          if ($ref) {
334            hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
335          } else {
336            my $val = getStructSlotByStringyAddress($data, \@indexstack);
337            
338    #print Dumper($options);
339            my $field_target = $field;
340            if (my $pattern = $options->{pattern_strip_key}) {
341              print "pattern: $pattern", "\n";
342              $field_target =~ s/$pattern//;
343              print "field: $field_target", "\n";
344            }
345    
346            $object->{$field_target} = $val if defined $val;
347          }
348          pop @indexstack;
349        }
350    
351        # save object to database ...
352        # ... do an update if it already exists, do an insert if it doesn't
353    #    my $objectId = $self->{storage}->id($obj);
354    #    $logger->debug( __PACKAGE__ . "->saveObjectFromHash_traverse_mixin_update( object $obj objectId $objectId )" );
355    #    if ($objectId) {
356    #      $self->{storage}->update($obj);
357    
358    #print __PACKAGE__ . ":", "\n";
359    #print Dumper($object);
360    
361    #    } else {
362    #      $self->{storage}->insert($obj);
363    #    }
364        
365      }
366    
367    #&& ( ref($obj) ne 'HASH' )
368    
369        # loop through entries of array (IntrArray, isn't it?)
370      if ((ref $object) eq 'ARRAY') {
371    #    print STDERR "===", "refttype ", attributes::reftype($obj), "\n";
372        my $i = 0;
373        foreach (@{$object}) {
374          push @indexstack, $i;
375          my $ref = ref $_;
376    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
377    #      if ($ref && $_) {
378          if ($ref) {
379            hash2object_traverse_mixin($_, $data, 1, $options);
380          } else {
381            $object->[$i] = $_ if defined $_;
382          }
383          pop @indexstack;
384          $i++;
385        }
386      }
387    
388    }
389    
390    
391    # this function seems to do similar stuff like these below (refexpr2perlref & co.)
392    # TODO: maybe this mechanism can be replaced completely through some nice module from CPAN .... ?   ;-)
393  sub getStructSlotByStringyAddress {  sub getStructSlotByStringyAddress {
394    my $var = shift;    my $var = shift;
395    my $indexstack_ref = shift;    my $indexstack_ref = shift;
# Line 147  sub getStructSlotByStringyAddress { Line 408  sub getStructSlotByStringyAddress {
408    return eval($evstring);    return eval($evstring);
409  }  }
410    
411    
412    sub refexpr2perlref {
413    
414      my $obj = shift;
415      my $expr = shift;
416      my $callbackMap = shift;
417    
418      my $value;
419      # detect for callback (code-reference)
420      if (ref($expr) eq 'CODE') {
421        $value = &$expr($obj);
422    
423      } elsif ($expr =~ m/->/) {
424        # use expr as complex object reference declaration (obj->subObj->subSubObj->0->attribute)
425        (my $objPerlRefString, my $parts) = refexpr2perlref_parts($expr);
426        #print "\n", "expr: $expr";
427        #print "\n", "objPerlRefString: $objPerlRefString";
428        $value = eval('$obj' . '->' . $objPerlRefString);
429        
430        # if value isn't set, try to "fallback" to callbackMap
431        # callbacks are applied this way:
432        #   take the last element of the expression parts and check if this string exists as a key in the callback-map
433        if (!$value && $callbackMap) {
434          #print Dumper($callbackMap);
435          
436          # prepare needle
437          my @parts = @$parts;
438          my $count = $#parts;
439          my $needle = $parts[$count];
440    
441          # prepare haystack
442          my @haystack = keys %$callbackMap;
443          if (grep($needle, @haystack)) {
444            $value = $callbackMap->{$needle}->();
445            #print "value: ", $value, "\n";
446          }
447        }
448    
449      } else {
450        # use expr as simple scalar key (attributename)
451        $value = $obj->{$expr};
452      }
453              
454      return $value;
455      
456    }
457    
458    
459    sub refexpr2perlref_parts {
460      my $expr = shift;
461    
462      # split expression by dereference operators first
463      my @parts_pure = split(/->/, $expr);
464    
465      # wrap []'s around each part, if it consists of numeric characters only (=> numeric = array-index),
466      # use {}'s, if there are word-characters in it (=> alphanumeric = hash-key)
467      my @parts_capsule = @parts_pure;
468      map {
469        m/^\d+$/ && ($_ = "[$_]") || ($_ = "{$_}");
470      } @parts_capsule;
471    
472      # join parts with dereference operators together again and return built string
473      return (join('->', @parts_capsule), \@parts_pure);
474    }
475    
476    # ACK's go to ...
477    sub deep_copy {
478      my $this = shift;
479      if (not ref $this) {
480        $this;
481      } elsif (ref $this eq "ARRAY") {
482        [map deep_copy($_), @$this];
483      } elsif (ref $this eq "HASH") {
484        +{map { $_ => deep_copy($this->{$_}) } keys %$this};
485      } elsif (ref $this eq "CODE") {
486        $this;
487      #} else { die "deep_copy asks: what type is $this?" }
488      } else { print "deep_copy asks: what type is $this?", "\n"; }
489    }
490    
491  1;  1;

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.8

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed