/[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.5 by joko, Mon Dec 16 19:57:54 2002 UTC revision 1.16 by joko, Thu Mar 27 15:04:52 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.16  2003/03/27 15:04:52  joko
6  #  Revision 1.5  2002/12/16 19:57:54  joko  ##  minor update: comment
7  #  + option 'init'  ##
8  #  ##  Revision 1.15  2003/02/27 14:39:48  jonen
9  #  Revision 1.4  2002/12/05 13:56:49  joko  ##  + fixed bug at _hash2object()
10  #  - var_deref  ##
11  #  + expand - more sophisticated dereferencing with callbacks using Iterate  ##  Revision 1.14  2003/02/22 17:13:55  jonen
12  #  ##  + added function 'childObject2string()' to encode 'child'-references to option related string
13  #  Revision 1.3  2002/12/03 05:34:55  joko  ##  + use new option at 'expand()' for replacing 'childObject2string'
14  #  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode  ##
15  #  ##  Revision 1.13  2003/02/21 01:48:50  joko
16  #  Revision 1.2  2002/12/01 04:44:07  joko  ##  renamed core function
17  #  + code from Data::Transform::OO  ##
18  #  ##  Revision 1.12  2003/02/20 22:45:19  joko
19  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  fix regarding new deep_copy
20  #  + initial check-in  ##
21  #  ##  Revision 1.11  2003/02/20 21:13:54  joko
22  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
23  #  + new  ##
24  #  ##  Revision 1.10  2003/02/20 20:48:00  joko
25  ##############################################  ##  - refactored lots of code to Data::Code::Ref
26    ##  + alternative 'deep_copy' implementation
27    ##
28    ##  Revision 1.9  2003/02/18 19:35:56  joko
29    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
30    ##
31    ##  Revision 1.8  2003/02/09 05:10:56  joko
32    ##  + minor update
33    ##
34    ##  Revision 1.7  2003/01/19 03:26:59  joko
35    ##  + added 'sub deep_copy'  -  refactored from libp
36    ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
37    ##
38    ##  Revision 1.6  2002/12/23 11:27:53  jonen
39    ##  + changed behavior WATCH!
40    ##
41    ##  Revision 1.5  2002/12/16 19:57:54  joko
42    ##  + option 'init'
43    ##
44    ##  Revision 1.4  2002/12/05 13:56:49  joko
45    ##  - var_deref
46    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
47    ##
48    ##  Revision 1.3  2002/12/03 05:34:55  joko
49    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
50    ##
51    ##  Revision 1.2  2002/12/01 04:44:07  joko
52    ##  + code from Data::Transform::OO
53    ##
54    ##  Revision 1.1  2002/11/29 04:49:20  joko
55    ##  + initial check-in
56    ##
57    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
58    ##  + new
59    ## ---------------------------------------------------------------------------
60    
61    
62  package Data::Transform::Deep;  package Data::Transform::Deep;
# Line 33  use warnings; Line 67  use warnings;
67  require Exporter;  require Exporter;
68  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
69  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
70    &expand    &expand
71      &deep_copy
72      &merge_to
73  );  );
74  #  &var_deref  
 #  &getStructSlotByStringyAddress  
75    
76  use attributes;  use attributes;
77  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
 use libp qw( deep_copy );  
78  use Iterate;  use Iterate;
79    
80  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
81    use Data::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar );
82    use Data::Code::Ref qw( ref_slot );
83    
84    sub numhash2list {
85    my $vref = shift;    my $vref = shift;
86    #my $context = shift;    #my $context = shift;
87    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 65  sub var_NumericalHashToArray { Line 97  sub var_NumericalHashToArray {
97                }                }
98                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
99              }              }
100              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
101            }            }
102  #      } else {  #      } else {
103  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 75  sub var_NumericalHashToArray { Line 107  sub var_NumericalHashToArray {
107  }  }
108    
109    
110  sub var_deref {  # FIXME: could this be refactored using expand?
111    # btw: "expand": look at scripts@CPAN (System Administration):
112    # there is a perl make with perl
113    sub _var_deref_test {
114    my $obj = shift;    my $obj = shift;
115    my $options = shift;    my $options = shift;
116    my $result;    my $result;
# Line 114  sub var_deref { Line 149  sub var_deref {
149  }  }
150    
151    
152    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
153    # but still using the known latin locale stuff
154  sub expand {  sub expand {
155    
156    my $obj = shift;    my $obj = shift;
157    my $options = shift;    my $options = shift;
158    my $result;    my $result;
159    
160    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
161    
162      if (ref $obj eq 'ARRAY') {
163    
164      IterArray @$obj, sub {      IterArray @$obj, sub {
165        my $item;        my $item;
166        # if current item is a reference ...        # if current item is a reference ...
167        if (ref $_[0]) {        if (ref $_[0]) {
168          # ... expand structure recursively          $item = $_[0];
169          $item = expand($_[0], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
170            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
171            if ($item && $options->{childObj2string}) {
172              $item = childObj2string($item, $options->{childObj2string});
173            } else {
174              # ... expand structure recursively
175              $item = expand($_[0], $options);
176            }
177          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
178          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
179    
# Line 136  sub expand { Line 182  sub expand {
182          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
183          $item = $_[0];          $item = $_[0];
184          # conversions/encodings          # conversions/encodings
185          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
186            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
187        }        }
188        #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)        #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
189        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
190    
191      }      }
192    
193      } elsif (ref $obj eq 'CODE') {
194        #print Dumper($obj);
195        #exit;
196    
197    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
198    } else {    } elsif (ref $obj) {
199    
200      IterHash %$obj, sub {      IterHash %$obj, sub {
201        my $item;        my $item;
202                
203        # if current item is a reference ...        # if current item is a reference ...
204        if (ref $_[1]) {        if (ref $_[1]) {
205          # ... expand structure recursively          $item = $_[1];
206          $item = expand($_[1], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
207            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
208            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH")) {
209              $item = childObj2string($item, $options->{childObj2string});
210            } else {
211              # ... expand structure recursively
212              $item = expand($_[1], $options);
213            }
214          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
215          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
216                
# Line 161  sub expand { Line 219  sub expand {
219          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
220          $item = $_[1];          $item = $_[1];
221          # conversions/encodings          # conversions/encodings
222          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
223            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
224        }        }
225        #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)        #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
226        $result->{$_[0]} = $item;               # use item in any case        $result->{$_[0]} = $item;               # use item in any case
227      }      }
228    
229      } else {
230        #die ("not a reference!");
231        $result = $obj;
232    
233    }    }
234    
235    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
236      # now done in core-item-callbacks via Greg London's "Iterate" from CPAN      # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
237      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
238    
239    # destroy persistent object from memory to be sure to get a fresh one next time    # destroy persistent object from memory to be sure to get a fresh one next time
240    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 184  sub expand { Line 247  sub expand {
247    
248    
249  my @indexstack;  my @indexstack;
250  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
251    my $obj = shift;    my $obj = shift;
252    my $data = shift;    my $data = shift;
253    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 228  sub var_traverse_mixin_update { Line 291  sub var_traverse_mixin_update {
291    #return $result;    #return $result;
292  }  }
293    
294  sub object2hash {  sub merge_to {
295    my $object = shift;    _hash2object(@_);
296    my $options = shift;    # TODO:
297    #my $deref = var_deref($object);    # re-implement using CPAN's "Iterate" and/or a modified Hash::Merge.
   my $deref = expand($object, $options);  
   #var2utf8($deref) if ($options->{utf8});  
   return $deref;  
298  }  }
299    
300    
301  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
302  sub hash2object {  sub _hash2object {
303    my $object = shift;    my $object = shift;
304    my $data = shift;    my $data = shift;
305    my $options = shift;    my $options = shift;
# Line 247  sub hash2object { Line 308  sub hash2object {
308        
309    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
310    # this method corrects this    # this method corrects this
311    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
312    
313    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
314    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
315    
316    # get fresh object from database    # get fresh object from database
317    # todo:    # todo:
# Line 259  sub hash2object { Line 320  sub hash2object {
320    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
321    
322    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
323    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
324    
325    # done in core mixin function?    # done in core mixin function?
326    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 282  sub hash2object { Line 343  sub hash2object {
343  #my @indexstack;  #my @indexstack;
344    
345  # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object  # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object
346  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
347    my $object = shift;    my $object = shift;
348    my $data = shift;    my $data = shift;
349    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 300  sub hash2object_traverse_mixin { Line 361  sub hash2object_traverse_mixin {
361    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
362    # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!    # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!
363    # extend! check!    # extend! check!
364    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
365      #print attributes::reftype($object), "\n";
366      
367      # V1
368      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
369      # V2
370      my $reftype = attributes::reftype($object);
371      #print "reftype: '$reftype'", "\n";
372      if ($reftype eq 'HASH') {
373    
374  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
375                    
# Line 310  sub hash2object_traverse_mixin { Line 379  sub hash2object_traverse_mixin {
379    
380      # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)      # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
381      @fields = keys %{$data} if $options->{init};      @fields = keys %{$data} if $options->{init};
382    #    @fields = keys %{$data} if $options->{mixin};
383            
384      foreach (@fields) {      foreach (@fields) {
385        push @indexstack, $_;        my $field = $_;
386          push @indexstack, $field;
387                            
388        # determine type of object        # determine type of object
389        my $ref = ref $object->{$_};        my $ref = ref $object->{$field};
390  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
391        if ($ref) {        if ($ref) {
392          hash2object_traverse_mixin($object->{$_}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
393        } else {        } else {
394          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
395          $object->{$_} = $val;                  
396    #print Dumper($options);
397            my $field_target = $field;
398            if (my $pattern = $options->{pattern_strip_key}) {
399              print "pattern: $pattern", "\n";
400              $field_target =~ s/$pattern//;
401              print "field: $field_target", "\n";
402            }
403    
404            $object->{$field_target} = $val if defined $val;
405        }        }
406        pop @indexstack;        pop @indexstack;
407      }      }
# Line 352  sub hash2object_traverse_mixin { Line 432  sub hash2object_traverse_mixin {
432        push @indexstack, $i;        push @indexstack, $i;
433        my $ref = ref $_;        my $ref = ref $_;
434  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
435        if ($ref && $_) {  #      if ($ref && $_) {
436          hash2object_traverse_mixin($_, $data, 1, $options);        if ($ref) {
437            _hash2object_traverse_mixin($_, $data, 1, $options);
438        } else {        } else {
439          $object->[$i] = $_;          $object->[$i] = $_ if defined $_;
440        }        }
441        pop @indexstack;        pop @indexstack;
442        $i++;        $i++;
443      }      }
444    
445    =pod
446      # object?
447      } else {
448        print "reference: ", ref $object, "\n";
449        print "reftype: ", $reftype, "\n";
450        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
451    =cut
452      
453    }    }
454    
455  }  }
456    
457    
458  # this function seems to do similar stuff like these below (refexpr2perlref & co.)  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
459  # TODO: maybe this mechanism can be replaced completely through some nice module from CPAN .... ?   ;-)  # on the website:
460  sub getStructSlotByStringyAddress {  # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
461    my $var = shift;  # Further distribution or use is not permitted.
462    my $indexstack_ref = shift;  # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
463    my @indexstack = @{$indexstack_ref};  sub deep_copy1 {
464    my $joiner = '->';    my $this = shift;
465    my @evlist;    if (not ref $this) {
466    foreach (@indexstack) {      $this;
467      my $elem;    } elsif (ref $this eq "ARRAY") {
468      if ($_ =~ m/\d+/) { $elem = "[$_]"; }      [map deep_copy1($_), @$this];
469      if ($_ =~ m/\D+/) { $elem = "{$_}"; }    } elsif (ref $this eq "HASH") {
470      push @evlist, $elem;      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
471    }    } elsif (ref $this eq "CODE") {
472    my $evstring = join($joiner, @evlist);      $this;
473    $evstring = 'return $var->' . $evstring . ';';    } else { die "deep_copy1 asks: what type is $this?" }
474    #print "ev: $evstring\n";    #} else { print "deep_copy asks: what type is $this?", "\n"; }
   return eval($evstring);  
475  }  }
476    
477    # ACK's go to Andrew Pitonyak
478    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
479    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
480    sub deep_copy {
481      Pitonyak::DeepCopy::deep_copy(@_);
482    }
483    
 sub refexpr2perlref {  
484    
485    sub childObj2string {
486    my $obj = shift;    my $obj = shift;
487    my $expr = shift;    my $option = shift;
488    my $callbackMap = shift;    my $classname = ref $obj;
   
   my $value;  
   # detect for callback (code-reference)  
   if (ref($expr) eq 'CODE') {  
     $value = &$expr($obj);  
   
   } elsif ($expr =~ m/->/) {  
     # use expr as complex object reference declaration (obj->subObj->subSubObj->0->attribute)  
     (my $objPerlRefString, my $parts) = refexpr2perlref_parts($expr);  
     #print "\n", "expr: $expr";  
     #print "\n", "objPerlRefString: $objPerlRefString";  
     $value = eval('$obj' . '->' . $objPerlRefString);  
       
     # if value isn't set, try to "fallback" to callbackMap  
     # callbacks are applied this way:  
     #   take the last element of the expression parts and check if this string exists as a key in the callback-map  
     if (!$value && $callbackMap) {  
       #print Dumper($callbackMap);  
         
       # prepare needle  
       my @parts = @$parts;  
       my $count = $#parts;  
       my $needle = $parts[$count];  
   
       # prepare haystack  
       my @haystack = keys %$callbackMap;  
       if (grep($needle, @haystack)) {  
         $value = $callbackMap->{$needle}->();  
         #print "value: ", $value, "\n";  
       }  
     }  
   
   } else {  
     # use expr as simple scalar key (attributename)  
     $value = $obj->{$expr};  
   }  
             
   return $value;  
489        
490      if($option == 1) {
491        my $string = "o_" . $classname . "_" .$obj->{guid};
492        return $string;
493      }  
494  }  }
495    
496    
 sub refexpr2perlref_parts {  
   my $expr = shift;  
   
   # split expression by dereference operators first  
   my @parts_pure = split(/->/, $expr);  
   
   # wrap []'s around each part, if it consists of numeric characters only (=> numeric = array-index),  
   # use {}'s, if there are word-characters in it (=> alphanumeric = hash-key)  
   my @parts_capsule = @parts_pure;  
   map {  
     m/^\d+$/ && ($_ = "[$_]") || ($_ = "{$_}");  
   } @parts_capsule;  
   
   # join parts with dereference operators together again and return built string  
   return (join('->', @parts_capsule), \@parts_pure);  
 }  
   
497  1;  1;
498    __END__

Legend:
Removed from v.1.5  
changed lines
  Added in v.1.16

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