/[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.3 by joko, Tue Dec 3 05:34:55 2002 UTC revision 1.23 by joko, Tue May 13 07:39:22 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.23  2003/05/13 07:39:22  joko
6  #  Revision 1.3  2002/12/03 05:34:55  joko  ##  new option 'define' for "sub expand": set value to empty string if desired
7  #  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode  ##
8  #  ##  Revision 1.22  2003/05/10 17:09:18  jonen
9  #  Revision 1.2  2002/12/01 04:44:07  joko  ##  + added keep of empty arrays/hashes if 'expand' for php
10  #  + code from Data::Transform::OO  ##
11  #  ##  Revision 1.21  2003/04/09 07:21:56  joko
12  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  childObj2string now inside Encode.pm, renamed to 'twingle_reference'
13  #  + initial check-in  ##
14  #  ##  Revision 1.20  2003/04/04 17:31:23  joko
15  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  minor update to 'childObj2string'
16  #  + new  ##
17  #  ##  Revision 1.19  2003/03/28 03:11:25  jonen
18  ##############################################  ##  + bugfix
19    ##
20    ##  Revision 1.18  2003/03/28 03:07:26  jonen
21    ##  + minor changes
22    ##
23    ##  Revision 1.17  2003/03/27 15:17:07  joko
24    ##  namespace fixes for Data::Mungle::*
25    ##
26    ##  Revision 1.16  2003/03/27 15:04:52  joko
27    ##  minor update: comment
28    ##
29    ##  Revision 1.15  2003/02/27 14:39:48  jonen
30    ##  + fixed bug at _hash2object()
31    ##
32    ##  Revision 1.14  2003/02/22 17:13:55  jonen
33    ##  + added function 'childObject2string()' to encode 'child'-references to option related string
34    ##  + use new option at 'expand()' for replacing 'childObject2string'
35    ##
36    ##  Revision 1.13  2003/02/21 01:48:50  joko
37    ##  renamed core function
38    ##
39    ##  Revision 1.12  2003/02/20 22:45:19  joko
40    ##  fix regarding new deep_copy
41    ##
42    ##  Revision 1.11  2003/02/20 21:13:54  joko
43    ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
44    ##
45    ##  Revision 1.10  2003/02/20 20:48:00  joko
46    ##  - refactored lots of code to Data::Code::Ref
47    ##  + alternative 'deep_copy' implementation
48    ##
49    ##  Revision 1.9  2003/02/18 19:35:56  joko
50    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
51    ##
52    ##  Revision 1.8  2003/02/09 05:10:56  joko
53    ##  + minor update
54    ##
55    ##  Revision 1.7  2003/01/19 03:26:59  joko
56    ##  + added 'sub deep_copy'  -  refactored from libp
57    ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
58    ##
59    ##  Revision 1.6  2002/12/23 11:27:53  jonen
60    ##  + changed behavior WATCH!
61    ##
62    ##  Revision 1.5  2002/12/16 19:57:54  joko
63    ##  + option 'init'
64    ##
65    ##  Revision 1.4  2002/12/05 13:56:49  joko
66    ##  - var_deref
67    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
68    ##
69    ##  Revision 1.3  2002/12/03 05:34:55  joko
70    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
71    ##
72    ##  Revision 1.2  2002/12/01 04:44:07  joko
73    ##  + code from Data::Transform::OO
74    ##
75    ##  Revision 1.1  2002/11/29 04:49:20  joko
76    ##  + initial check-in
77    ##
78    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
79    ##  + new
80    ## ---------------------------------------------------------------------------
81    
82    
83  package Data::Transform::Deep;  package Data::Mungle::Transform::Deep;
84    
85  use strict;  use strict;
86  use warnings;  use warnings;
# Line 26  use warnings; Line 88  use warnings;
88  require Exporter;  require Exporter;
89  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
90  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
91    &var_NumericalHashToArray    &expand
92    &var_deref    &deep_copy
93    &var_mixin    &merge_to
   &object2hash  
   &hash2object  
   &refexpr2perlref  
94  );  );
95  #  &getStructSlotByStringyAddress  
96    
97  use attributes;  use attributes;
98  use Data::Dumper;  use Data::Dumper;
99  use Data::Transform::Encode qw( var_utf2iso );  use Iterate;
100    
101    use Pitonyak::DeepCopy;
102    use Data::Mungle::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar twingle_reference );
103    use Data::Mungle::Code::Ref qw( ref_slot );
104    
105  sub var_NumericalHashToArray {  sub numhash2list {
106    my $vref = shift;    my $vref = shift;
107    #my $context = shift;    #my $context = shift;
108    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 55  sub var_NumericalHashToArray { Line 118  sub var_NumericalHashToArray {
118                }                }
119                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
120              }              }
121              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
122            }            }
123  #      } else {  #      } else {
124  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 65  sub var_NumericalHashToArray { Line 128  sub var_NumericalHashToArray {
128  }  }
129    
130    
131  sub var_deref {  # FIXME: could this be refactored using expand?
132    # btw: "expand": look at scripts@CPAN (System Administration):
133    # there is a perl make with perl
134    sub _var_deref_test {
135    my $obj = shift;    my $obj = shift;
136      my $options = shift;
137    my $result;    my $result;
138    if ((ref $obj) eq 'ARRAY') {    if ((ref $obj) eq 'ARRAY') {
139      foreach (@{$obj}) {      foreach (@{$obj}) {
140        my $ref = ref $_;        my $ref = ref $_;
141        if ($ref) {        if ($ref) {
142          push(@{$result}, var_deref($_));          push(@{$result}, var_deref($_, $options));
143            #undef $_;
144        } else {        } else {
145          push(@{$result}, $_);          #push(@{$result}, $_);
146            push(@{$result}, deep_copy($_));
147        }        }
148          #undef $_ if $options->{destroy};
149          #$options->{destroy}->($_) if $options->{destroy};
150      }      }
151    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
152    } else {    } else {
# Line 83  sub var_deref { Line 154  sub var_deref {
154        my $key = $_;        my $key = $_;
155        my $ref = ref $obj->{$_};        my $ref = ref $obj->{$_};
156        if ($ref) {        if ($ref) {
157          $result->{$_} = var_deref($obj->{$_});          $result->{$_} = var_deref($obj->{$_}, $options);
158            #undef $obj->{$_};
159        } else {        } else {
160          $result->{$_} = $obj->{$_};          #$result->{$_} = $obj->{$_};
161            $result->{$_} = deep_copy($obj->{$_});
162        }        }
163          #undef $obj->{$_} if $options->{destroy};
164          #$options->{destroy}->($obj->{$_}) if $options->{destroy};
165      }      }
166    }    }
167      #undef $obj if $options->{destroy};
168      $options->{cb_destroy}->($obj) if $options->{cb_destroy};
169    return $result;    return $result;
170  }  }
171    
172    
173    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
174    # but still using the known latin locale stuff
175    # TODO: Review: Could this be revamped using Clone.pm?
176    sub expand {
177    
178      my $obj = shift;
179      my $options = shift;
180      my $result;
181    
182      #print "ref: ", ref $obj, "\n";
183    
184      if (ref $obj eq 'ARRAY') {
185      
186       # if we expand for php, keep empty ARRAY
187       if($#$obj == -1 && $options->{childObj2string}) {
188         $result = $obj;
189       } else {
190        IterArray @$obj, sub {
191          my $item;
192          # if current item is a reference ...
193          if (ref $_[0]) {
194            $item = $_[0];
195            # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
196            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
197            if ($item && $options->{childObj2string}) {
198              $item = twingle_reference($item);
199            } else {
200              # ... expand structure recursively
201              $item = expand($_[0], $options);
202            }
203            # destroy item via seperate callback method (a POST) if requested
204            #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
205    
206          # ... assume plain scalar
207          } else {
208            #$item = deep_copy($_[0]);
209            $item = $_[0];
210            # conversions/encodings
211            $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
212            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
213          }
214          
215          $item = '' if $options->{define} and not defined $item;
216          #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
217          push(@{$result}, $item);                 # use item in any case
218    
219        }
220       }
221    
222      } elsif (ref $obj eq 'CODE') {
223        #print Dumper($obj);
224        #exit;
225    
226      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
227      } elsif (ref $obj) {
228      
229       # if we expand for php, keep empty HASH
230       my @tmp = keys %$obj;
231       if($#tmp == -1 && $options->{childObj2string}) {
232         $result = $obj;
233       } else {
234        IterHash %$obj, sub {
235          my $item;
236          
237          # if current item is a reference ...
238          if (ref $_[1]) {
239            $item = $_[1];
240            # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
241            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
242            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH") && !(ref $_[1] eq "Set::Object")) {
243              $item = twingle_reference($item);
244            } else {
245              # ... expand structure recursively
246              $item = expand($_[1], $options);
247            }
248            # destroy item via seperate callback method (a POST) if requested
249            #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
250          
251          # ... assume plain scalar
252          } else {
253            #$item = deep_copy($_[1]);
254            $item = $_[1];
255            # conversions/encodings
256            $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
257            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
258          }
259          
260          $item = '' if $options->{define} and not defined $item;
261          #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
262          $result->{$_[0]} = $item;               # use item in any case
263        }
264       }
265    
266      } else {
267        #die ("not a reference!");
268        $result = $obj;
269    
270      }
271    
272      # convert all values to utf8 (inside complex struct)
273        # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
274        # latin_to_utf8($result) if ($options->{utf8});
275    
276      # destroy persistent object from memory to be sure to get a fresh one next time
277      #undef $obj if $options->{destroy};
278      #$options->{cb_destroy}->($obj) if $options->{cb_destroy};
279      #$options->{cb}->{destroy}->($obj) if $options->{destroy};
280      
281      return $result;
282    }
283    
284    
285    
286  my @indexstack;  my @indexstack;
287  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
288    my $obj = shift;    my $obj = shift;
289    my $data = shift;    my $data = shift;
290    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 140  sub var_traverse_mixin_update { Line 328  sub var_traverse_mixin_update {
328    #return $result;    #return $result;
329  }  }
330    
331  sub object2hash {  sub merge_to {
332    my $object = shift;    _hash2object(@_);
333    my $options = shift;    # TODO:
334    my $deref = var_deref($object);    # re-implement using CPAN's "Iterate" and/or a modified Hash::Merge.
   var2utf8($deref) if ($options->{utf8});  
   return $deref;  
335  }  }
336    
337    
338  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
339  sub hash2object {  sub _hash2object {
340    my $object = shift;    my $object = shift;
341    my $data = shift;    my $data = shift;
342    my $options = shift;    my $options = shift;
# Line 158  sub hash2object { Line 345  sub hash2object {
345        
346    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
347    # this method corrects this    # this method corrects this
348    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
349    
350    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
351    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
352    
353    # get fresh object from database    # get fresh object from database
354    # todo:    # todo:
# Line 170  sub hash2object { Line 357  sub hash2object {
357    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
358    
359    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
360    hash2object_traverse_mixin($object, $data);    _hash2object_traverse_mixin($object, $data, 0, $options);
361    
362    # done in core mixin function?    # done in core mixin function?
363    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 193  sub hash2object { Line 380  sub hash2object {
380  #my @indexstack;  #my @indexstack;
381    
382  # 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
383  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
384    my $object = shift;    my $object = shift;
385    my $data = shift;    my $data = shift;
386    my $bool_recursion = shift;    my $bool_recursion = shift;
387      my $options = shift;
388    
389    # clear our key - stack if we are called from user-code (non-recursively)    # clear our key - stack if we are called from user-code (non-recursively)
390    @indexstack = () if (!$bool_recursion);    @indexstack = () if (!$bool_recursion);
# Line 210  sub hash2object_traverse_mixin { Line 398  sub hash2object_traverse_mixin {
398    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
399    # 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!!!
400    # extend! check!    # extend! check!
401    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
402      #print attributes::reftype($object), "\n";
403      
404      # V1
405      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
406      # V2
407      my $reftype = attributes::reftype($object);
408      #print "reftype: '$reftype'", "\n";
409      if ($reftype eq 'HASH') {
410    
411  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
412                    
413        my @fields;
414      # loop through fields of object (Tangram-object)      # loop through fields of object (Tangram-object)
415      foreach (keys %{$object}) {      @fields = keys %{$object};
416        push @indexstack, $_;  
417        # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
418        @fields = keys %{$data} if $options->{init};
419    #    @fields = keys %{$data} if $options->{mixin};
420        
421        foreach (@fields) {
422          my $field = $_;
423          push @indexstack, $field;
424                            
425        # determine type of object        # determine type of object
426        my $ref = ref $object->{$_};        my $ref = ref $object->{$field};
427  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
428        if ($ref) {        if ($ref) {
429          hash2object_traverse_mixin($object->{$_}, $data, 1);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
430        } else {        } else {
431          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
432          $object->{$_} = $val;                  
433    #print Dumper($options);
434            my $field_target = $field;
435            if (my $pattern = $options->{pattern_strip_key}) {
436              print "pattern: $pattern", "\n";
437              $field_target =~ s/$pattern//;
438              print "field: $field_target", "\n";
439            }
440    
441            $object->{$field_target} = $val if defined $val;
442        }        }
443        pop @indexstack;        pop @indexstack;
444      }      }
# Line 256  sub hash2object_traverse_mixin { Line 469  sub hash2object_traverse_mixin {
469        push @indexstack, $i;        push @indexstack, $i;
470        my $ref = ref $_;        my $ref = ref $_;
471  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
472        if ($ref && $_) {  #      if ($ref && $_) {
473          hash2object_traverse_mixin($_, $data, 1);        if ($ref) {
474            _hash2object_traverse_mixin($_, $data, 1, $options);
475        } else {        } else {
476          $object->[$i] = $_;          $object->[$i] = $_ if defined $_;
477        }        }
478        pop @indexstack;        pop @indexstack;
479        $i++;        $i++;
480      }      }
481    
482    =pod
483      # object?
484      } else {
485        print "reference: ", ref $object, "\n";
486        print "reftype: ", $reftype, "\n";
487        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
488    =cut
489      
490    }    }
491    
492  }  }
493    
494    
495  # this function seems to do similar stuff like these below (refexpr2perlref & co.)  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
496  sub getStructSlotByStringyAddress {  # on the website:
497    my $var = shift;  # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
498    my $indexstack_ref = shift;  # Further distribution or use is not permitted.
499    my @indexstack = @{$indexstack_ref};  # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
500    my $joiner = '->';  sub deep_copy1 {
501    my @evlist;    my $this = shift;
502    foreach (@indexstack) {    if (not ref $this) {
503      my $elem;      $this;
504      if ($_ =~ m/\d+/) { $elem = "[$_]"; }    } elsif (ref $this eq "ARRAY") {
505      if ($_ =~ m/\D+/) { $elem = "{$_}"; }      [map deep_copy1($_), @$this];
506      push @evlist, $elem;    } elsif (ref $this eq "HASH") {
507    }      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
508    my $evstring = join($joiner, @evlist);    } elsif (ref $this eq "CODE") {
509    $evstring = 'return $var->' . $evstring . ';';      $this;
510    #print "ev: $evstring\n";    } else { die "deep_copy1 asks: what type is $this?" }
511    return eval($evstring);    #} else { print "deep_copy asks: what type is $this?", "\n"; }
512  }  }
513    
514    # ACK's go to Andrew Pitonyak
515  sub refexpr2perlref {  # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
516    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
517    my $obj = shift;  sub deep_copy {
518    my $expr = shift;    Pitonyak::DeepCopy::deep_copy(@_);
   my $callbackMap = shift;  
   
   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;  
     
519  }  }
520    
521    
 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);  
 }  
   
522  1;  1;
523    __END__

Legend:
Removed from v.1.3  
changed lines
  Added in v.1.23

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