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

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

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