/[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.9 by joko, Tue Feb 18 19:35:56 2003 UTC revision 1.15 by jonen, Thu Feb 27 14:39:48 2003 UTC
# Line 2  Line 2 
2  ##  $Id$  ##  $Id$
3  ## ---------------------------------------------------------------------------  ## ---------------------------------------------------------------------------
4  ##  $Log$  ##  $Log$
5    ##  Revision 1.15  2003/02/27 14:39:48  jonen
6    ##  + fixed bug at _hash2object()
7    ##
8    ##  Revision 1.14  2003/02/22 17:13:55  jonen
9    ##  + added function 'childObject2string()' to encode 'child'-references to option related string
10    ##  + use new option at 'expand()' for replacing 'childObject2string'
11    ##
12    ##  Revision 1.13  2003/02/21 01:48:50  joko
13    ##  renamed core function
14    ##
15    ##  Revision 1.12  2003/02/20 22:45:19  joko
16    ##  fix regarding new deep_copy
17    ##
18    ##  Revision 1.11  2003/02/20 21:13:54  joko
19    ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
20    ##
21    ##  Revision 1.10  2003/02/20 20:48:00  joko
22    ##  - refactored lots of code to Data::Code::Ref
23    ##  + alternative 'deep_copy' implementation
24    ##
25  ##  Revision 1.9  2003/02/18 19:35:56  joko  ##  Revision 1.9  2003/02/18 19:35:56  joko
26  ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too  ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
27  ##  ##
# Line 44  use warnings; Line 64  use warnings;
64  require Exporter;  require Exporter;
65  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
66  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
   &var_NumericalHashToArray  
   &var_mixin  
   &object2hash  
   &hash2object  
   &refexpr2perlref  
67    &expand    &expand
68    &deep_copy    &deep_copy
69    &merge    &merge_to
70  );  );
71  #  &var_deref  
 #  &getStructSlotByStringyAddress  
72    
73  use attributes;  use attributes;
74  use Data::Dumper;  use Data::Dumper;
 use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );  
   
 use Hash::Merge qw( merge );  
75  use Iterate;  use Iterate;
76    
77  sub var_NumericalHashToArray {  use Pitonyak::DeepCopy;
78    use Data::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar );
79    use Data::Code::Ref qw( ref_slot );
80    
81    sub numhash2list {
82    my $vref = shift;    my $vref = shift;
83    #my $context = shift;    #my $context = shift;
84    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 79  sub var_NumericalHashToArray { Line 94  sub var_NumericalHashToArray {
94                }                }
95                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
96              }              }
97              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
98            }            }
99  #      } else {  #      } else {
100  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 92  sub var_NumericalHashToArray { Line 107  sub var_NumericalHashToArray {
107  # FIXME: could this be refactored using expand?  # FIXME: could this be refactored using expand?
108  # btw: "expand": look at scripts@CPAN (System Administration):  # btw: "expand": look at scripts@CPAN (System Administration):
109  # there is a perl make with perl  # there is a perl make with perl
110  sub var_deref {  sub _var_deref_test {
111    my $obj = shift;    my $obj = shift;
112    my $options = shift;    my $options = shift;
113    my $result;    my $result;
# Line 131  sub var_deref { Line 146  sub var_deref {
146  }  }
147    
148    
149    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
150    # but still using the known latin locale stuff
151  sub expand {  sub expand {
152    
153    my $obj = shift;    my $obj = shift;
154    my $options = shift;    my $options = shift;
155    my $result;    my $result;
156    
157    if ((ref $obj) eq 'ARRAY') {    #print "ref: ", ref $obj, "\n";
158    
159      if (ref $obj eq 'ARRAY') {
160    
161      IterArray @$obj, sub {      IterArray @$obj, sub {
162        my $item;        my $item;
163        # if current item is a reference ...        # if current item is a reference ...
164        if (ref $_[0]) {        if (ref $_[0]) {
165          # ... expand structure recursively          $item = $_[0];
166          $item = expand($_[0], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
167            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
168            if ($item && $options->{childObj2string}) {
169              $item = childObj2string($item, $options->{childObj2string});
170            } else {
171              # ... expand structure recursively
172              $item = expand($_[0], $options);
173            }
174          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
175          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
176    
# Line 153  sub expand { Line 179  sub expand {
179          #$item = deep_copy($_[0]);          #$item = deep_copy($_[0]);
180          $item = $_[0];          $item = $_[0];
181          # conversions/encodings          # conversions/encodings
182          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
183            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
184        }        }
185        #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)
186        push(@{$result}, $item);                 # use item in any case        push(@{$result}, $item);                 # use item in any case
187    
188      }      }
189    
190      } elsif (ref $obj eq 'CODE') {
191        #print Dumper($obj);
192        #exit;
193    
194    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
195    } else {    } elsif (ref $obj) {
196    
197      IterHash %$obj, sub {      IterHash %$obj, sub {
198        my $item;        my $item;
199                
200        # if current item is a reference ...        # if current item is a reference ...
201        if (ref $_[1]) {        if (ref $_[1]) {
202          # ... expand structure recursively          $item = $_[1];
203          $item = expand($_[1], $options);          # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
204            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
205            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH")) {
206              $item = childObj2string($item, $options->{childObj2string});
207            } else {
208              # ... expand structure recursively
209              $item = expand($_[1], $options);
210            }
211          # destroy item via seperate callback method (a POST) if requested          # destroy item via seperate callback method (a POST) if requested
212          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};          #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
213                
# Line 178  sub expand { Line 216  sub expand {
216          #$item = deep_copy($_[1]);          #$item = deep_copy($_[1]);
217          $item = $_[1];          $item = $_[1];
218          # conversions/encodings          # conversions/encodings
219          $item = scalar2utf8($item) if ($item && $options->{utf8});          $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
220            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
221        }        }
222        #$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)
223        $result->{$_[0]} = $item;               # use item in any case        $result->{$_[0]} = $item;               # use item in any case
224      }      }
225    
226      } else {
227        #die ("not a reference!");
228        $result = $obj;
229    
230    }    }
231    
232    # convert all values to utf8 (inside complex struct)    # convert all values to utf8 (inside complex struct)
233      # 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
234      # var2utf8($result) if ($options->{utf8});      # latin_to_utf8($result) if ($options->{utf8});
235    
236    # 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
237    #undef $obj if $options->{destroy};    #undef $obj if $options->{destroy};
# Line 201  sub expand { Line 244  sub expand {
244    
245    
246  my @indexstack;  my @indexstack;
247  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
248    my $obj = shift;    my $obj = shift;
249    my $data = shift;    my $data = shift;
250    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 245  sub var_traverse_mixin_update { Line 288  sub var_traverse_mixin_update {
288    #return $result;    #return $result;
289  }  }
290    
291  sub object2hash {  sub merge_to {
292    my $object = shift;    _hash2object(@_);
293    my $options = shift;    # TODO:
294    #my $deref = var_deref($object);    # re-implement using CPAN's "Iterate".
   my $deref = expand($object, $options);  
   #var2utf8($deref) if ($options->{utf8});  
   return $deref;  
295  }  }
296    
297    
298  # todo: maybe do diff(s) here sometimes!?  # todo: maybe do diff(s) here sometimes!?
299  sub hash2object {  sub _hash2object {
300    my $object = shift;    my $object = shift;
301    my $data = shift;    my $data = shift;
302    my $options = shift;    my $options = shift;
# Line 264  sub hash2object { Line 305  sub hash2object {
305        
306    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
307    # this method corrects this    # this method corrects this
308    var_NumericalHashToArray($data) if ($options->{php});    numhash2list($data) if ($options->{php});
309    
310    # utf8-conversion/-encoding (essential for I18N)    # utf8-conversion/-encoding (essential for I18N)
311    var_utf2iso($data) if ($options->{utf8});    utf8_to_latin($data) if ($options->{utf8});
312    
313    # get fresh object from database    # get fresh object from database
314    # todo:    # todo:
# Line 276  sub hash2object { Line 317  sub hash2object {
317    #my $obj = $self->getObject($oid);    #my $obj = $self->getObject($oid);
318    
319    # mix changes into fresh object and save it back    # mix changes into fresh object and save it back
320    hash2object_traverse_mixin($object, $data, 0, $options);    _hash2object_traverse_mixin($object, $data, 0, $options);
321    
322    # done in core mixin function?    # done in core mixin function?
323    #$self->{storage}->update($obj);    #$self->{storage}->update($obj);
# Line 299  sub hash2object { Line 340  sub hash2object {
340  #my @indexstack;  #my @indexstack;
341    
342  # 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
343  sub hash2object_traverse_mixin {  sub _hash2object_traverse_mixin {
344    my $object = shift;    my $object = shift;
345    my $data = shift;    my $data = shift;
346    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 317  sub hash2object_traverse_mixin { Line 358  sub hash2object_traverse_mixin {
358    # what's exactly done here? hmmm.... it works ;)    # what's exactly done here? hmmm.... it works ;)
359    # 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!!!
360    # extend! check!    # extend! check!
361    if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {    
362      #print attributes::reftype($object), "\n";
363      
364      # V1
365      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
366      # V2
367      my $reftype = attributes::reftype($object);
368      #print "reftype: '$reftype'", "\n";
369      if ($reftype eq 'HASH') {
370    
371  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";  #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
372                    
# Line 337  sub hash2object_traverse_mixin { Line 386  sub hash2object_traverse_mixin {
386        my $ref = ref $object->{$field};        my $ref = ref $object->{$field};
387  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
388        if ($ref) {        if ($ref) {
389          hash2object_traverse_mixin($object->{$field}, $data, 1, $options);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
390        } else {        } else {
391          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
392                    
393  #print Dumper($options);  #print Dumper($options);
394          my $field_target = $field;          my $field_target = $field;
# Line 382  sub hash2object_traverse_mixin { Line 431  sub hash2object_traverse_mixin {
431  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
432  #      if ($ref && $_) {  #      if ($ref && $_) {
433        if ($ref) {        if ($ref) {
434          hash2object_traverse_mixin($_, $data, 1, $options);          _hash2object_traverse_mixin($_, $data, 1, $options);
435        } else {        } else {
436          $object->[$i] = $_ if defined $_;          $object->[$i] = $_ if defined $_;
437        }        }
438        pop @indexstack;        pop @indexstack;
439        $i++;        $i++;
440      }      }
   }  
   
 }  
   
   
 # 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 $values = shift;  
   my $delimiter = shift;  
   
   $delimiter ||= '->';  
   
   my $value;  
   # detect for callback (code-reference)  
   if (ref($expr) eq 'CODE') {  
     $value = &$expr($obj);  
   
   } elsif ($expr =~ m/$delimiter/) {  
     # use expr as complex object reference declaration (obj->subObj->subSubObj->0->attribute)  
     (my $objPerlRefString, my $parts) = refexpr2perlref_parts($expr, $delimiter);  
       
     # trace  
       #print "expr: $expr", "\n";  
       #print "objPerlRefString: $objPerlRefString", "\n";  
       
     my $evstr = '$obj' . '->' . $objPerlRefString;  
       
     # trace  
       #print "eval: $evstr", "\n";  
       
     $value = eval($evstr);  
     die ($@) if $@;  
       
     # if value isn't set, try to set it  
     my $callbackMap;  
     if ($values) {  
       #if (ref $values eq 'HASH') {  
       if (ref $values eq 'Data::Map') {  
         $callbackMap = $values->getAttributes();  
       } else {  
         # apply $values as single value to referenced slot  
         #print "APPLY!", "\n";  
         eval('$obj' . '->' . $objPerlRefString . ' = $values;');  
         die ($@) if $@;  
       }  
     }  
       
     # determine $values - if it's a hashref, use it as a "valueMap"  
     # "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";  
       }  
     }  
441    
442    =pod
443      # object?
444    } else {    } else {
445      # use expr as simple scalar key (attributename)      print "reference: ", ref $object, "\n";
446      $value = $obj->{$expr};      print "reftype: ", $reftype, "\n";
447    }      die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
448              =cut
   return $value;  
449        
450  }    }
   
   
 sub refexpr2perlref_parts {  
   my $expr = shift;  
   my $delimiter = shift;  
   
   $delimiter = quotemeta($delimiter);  
   
   # split expression by dereference operators first  
   my @parts_pure = split(/$delimiter/, $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;  
451    
   # join parts with dereference operators together again and return built string  
   return (join('->', @parts_capsule), \@parts_pure);  
452  }  }
453    
454  # ACK's go to ...  
455  sub deep_copy {  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
456    # on the website:
457    # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
458    # Further distribution or use is not permitted.
459    # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
460    sub deep_copy1 {
461    my $this = shift;    my $this = shift;
462    if (not ref $this) {    if (not ref $this) {
463      $this;      $this;
464    } elsif (ref $this eq "ARRAY") {    } elsif (ref $this eq "ARRAY") {
465      [map deep_copy($_), @$this];      [map deep_copy1($_), @$this];
466    } elsif (ref $this eq "HASH") {    } elsif (ref $this eq "HASH") {
467      +{map { $_ => deep_copy($this->{$_}) } keys %$this};      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
468    } elsif (ref $this eq "CODE") {    } elsif (ref $this eq "CODE") {
469      $this;      $this;
470    #} else { die "deep_copy asks: what type is $this?" }    } else { die "deep_copy1 asks: what type is $this?" }
471    } else { print "deep_copy asks: what type is $this?", "\n"; }    #} else { print "deep_copy asks: what type is $this?", "\n"; }
472  }  }
473    
474    # ACK's go to Andrew Pitonyak
475    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
476    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
477    sub deep_copy {
478      Pitonyak::DeepCopy::deep_copy(@_);
479    }
480    
481    
482    sub childObj2string {
483      my $obj = shift;
484      my $option = shift;
485      my $classname = ref $obj;
486      
487      if($option == 1) {
488        my $string = "o_" . $classname . "_" .$obj->{guid};
489        return $string;
490      }  
491    }
492    
493    
494  1;  1;
495    __END__

Legend:
Removed from v.1.9  
changed lines
  Added in v.1.15

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