/[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.24 by joko, Mon Jun 7 16:44:54 2004 UTC
# Line 2  Line 2 
2  ##  $Id$  ##  $Id$
3  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
4  ##  $Log$  ##  $Log$
5    ##  Revision 1.24  2004/06/07 16:44:54  joko
6    ##  sub expand: Now also converts hash-keys to/from utf-8
7    ##
8    ##  Revision 1.23  2003/05/13 07:39:22  joko
9    ##  new option 'define' for "sub expand": set value to empty string if desired
10    ##
11    ##  Revision 1.22  2003/05/10 17:09:18  jonen
12    ##  + added keep of empty arrays/hashes if 'expand' for php
13    ##
14    ##  Revision 1.21  2003/04/09 07:21:56  joko
15    ##  childObj2string now inside Encode.pm, renamed to 'twingle_reference'
16    ##
17    ##  Revision 1.20  2003/04/04 17:31:23  joko
18    ##  minor update to 'childObj2string'
19    ##
20    ##  Revision 1.19  2003/03/28 03:11:25  jonen
21    ##  + bugfix
22    ##
23    ##  Revision 1.18  2003/03/28 03:07:26  jonen
24    ##  + minor changes
25    ##
26    ##  Revision 1.17  2003/03/27 15:17:07  joko
27    ##  namespace fixes for Data::Mungle::*
28    ##
29    ##  Revision 1.16  2003/03/27 15:04:52  joko
30    ##  minor update: comment
31    ##
32    ##  Revision 1.15  2003/02/27 14:39:48  jonen
33    ##  + fixed bug at _hash2object()
34    ##
35    ##  Revision 1.14  2003/02/22 17:13:55  jonen
36    ##  + added function 'childObject2string()' to encode 'child'-references to option related string
37    ##  + use new option at 'expand()' for replacing 'childObject2string'
38    ##
39    ##  Revision 1.13  2003/02/21 01:48:50  joko
40    ##  renamed core function
41    ##
42    ##  Revision 1.12  2003/02/20 22:45:19  joko
43    ##  fix regarding new deep_copy
44    ##
45    ##  Revision 1.11  2003/02/20 21:13:54  joko
46    ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
47    ##
48    ##  Revision 1.10  2003/02/20 20:48:00  joko
49    ##  - refactored lots of code to Data::Code::Ref
50    ##  + alternative 'deep_copy' implementation
51    ##
52    ##  Revision 1.9  2003/02/18 19:35:56  joko
53    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
54    ##
55  ##  Revision 1.8  2003/02/09 05:10:56  joko  ##  Revision 1.8  2003/02/09 05:10:56  joko
56  ##  + minor update  ##  + minor update
57  ##  ##
# Line 33  Line 83 
83  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
84    
85    
86  package Data::Transform::Deep;  package Data::Mungle::Transform::Deep;
87    
88  use strict;  use strict;
89  use warnings;  use warnings;
# Line 41  use warnings; Line 91  use warnings;
91  require Exporter;  require Exporter;
92  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
93  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
94    &expand    &expand
95    &deep_copy    &deep_copy
96    &merge    &merge_to
97  );  );
98  #  &var_deref  
 #  &getStructSlotByStringyAddress  
99    
100  use attributes;  use attributes;
101  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
   
 use Hash::Merge qw( merge );  
102  use Iterate;  use Iterate;
103    
104  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
105    use Data::Mungle::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar twingle_reference );
106    use Data::Mungle::Code::Ref qw( ref_slot );
107    
108    sub numhash2list {
109    my $vref = shift;    my $vref = shift;
110    #my $context = shift;    #my $context = shift;
111    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 76  sub var_NumericalHashToArray { Line 121  sub var_NumericalHashToArray {
121                }                }
122                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
123              }              }
124              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
125            }            }
126  #      } else {  #      } else {
127  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 86  sub var_NumericalHashToArray { Line 131  sub var_NumericalHashToArray {
131  }  }
132    
133    
134  sub var_deref {  # FIXME: could this be refactored using expand?
135    # btw: "expand": look at scripts@CPAN (System Administration):
136    # there is a perl make with perl
137    sub _var_deref_test {
138    my $obj = shift;    my $obj = shift;
139    my $options = shift;    my $options = shift;
140    my $result;    my $result;
# Line 125  sub var_deref { Line 173  sub var_deref {
173  }  }
174    
175    
176    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
177    # but still using the known latin locale stuff
178    # TODO: Review: Could this be revamped using Clone.pm?
179  sub expand {  sub expand {
180    
181    my $obj = shift;    my $obj = shift;
182    my $options = shift;    my $options = shift;
183    my $result;    my $result;
184    
185    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
186    
187      if (ref $obj eq 'ARRAY') {
188      
189       # if we expand for php, keep empty ARRAY
190       if($#$obj == -1 && $options->{childObj2string}) {
191         $result = $obj;
192       } else {
193      IterArray @$obj, sub {      IterArray @$obj, sub {
194        my $item;        my $item;
195        # if current item is a reference ...        # if current item is a reference ...
196        if (ref $_[0]) {        if (ref $_[0]) {
197          # ... expand structure recursively          $item = $_[0];
198          $item = expand($_[0], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
199            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
200            if ($item && $options->{childObj2string}) {
201              $item = twingle_reference($item);
202            } else {
203              # ... expand structure recursively
204              $item = expand($_[0], $options);
205            }
206          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
207          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
208    
# Line 147  sub expand { Line 211  sub expand {
211          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
212          $item = $_[0];          $item = $_[0];
213          # conversions/encodings          # conversions/encodings
214          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
215            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
216        }        }
217          
218          $item = '' if $options->{define} and not defined $item;
219        #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)
220        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
221    
222      }      }
223       }
224    
225    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    } elsif (ref $obj eq 'CODE') {
226    } else {      #print Dumper($obj);
227        #exit;
228    
229      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
230      } elsif (ref $obj) {
231      
232       # if we expand for php, keep empty HASH
233       my @tmp = keys %$obj;
234       if($#tmp == -1 && $options->{childObj2string}) {
235         $result = $obj;
236       } else {
237      IterHash %$obj, sub {      IterHash %$obj, sub {
238          my $key = $_[0];
239        my $item;        my $item;
240          
241          # conversions/encodings
242          $key = latin_to_utf8_scalar($key) if ($key && $options->{utf8});
243          $key = utf8_to_latin_scalar($key) if ($key && $options->{to_latin});
244    
245        # if current item is a reference ...        # if current item is a reference ...
246        if (ref $_[1]) {        if (ref $_[1]) {
247          # ... expand structure recursively          $item = $_[1];
248          $item = expand($_[1], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
249            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
250            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH") && !(ref $_[1] eq "Set::Object")) {
251              $item = twingle_reference($item);
252            } else {
253              # ... expand structure recursively
254              $item = expand($_[1], $options);
255            }
256          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
257          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
258                
# Line 172  sub expand { Line 261  sub expand {
261          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
262          $item = $_[1];          $item = $_[1];
263          # conversions/encodings          # conversions/encodings
264          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
265            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
266        }        }
267          
268          $item = '' if $options->{define} and not defined $item;
269        #$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)
270        $result->{$_[0]} = $item;               # use item in any case        $result->{$key} = $item;               # use item in any case
271      }      }
272       }
273    
274      } else {
275        #die ("not a reference!");
276        $result = $obj;
277    
278    }    }
279    
280    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
281      # 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
282      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
283    
284    # 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
285    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 195  sub expand { Line 292  sub expand {
292    
293    
294  my @indexstack;  my @indexstack;
295  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
296    my $obj = shift;    my $obj = shift;
297    my $data = shift;    my $data = shift;
298    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 239  sub var_traverse_mixin_update { Line 336  sub var_traverse_mixin_update {
336    #return $result;    #return $result;
337  }  }
338    
339  sub object2hash {  sub merge_to {
340    my $object = shift;    _hash2object(@_);
341    my $options = shift;    # TODO:
342    #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;  
343  }  }
344    
345    
346  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
347  sub hash2object {  sub _hash2object {
348    my $object = shift;    my $object = shift;
349    my $data = shift;    my $data = shift;
350    my $options = shift;    my $options = shift;
# Line 258  sub hash2object { Line 353  sub hash2object {
353        
354    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
355    # this method corrects this    # this method corrects this
356    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
357    
358    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
359    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
360    
361    # get fresh object from database    # get fresh object from database
362    # todo:    # todo:
# Line 270  sub hash2object { Line 365  sub hash2object {
365    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
366    
367    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
368    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
369    
370    # done in core mixin function?    # done in core mixin function?
371    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 293  sub hash2object { Line 388  sub hash2object {
388  #my @indexstack;  #my @indexstack;
389    
390  # 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
391  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
392    my $object = shift;    my $object = shift;
393    my $data = shift;    my $data = shift;
394    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 311  sub hash2object_traverse_mixin { Line 406  sub hash2object_traverse_mixin {
406    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
407    # 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!!!
408    # extend! check!    # extend! check!
409    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
410      #print attributes::reftype($object), "\n";
411      
412      # V1
413      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
414      # V2
415      my $reftype = attributes::reftype($object);
416      #print "reftype: '$reftype'", "\n";
417      if ($reftype eq 'HASH') {
418    
419  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
420                    
# Line 331  sub hash2object_traverse_mixin { Line 434  sub hash2object_traverse_mixin {
434        my $ref = ref $object->{$field};        my $ref = ref $object->{$field};
435  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
436        if ($ref) {        if ($ref) {
437          hash2object_traverse_mixin($object->{$field}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
438        } else {        } else {
439          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
440                    
441  #print Dumper($options);  #print Dumper($options);
442          my $field_target = $field;          my $field_target = $field;
# Line 376  sub hash2object_traverse_mixin { Line 479  sub hash2object_traverse_mixin {
479  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
480  #      if ($ref && $_) {  #      if ($ref && $_) {
481        if ($ref) {        if ($ref) {
482          hash2object_traverse_mixin($_, $data, 1, $options);          _hash2object_traverse_mixin($_, $data, 1, $options);
483        } else {        } else {
484          $object->[$i] = $_ if defined $_;          $object->[$i] = $_ if defined $_;
485        }        }
486        pop @indexstack;        pop @indexstack;
487        $i++;        $i++;
488      }      }
   }  
   
 }  
   
   
 # 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";  
       }  
     }  
489    
490    =pod
491      # object?
492    } else {    } else {
493      # use expr as simple scalar key (attributename)      print "reference: ", ref $object, "\n";
494      $value = $obj->{$expr};      print "reftype: ", $reftype, "\n";
495    }      die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
496              =cut
   return $value;  
497        
498  }    }
   
   
 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;  
499    
   # join parts with dereference operators together again and return built string  
   return (join('->', @parts_capsule), \@parts_pure);  
500  }  }
501    
502  # ACK's go to ...  
503  sub deep_copy {  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
504    # on the website:
505    # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
506    # Further distribution or use is not permitted.
507    # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
508    sub deep_copy1 {
509    my $this = shift;    my $this = shift;
510    if (not ref $this) {    if (not ref $this) {
511      $this;      $this;
512    } elsif (ref $this eq "ARRAY") {    } elsif (ref $this eq "ARRAY") {
513      [map deep_copy($_), @$this];      [map deep_copy1($_), @$this];
514    } elsif (ref $this eq "HASH") {    } elsif (ref $this eq "HASH") {
515      +{map { $_ => deep_copy($this->{$_}) } keys %$this};      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
516    } elsif (ref $this eq "CODE") {    } elsif (ref $this eq "CODE") {
517      $this;      $this;
518    #} else { die "deep_copy asks: what type is $this?" }    } else { die "deep_copy1 asks: what type is $this?" }
519    } else { print "deep_copy asks: what type is $this?", "\n"; }    #} else { print "deep_copy asks: what type is $this?", "\n"; }
520  }  }
521    
522    # ACK's go to Andrew Pitonyak
523    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
524    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
525    sub deep_copy {
526      Pitonyak::DeepCopy::deep_copy(@_);
527    }
528    
529    
530  1;  1;
531    __END__

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

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