/[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.8 by joko, Sun Feb 9 05:10:56 2003 UTC revision 1.22 by jonen, Sat May 10 17:09:18 2003 UTC
# Line 2  Line 2 
2  ##  $Id$  ##  $Id$
3  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
4  ##  $Log$  ##  $Log$
5    ##  Revision 1.22  2003/05/10 17:09:18  jonen
6    ##  + added keep of empty arrays/hashes if 'expand' for php
7    ##
8    ##  Revision 1.21  2003/04/09 07:21:56  joko
9    ##  childObj2string now inside Encode.pm, renamed to 'twingle_reference'
10    ##
11    ##  Revision 1.20  2003/04/04 17:31:23  joko
12    ##  minor update to 'childObj2string'
13    ##
14    ##  Revision 1.19  2003/03/28 03:11:25  jonen
15    ##  + bugfix
16    ##
17    ##  Revision 1.18  2003/03/28 03:07:26  jonen
18    ##  + minor changes
19    ##
20    ##  Revision 1.17  2003/03/27 15:17:07  joko
21    ##  namespace fixes for Data::Mungle::*
22    ##
23    ##  Revision 1.16  2003/03/27 15:04:52  joko
24    ##  minor update: comment
25    ##
26    ##  Revision 1.15  2003/02/27 14:39:48  jonen
27    ##  + fixed bug at _hash2object()
28    ##
29    ##  Revision 1.14  2003/02/22 17:13:55  jonen
30    ##  + added function 'childObject2string()' to encode 'child'-references to option related string
31    ##  + use new option at 'expand()' for replacing 'childObject2string'
32    ##
33    ##  Revision 1.13  2003/02/21 01:48:50  joko
34    ##  renamed core function
35    ##
36    ##  Revision 1.12  2003/02/20 22:45:19  joko
37    ##  fix regarding new deep_copy
38    ##
39    ##  Revision 1.11  2003/02/20 21:13:54  joko
40    ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
41    ##
42    ##  Revision 1.10  2003/02/20 20:48:00  joko
43    ##  - refactored lots of code to Data::Code::Ref
44    ##  + alternative 'deep_copy' implementation
45    ##
46    ##  Revision 1.9  2003/02/18 19:35:56  joko
47    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
48    ##
49  ##  Revision 1.8  2003/02/09 05:10:56  joko  ##  Revision 1.8  2003/02/09 05:10:56  joko
50  ##  + minor update  ##  + minor update
51  ##  ##
# Line 33  Line 77 
77  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
78    
79    
80  package Data::Transform::Deep;  package Data::Mungle::Transform::Deep;
81    
82  use strict;  use strict;
83  use warnings;  use warnings;
# Line 41  use warnings; Line 85  use warnings;
85  require Exporter;  require Exporter;
86  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
87  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
88    &expand    &expand
89    &deep_copy    &deep_copy
90    &merge    &merge_to
91  );  );
92  #  &var_deref  
 #  &getStructSlotByStringyAddress  
93    
94  use attributes;  use attributes;
95  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
   
 use Hash::Merge qw( merge );  
96  use Iterate;  use Iterate;
97    
98  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
99    use Data::Mungle::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar twingle_reference );
100    use Data::Mungle::Code::Ref qw( ref_slot );
101    
102    sub numhash2list {
103    my $vref = shift;    my $vref = shift;
104    #my $context = shift;    #my $context = shift;
105    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 76  sub var_NumericalHashToArray { Line 115  sub var_NumericalHashToArray {
115                }                }
116                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
117              }              }
118              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
119            }            }
120  #      } else {  #      } else {
121  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 86  sub var_NumericalHashToArray { Line 125  sub var_NumericalHashToArray {
125  }  }
126    
127    
128  sub var_deref {  # FIXME: could this be refactored using expand?
129    # btw: "expand": look at scripts@CPAN (System Administration):
130    # there is a perl make with perl
131    sub _var_deref_test {
132    my $obj = shift;    my $obj = shift;
133    my $options = shift;    my $options = shift;
134    my $result;    my $result;
# Line 125  sub var_deref { Line 167  sub var_deref {
167  }  }
168    
169    
170    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
171    # but still using the known latin locale stuff
172  sub expand {  sub expand {
173    
174    my $obj = shift;    my $obj = shift;
175    my $options = shift;    my $options = shift;
176    my $result;    my $result;
177    
178    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
179    
180      if (ref $obj eq 'ARRAY') {
181      
182       # if we expand for php, keep empty ARRAY
183       if($#$obj == -1 && $options->{childObj2string}) {
184         $result = $obj;
185       } else {
186      IterArray @$obj, sub {      IterArray @$obj, sub {
187        my $item;        my $item;
188        # if current item is a reference ...        # if current item is a reference ...
189        if (ref $_[0]) {        if (ref $_[0]) {
190          # ... expand structure recursively          $item = $_[0];
191          $item = expand($_[0], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
192            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
193            if ($item && $options->{childObj2string}) {
194              $item = twingle_reference($item);
195            } else {
196              # ... expand structure recursively
197              $item = expand($_[0], $options);
198            }
199          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
200          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
201    
# Line 147  sub expand { Line 204  sub expand {
204          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
205          $item = $_[0];          $item = $_[0];
206          # conversions/encodings          # conversions/encodings
207          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
208            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
209        }        }
210        #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)
211        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
212    
213      }      }
214       }
215    
216    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    } elsif (ref $obj eq 'CODE') {
217    } else {      #print Dumper($obj);
218        #exit;
219    
220      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
221      } elsif (ref $obj) {
222      
223       # if we expand for php, keep empty HASH
224       my @tmp = keys %$obj;
225       if($#tmp == -1 && $options->{childObj2string}) {
226         $result = $obj;
227       } else {
228      IterHash %$obj, sub {      IterHash %$obj, sub {
229        my $item;        my $item;
230                
231        # if current item is a reference ...        # if current item is a reference ...
232        if (ref $_[1]) {        if (ref $_[1]) {
233          # ... expand structure recursively          $item = $_[1];
234          $item = expand($_[1], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
235            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
236            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH") && !(ref $_[1] eq "Set::Object")) {
237              $item = twingle_reference($item);
238            } else {
239              # ... expand structure recursively
240              $item = expand($_[1], $options);
241            }
242          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
243          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
244                
# Line 172  sub expand { Line 247  sub expand {
247          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
248          $item = $_[1];          $item = $_[1];
249          # conversions/encodings          # conversions/encodings
250          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
251            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
252        }        }
253        #$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)
254        $result->{$_[0]} = $item;               # use item in any case        $result->{$_[0]} = $item;               # use item in any case
255      }      }
256       }
257    
258      } else {
259        #die ("not a reference!");
260        $result = $obj;
261    
262    }    }
263    
264    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
265      # 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
266      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
267    
268    # 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
269    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 195  sub expand { Line 276  sub expand {
276    
277    
278  my @indexstack;  my @indexstack;
279  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
280    my $obj = shift;    my $obj = shift;
281    my $data = shift;    my $data = shift;
282    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 239  sub var_traverse_mixin_update { Line 320  sub var_traverse_mixin_update {
320    #return $result;    #return $result;
321  }  }
322    
323  sub object2hash {  sub merge_to {
324    my $object = shift;    _hash2object(@_);
325    my $options = shift;    # TODO:
326    #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;  
327  }  }
328    
329    
330  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
331  sub hash2object {  sub _hash2object {
332    my $object = shift;    my $object = shift;
333    my $data = shift;    my $data = shift;
334    my $options = shift;    my $options = shift;
# Line 258  sub hash2object { Line 337  sub hash2object {
337        
338    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
339    # this method corrects this    # this method corrects this
340    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
341    
342    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
343    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
344    
345    # get fresh object from database    # get fresh object from database
346    # todo:    # todo:
# Line 270  sub hash2object { Line 349  sub hash2object {
349    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
350    
351    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
352    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
353    
354    # done in core mixin function?    # done in core mixin function?
355    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 293  sub hash2object { Line 372  sub hash2object {
372  #my @indexstack;  #my @indexstack;
373    
374  # 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
375  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
376    my $object = shift;    my $object = shift;
377    my $data = shift;    my $data = shift;
378    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 311  sub hash2object_traverse_mixin { Line 390  sub hash2object_traverse_mixin {
390    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
391    # 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!!!
392    # extend! check!    # extend! check!
393    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
394      #print attributes::reftype($object), "\n";
395      
396      # V1
397      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
398      # V2
399      my $reftype = attributes::reftype($object);
400      #print "reftype: '$reftype'", "\n";
401      if ($reftype eq 'HASH') {
402    
403  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
404                    
# Line 331  sub hash2object_traverse_mixin { Line 418  sub hash2object_traverse_mixin {
418        my $ref = ref $object->{$field};        my $ref = ref $object->{$field};
419  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
420        if ($ref) {        if ($ref) {
421          hash2object_traverse_mixin($object->{$field}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
422        } else {        } else {
423          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
424                    
425  #print Dumper($options);  #print Dumper($options);
426          my $field_target = $field;          my $field_target = $field;
# Line 376  sub hash2object_traverse_mixin { Line 463  sub hash2object_traverse_mixin {
463  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
464  #      if ($ref && $_) {  #      if ($ref && $_) {
465        if ($ref) {        if ($ref) {
466          hash2object_traverse_mixin($_, $data, 1, $options);          _hash2object_traverse_mixin($_, $data, 1, $options);
467        } else {        } else {
468          $object->[$i] = $_ if defined $_;          $object->[$i] = $_ if defined $_;
469        }        }
470        pop @indexstack;        pop @indexstack;
471        $i++;        $i++;
472      }      }
   }  
   
 }  
   
   
 # this function seems to do similar stuff like these below (refexpr2perlref & co.)  
 # TODO: maybe this mechanism can be replaced completely through some nice module from CPAN .... ?   ;-)  
 sub getStructSlotByStringyAddress {  
   my $var = shift;  
   my $indexstack_ref = shift;  
   my @indexstack = @{$indexstack_ref};  
   my $joiner = '->';  
   my @evlist;  
   foreach (@indexstack) {  
     my $elem;  
     if ($_ =~ m/\d+/) { $elem = "[$_]"; }  
     if ($_ =~ m/\D+/) { $elem = "{$_}"; }  
     push @evlist, $elem;  
   }  
   my $evstring = join($joiner, @evlist);  
   $evstring = 'return $var->' . $evstring . ';';  
   #print "ev: $evstring\n";  
   return eval($evstring);  
 }  
   
   
 sub refexpr2perlref {  
   
   my $obj = shift;  
   my $expr = shift;  
   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";  
       }  
     }  
473    
474    =pod
475      # object?
476    } else {    } else {
477      # use expr as simple scalar key (attributename)      print "reference: ", ref $object, "\n";
478      $value = $obj->{$expr};      print "reftype: ", $reftype, "\n";
479    }      die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
480              =cut
   return $value;  
481        
482  }    }
   
   
 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;  
483    
   # join parts with dereference operators together again and return built string  
   return (join('->', @parts_capsule), \@parts_pure);  
484  }  }
485    
486  # ACK's go to ...  
487  sub deep_copy {  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
488    # on the website:
489    # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
490    # Further distribution or use is not permitted.
491    # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
492    sub deep_copy1 {
493    my $this = shift;    my $this = shift;
494    if (not ref $this) {    if (not ref $this) {
495      $this;      $this;
496    } elsif (ref $this eq "ARRAY") {    } elsif (ref $this eq "ARRAY") {
497      [map deep_copy($_), @$this];      [map deep_copy1($_), @$this];
498    } elsif (ref $this eq "HASH") {    } elsif (ref $this eq "HASH") {
499      +{map { $_ => deep_copy($this->{$_}) } keys %$this};      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
500    } elsif (ref $this eq "CODE") {    } elsif (ref $this eq "CODE") {
501      $this;      $this;
502    #} else { die "deep_copy asks: what type is $this?" }    } else { die "deep_copy1 asks: what type is $this?" }
503    } else { print "deep_copy asks: what type is $this?", "\n"; }    #} else { print "deep_copy asks: what type is $this?", "\n"; }
504  }  }
505    
506    # ACK's go to Andrew Pitonyak
507    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
508    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
509    sub deep_copy {
510      Pitonyak::DeepCopy::deep_copy(@_);
511    }
512    
513    
514  1;  1;
515    __END__

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

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