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

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

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