/[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.19 by jonen, Fri Mar 28 03:11:25 2003 UTC
# Line 2  Line 2 
2  ##  $Id$  ##  $Id$
3  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
4  ##  $Log$  ##  $Log$
5    ##  Revision 1.19  2003/03/28 03:11:25  jonen
6    ##  + bugfix
7    ##
8    ##  Revision 1.18  2003/03/28 03:07:26  jonen
9    ##  + minor changes
10    ##
11    ##  Revision 1.17  2003/03/27 15:17:07  joko
12    ##  namespace fixes for Data::Mungle::*
13    ##
14    ##  Revision 1.16  2003/03/27 15:04:52  joko
15    ##  minor update: comment
16    ##
17    ##  Revision 1.15  2003/02/27 14:39:48  jonen
18    ##  + fixed bug at _hash2object()
19    ##
20    ##  Revision 1.14  2003/02/22 17:13:55  jonen
21    ##  + added function 'childObject2string()' to encode 'child'-references to option related string
22    ##  + use new option at 'expand()' for replacing 'childObject2string'
23    ##
24    ##  Revision 1.13  2003/02/21 01:48:50  joko
25    ##  renamed core function
26    ##
27    ##  Revision 1.12  2003/02/20 22:45:19  joko
28    ##  fix regarding new deep_copy
29    ##
30    ##  Revision 1.11  2003/02/20 21:13:54  joko
31    ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
32    ##
33    ##  Revision 1.10  2003/02/20 20:48:00  joko
34    ##  - refactored lots of code to Data::Code::Ref
35    ##  + alternative 'deep_copy' implementation
36    ##
37    ##  Revision 1.9  2003/02/18 19:35:56  joko
38    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
39    ##
40  ##  Revision 1.8  2003/02/09 05:10:56  joko  ##  Revision 1.8  2003/02/09 05:10:56  joko
41  ##  + minor update  ##  + minor update
42  ##  ##
# Line 33  Line 68 
68  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
69    
70    
71  package Data::Transform::Deep;  package Data::Mungle::Transform::Deep;
72    
73  use strict;  use strict;
74  use warnings;  use warnings;
# Line 41  use warnings; Line 76  use warnings;
76  require Exporter;  require Exporter;
77  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
78  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
79    &expand    &expand
80    &deep_copy    &deep_copy
81    &merge    &merge_to
82  );  );
83  #  &var_deref  
 #  &getStructSlotByStringyAddress  
84    
85  use attributes;  use attributes;
86  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
   
 use Hash::Merge qw( merge );  
87  use Iterate;  use Iterate;
88    
89  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
90    use Data::Mungle::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar );
91    use Data::Mungle::Code::Ref qw( ref_slot );
92    
93    sub numhash2list {
94    my $vref = shift;    my $vref = shift;
95    #my $context = shift;    #my $context = shift;
96    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 76  sub var_NumericalHashToArray { Line 106  sub var_NumericalHashToArray {
106                }                }
107                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
108              }              }
109              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
110            }            }
111  #      } else {  #      } else {
112  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 86  sub var_NumericalHashToArray { Line 116  sub var_NumericalHashToArray {
116  }  }
117    
118    
119  sub var_deref {  # FIXME: could this be refactored using expand?
120    # btw: "expand": look at scripts@CPAN (System Administration):
121    # there is a perl make with perl
122    sub _var_deref_test {
123    my $obj = shift;    my $obj = shift;
124    my $options = shift;    my $options = shift;
125    my $result;    my $result;
# Line 125  sub var_deref { Line 158  sub var_deref {
158  }  }
159    
160    
161    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
162    # but still using the known latin locale stuff
163  sub expand {  sub expand {
164    
165    my $obj = shift;    my $obj = shift;
166    my $options = shift;    my $options = shift;
167    my $result;    my $result;
168    
169    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
170    
171      if (ref $obj eq 'ARRAY') {
172    
173      IterArray @$obj, sub {      IterArray @$obj, sub {
174        my $item;        my $item;
175        # if current item is a reference ...        # if current item is a reference ...
176        if (ref $_[0]) {        if (ref $_[0]) {
177          # ... expand structure recursively          $item = $_[0];
178          $item = expand($_[0], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
179            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
180            if ($item && $options->{childObj2string}) {
181              $item = childObj2string($item, $options->{childObj2string});
182            } else {
183              # ... expand structure recursively
184              $item = expand($_[0], $options);
185            }
186          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
187          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
188    
# Line 147  sub expand { Line 191  sub expand {
191          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
192          $item = $_[0];          $item = $_[0];
193          # conversions/encodings          # conversions/encodings
194          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
195            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
196        }        }
197        #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)
198        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
199    
200      }      }
201    
202      } elsif (ref $obj eq 'CODE') {
203        #print Dumper($obj);
204        #exit;
205    
206    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
207    } else {    } elsif (ref $obj) {
208    
209      IterHash %$obj, sub {      IterHash %$obj, sub {
210        my $item;        my $item;
211                
212        # if current item is a reference ...        # if current item is a reference ...
213        if (ref $_[1]) {        if (ref $_[1]) {
214          # ... expand structure recursively          $item = $_[1];
215          $item = expand($_[1], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
216            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
217            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH")) {
218              $item = childObj2string($item, $options->{childObj2string});
219            } else {
220              # ... expand structure recursively
221              $item = expand($_[1], $options);
222            }
223          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
224          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
225                
# Line 172  sub expand { Line 228  sub expand {
228          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
229          $item = $_[1];          $item = $_[1];
230          # conversions/encodings          # conversions/encodings
231          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
232            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
233        }        }
234        #$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)
235        $result->{$_[0]} = $item;               # use item in any case        $result->{$_[0]} = $item;               # use item in any case
236      }      }
237    
238      } else {
239        #die ("not a reference!");
240        $result = $obj;
241    
242    }    }
243    
244    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
245      # 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
246      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
247    
248    # 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
249    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 195  sub expand { Line 256  sub expand {
256    
257    
258  my @indexstack;  my @indexstack;
259  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
260    my $obj = shift;    my $obj = shift;
261    my $data = shift;    my $data = shift;
262    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 239  sub var_traverse_mixin_update { Line 300  sub var_traverse_mixin_update {
300    #return $result;    #return $result;
301  }  }
302    
303  sub object2hash {  sub merge_to {
304    my $object = shift;    _hash2object(@_);
305    my $options = shift;    # TODO:
306    #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;  
307  }  }
308    
309    
310  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
311  sub hash2object {  sub _hash2object {
312    my $object = shift;    my $object = shift;
313    my $data = shift;    my $data = shift;
314    my $options = shift;    my $options = shift;
# Line 258  sub hash2object { Line 317  sub hash2object {
317        
318    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
319    # this method corrects this    # this method corrects this
320    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
321    
322    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
323    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
324    
325    # get fresh object from database    # get fresh object from database
326    # todo:    # todo:
# Line 270  sub hash2object { Line 329  sub hash2object {
329    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
330    
331    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
332    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
333    
334    # done in core mixin function?    # done in core mixin function?
335    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 293  sub hash2object { Line 352  sub hash2object {
352  #my @indexstack;  #my @indexstack;
353    
354  # 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
355  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
356    my $object = shift;    my $object = shift;
357    my $data = shift;    my $data = shift;
358    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 311  sub hash2object_traverse_mixin { Line 370  sub hash2object_traverse_mixin {
370    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
371    # 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!!!
372    # extend! check!    # extend! check!
373    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
374      #print attributes::reftype($object), "\n";
375      
376      # V1
377      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
378      # V2
379      my $reftype = attributes::reftype($object);
380      #print "reftype: '$reftype'", "\n";
381      if ($reftype eq 'HASH') {
382    
383  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
384                    
# Line 331  sub hash2object_traverse_mixin { Line 398  sub hash2object_traverse_mixin {
398        my $ref = ref $object->{$field};        my $ref = ref $object->{$field};
399  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
400        if ($ref) {        if ($ref) {
401          hash2object_traverse_mixin($object->{$field}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
402        } else {        } else {
403          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
404                    
405  #print Dumper($options);  #print Dumper($options);
406          my $field_target = $field;          my $field_target = $field;
# Line 376  sub hash2object_traverse_mixin { Line 443  sub hash2object_traverse_mixin {
443  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
444  #      if ($ref && $_) {  #      if ($ref && $_) {
445        if ($ref) {        if ($ref) {
446          hash2object_traverse_mixin($_, $data, 1, $options);          _hash2object_traverse_mixin($_, $data, 1, $options);
447        } else {        } else {
448          $object->[$i] = $_ if defined $_;          $object->[$i] = $_ if defined $_;
449        }        }
450        pop @indexstack;        pop @indexstack;
451        $i++;        $i++;
452      }      }
   }  
   
 }  
   
   
 # 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";  
       }  
     }  
453    
454    =pod
455      # object?
456    } else {    } else {
457      # use expr as simple scalar key (attributename)      print "reference: ", ref $object, "\n";
458      $value = $obj->{$expr};      print "reftype: ", $reftype, "\n";
459    }      die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
460              =cut
   return $value;  
461        
462  }    }
   
   
 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;  
463    
   # join parts with dereference operators together again and return built string  
   return (join('->', @parts_capsule), \@parts_pure);  
464  }  }
465    
466  # ACK's go to ...  
467  sub deep_copy {  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
468    # on the website:
469    # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
470    # Further distribution or use is not permitted.
471    # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
472    sub deep_copy1 {
473    my $this = shift;    my $this = shift;
474    if (not ref $this) {    if (not ref $this) {
475      $this;      $this;
476    } elsif (ref $this eq "ARRAY") {    } elsif (ref $this eq "ARRAY") {
477      [map deep_copy($_), @$this];      [map deep_copy1($_), @$this];
478    } elsif (ref $this eq "HASH") {    } elsif (ref $this eq "HASH") {
479      +{map { $_ => deep_copy($this->{$_}) } keys %$this};      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
480    } elsif (ref $this eq "CODE") {    } elsif (ref $this eq "CODE") {
481      $this;      $this;
482    #} else { die "deep_copy asks: what type is $this?" }    } else { die "deep_copy1 asks: what type is $this?" }
483    } else { print "deep_copy asks: what type is $this?", "\n"; }    #} else { print "deep_copy asks: what type is $this?", "\n"; }
484  }  }
485    
486    # ACK's go to Andrew Pitonyak
487    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
488    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
489    sub deep_copy {
490      Pitonyak::DeepCopy::deep_copy(@_);
491    }
492    
493    
494    sub childObj2string {
495      my $obj = shift;
496      my $option = shift;
497      my $classname = ref $obj;
498      my $string;
499      
500      if($option == 1) {
501        $string = "o_" . $obj->{guid} . "_" . $classname;
502      }  
503      return $string;
504    }
505    
506    
507  1;  1;
508    __END__

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

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