/[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.6 by jonen, Mon Dec 23 11:27:53 2002 UTC revision 1.17 by joko, Thu Mar 27 15:17:07 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.17  2003/03/27 15:17:07  joko
6  #  Revision 1.6  2002/12/23 11:27:53  jonen  ##  namespace fixes for Data::Mungle::*
7  #  + changed behavior WATCH!  ##
8  #  ##  Revision 1.16  2003/03/27 15:04:52  joko
9  #  Revision 1.5  2002/12/16 19:57:54  joko  ##  minor update: comment
10  #  + option 'init'  ##
11  #  ##  Revision 1.15  2003/02/27 14:39:48  jonen
12  #  Revision 1.4  2002/12/05 13:56:49  joko  ##  + fixed bug at _hash2object()
13  #  - var_deref  ##
14  #  + expand - more sophisticated dereferencing with callbacks using Iterate  ##  Revision 1.14  2003/02/22 17:13:55  jonen
15  #  ##  + added function 'childObject2string()' to encode 'child'-references to option related string
16  #  Revision 1.3  2002/12/03 05:34:55  joko  ##  + use new option at 'expand()' for replacing 'childObject2string'
17  #  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode  ##
18  #  ##  Revision 1.13  2003/02/21 01:48:50  joko
19  #  Revision 1.2  2002/12/01 04:44:07  joko  ##  renamed core function
20  #  + code from Data::Transform::OO  ##
21  #  ##  Revision 1.12  2003/02/20 22:45:19  joko
22  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  fix regarding new deep_copy
23  #  + initial check-in  ##
24  #  ##  Revision 1.11  2003/02/20 21:13:54  joko
25  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
26  #  + new  ##
27  #  ##  Revision 1.10  2003/02/20 20:48:00  joko
28  ##############################################  ##  - refactored lots of code to Data::Code::Ref
29    ##  + alternative 'deep_copy' implementation
30    ##
31    ##  Revision 1.9  2003/02/18 19:35:56  joko
32    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
33    ##
34    ##  Revision 1.8  2003/02/09 05:10:56  joko
35    ##  + minor update
36    ##
37    ##  Revision 1.7  2003/01/19 03:26:59  joko
38    ##  + added 'sub deep_copy'  -  refactored from libp
39    ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
40    ##
41    ##  Revision 1.6  2002/12/23 11:27:53  jonen
42    ##  + changed behavior WATCH!
43    ##
44    ##  Revision 1.5  2002/12/16 19:57:54  joko
45    ##  + option 'init'
46    ##
47    ##  Revision 1.4  2002/12/05 13:56:49  joko
48    ##  - var_deref
49    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
50    ##
51    ##  Revision 1.3  2002/12/03 05:34:55  joko
52    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
53    ##
54    ##  Revision 1.2  2002/12/01 04:44:07  joko
55    ##  + code from Data::Transform::OO
56    ##
57    ##  Revision 1.1  2002/11/29 04:49:20  joko
58    ##  + initial check-in
59    ##
60    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
61    ##  + new
62    ## ---------------------------------------------------------------------------
63    
64    
65  package Data::Transform::Deep;  package Data::Mungle::Transform::Deep;
66    
67  use strict;  use strict;
68  use warnings;  use warnings;
# Line 36  use warnings; Line 70  use warnings;
70  require Exporter;  require Exporter;
71  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
72  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
73    &expand    &expand
74      &deep_copy
75      &merge_to
76  );  );
77  #  &var_deref  
 #  &getStructSlotByStringyAddress  
78    
79  use attributes;  use attributes;
80  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
 use libp qw( deep_copy );  
81  use Iterate;  use Iterate;
82    
83  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
84    use Data::Mungle::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar );
85    use Data::Mungle::Code::Ref qw( ref_slot );
86    
87    sub numhash2list {
88    my $vref = shift;    my $vref = shift;
89    #my $context = shift;    #my $context = shift;
90    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 68  sub var_NumericalHashToArray { Line 100  sub var_NumericalHashToArray {
100                }                }
101                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
102              }              }
103              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
104            }            }
105  #      } else {  #      } else {
106  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 78  sub var_NumericalHashToArray { Line 110  sub var_NumericalHashToArray {
110  }  }
111    
112    
113  sub var_deref {  # FIXME: could this be refactored using expand?
114    # btw: "expand": look at scripts@CPAN (System Administration):
115    # there is a perl make with perl
116    sub _var_deref_test {
117    my $obj = shift;    my $obj = shift;
118    my $options = shift;    my $options = shift;
119    my $result;    my $result;
# Line 117  sub var_deref { Line 152  sub var_deref {
152  }  }
153    
154    
155    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
156    # but still using the known latin locale stuff
157  sub expand {  sub expand {
158    
159    my $obj = shift;    my $obj = shift;
160    my $options = shift;    my $options = shift;
161    my $result;    my $result;
162    
163    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
164    
165      if (ref $obj eq 'ARRAY') {
166    
167      IterArray @$obj, sub {      IterArray @$obj, sub {
168        my $item;        my $item;
169        # if current item is a reference ...        # if current item is a reference ...
170        if (ref $_[0]) {        if (ref $_[0]) {
171          # ... expand structure recursively          $item = $_[0];
172          $item = expand($_[0], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
173            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
174            if ($item && $options->{childObj2string}) {
175              $item = childObj2string($item, $options->{childObj2string});
176            } else {
177              # ... expand structure recursively
178              $item = expand($_[0], $options);
179            }
180          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
181          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
182    
# Line 139  sub expand { Line 185  sub expand {
185          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
186          $item = $_[0];          $item = $_[0];
187          # conversions/encodings          # conversions/encodings
188          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
189            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
190        }        }
191        #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)
192        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
193    
194      }      }
195    
196      } elsif (ref $obj eq 'CODE') {
197        #print Dumper($obj);
198        #exit;
199    
200    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
201    } else {    } elsif (ref $obj) {
202    
203      IterHash %$obj, sub {      IterHash %$obj, sub {
204        my $item;        my $item;
205                
206        # if current item is a reference ...        # if current item is a reference ...
207        if (ref $_[1]) {        if (ref $_[1]) {
208          # ... expand structure recursively          $item = $_[1];
209          $item = expand($_[1], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
210            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
211            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH")) {
212              $item = childObj2string($item, $options->{childObj2string});
213            } else {
214              # ... expand structure recursively
215              $item = expand($_[1], $options);
216            }
217          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
218          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
219                
# Line 164  sub expand { Line 222  sub expand {
222          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
223          $item = $_[1];          $item = $_[1];
224          # conversions/encodings          # conversions/encodings
225          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
226            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
227        }        }
228        #$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)
229        $result->{$_[0]} = $item;               # use item in any case        $result->{$_[0]} = $item;               # use item in any case
230      }      }
231    
232      } else {
233        #die ("not a reference!");
234        $result = $obj;
235    
236    }    }
237    
238    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
239      # 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
240      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
241    
242    # 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
243    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 187  sub expand { Line 250  sub expand {
250    
251    
252  my @indexstack;  my @indexstack;
253  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
254    my $obj = shift;    my $obj = shift;
255    my $data = shift;    my $data = shift;
256    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 231  sub var_traverse_mixin_update { Line 294  sub var_traverse_mixin_update {
294    #return $result;    #return $result;
295  }  }
296    
297  sub object2hash {  sub merge_to {
298    my $object = shift;    _hash2object(@_);
299    my $options = shift;    # TODO:
300    #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;  
301  }  }
302    
303    
304  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
305  sub hash2object {  sub _hash2object {
306    my $object = shift;    my $object = shift;
307    my $data = shift;    my $data = shift;
308    my $options = shift;    my $options = shift;
# Line 250  sub hash2object { Line 311  sub hash2object {
311        
312    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
313    # this method corrects this    # this method corrects this
314    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
315    
316    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
317    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
318    
319    # get fresh object from database    # get fresh object from database
320    # todo:    # todo:
# Line 262  sub hash2object { Line 323  sub hash2object {
323    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
324    
325    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
326    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
327    
328    # done in core mixin function?    # done in core mixin function?
329    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 285  sub hash2object { Line 346  sub hash2object {
346  #my @indexstack;  #my @indexstack;
347    
348  # 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
349  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
350    my $object = shift;    my $object = shift;
351    my $data = shift;    my $data = shift;
352    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 303  sub hash2object_traverse_mixin { Line 364  sub hash2object_traverse_mixin {
364    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
365    # 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!!!
366    # extend! check!    # extend! check!
367    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
368      #print attributes::reftype($object), "\n";
369      
370      # V1
371      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
372      # V2
373      my $reftype = attributes::reftype($object);
374      #print "reftype: '$reftype'", "\n";
375      if ($reftype eq 'HASH') {
376    
377  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
378                    
# Line 316  sub hash2object_traverse_mixin { Line 385  sub hash2object_traverse_mixin {
385  #    @fields = keys %{$data} if $options->{mixin};  #    @fields = keys %{$data} if $options->{mixin};
386            
387      foreach (@fields) {      foreach (@fields) {
388        push @indexstack, $_;        my $field = $_;
389          push @indexstack, $field;
390                            
391        # determine type of object        # determine type of object
392        my $ref = ref $object->{$_};        my $ref = ref $object->{$field};
393  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
394        if ($ref) {        if ($ref) {
395          hash2object_traverse_mixin($object->{$_}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
396        } else {        } else {
397          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
398          $object->{$_} = $val if defined $val;          
399    #print Dumper($options);
400            my $field_target = $field;
401            if (my $pattern = $options->{pattern_strip_key}) {
402              print "pattern: $pattern", "\n";
403              $field_target =~ s/$pattern//;
404              print "field: $field_target", "\n";
405            }
406    
407            $object->{$field_target} = $val if defined $val;
408        }        }
409        pop @indexstack;        pop @indexstack;
410      }      }
# Line 358  sub hash2object_traverse_mixin { Line 437  sub hash2object_traverse_mixin {
437  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
438  #      if ($ref && $_) {  #      if ($ref && $_) {
439        if ($ref) {        if ($ref) {
440          hash2object_traverse_mixin($_, $data, 1, $options);          _hash2object_traverse_mixin($_, $data, 1, $options);
441        } else {        } else {
442          $object->[$i] = $_ if defined $_;          $object->[$i] = $_ if defined $_;
443        }        }
444        pop @indexstack;        pop @indexstack;
445        $i++;        $i++;
446      }      }
447    
448    =pod
449      # object?
450      } else {
451        print "reference: ", ref $object, "\n";
452        print "reftype: ", $reftype, "\n";
453        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
454    =cut
455      
456    }    }
457    
458  }  }
459    
460    
461  # this function seems to do similar stuff like these below (refexpr2perlref & co.)  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
462  # TODO: maybe this mechanism can be replaced completely through some nice module from CPAN .... ?   ;-)  # on the website:
463  sub getStructSlotByStringyAddress {  # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
464    my $var = shift;  # Further distribution or use is not permitted.
465    my $indexstack_ref = shift;  # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
466    my @indexstack = @{$indexstack_ref};  sub deep_copy1 {
467    my $joiner = '->';    my $this = shift;
468    my @evlist;    if (not ref $this) {
469    foreach (@indexstack) {      $this;
470      my $elem;    } elsif (ref $this eq "ARRAY") {
471      if ($_ =~ m/\d+/) { $elem = "[$_]"; }      [map deep_copy1($_), @$this];
472      if ($_ =~ m/\D+/) { $elem = "{$_}"; }    } elsif (ref $this eq "HASH") {
473      push @evlist, $elem;      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
474    }    } elsif (ref $this eq "CODE") {
475    my $evstring = join($joiner, @evlist);      $this;
476    $evstring = 'return $var->' . $evstring . ';';    } else { die "deep_copy1 asks: what type is $this?" }
477    #print "ev: $evstring\n";    #} else { print "deep_copy asks: what type is $this?", "\n"; }
   return eval($evstring);  
478  }  }
479    
480    # ACK's go to Andrew Pitonyak
481    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
482    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
483    sub deep_copy {
484      Pitonyak::DeepCopy::deep_copy(@_);
485    }
486    
 sub refexpr2perlref {  
487    
488    sub childObj2string {
489    my $obj = shift;    my $obj = shift;
490    my $expr = shift;    my $option = shift;
491    my $callbackMap = shift;    my $classname = ref $obj;
   
   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;  
492        
493      if($option == 1) {
494        my $string = "o_" . $classname . "_" .$obj->{guid};
495        return $string;
496      }  
497  }  }
498    
499    
 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);  
 }  
   
500  1;  1;
501    __END__

Legend:
Removed from v.1.6  
changed lines
  Added in v.1.17

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