/[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.2 by joko, Sun Dec 1 04:44:07 2002 UTC revision 1.18 by jonen, Fri Mar 28 03:07:26 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.18  2003/03/28 03:07:26  jonen
6  #  Revision 1.2  2002/12/01 04:44:07  joko  ##  + minor changes
7  #  + code from Data::Transform::OO  ##
8  #  ##  Revision 1.17  2003/03/27 15:17:07  joko
9  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  namespace fixes for Data::Mungle::*
10  #  + initial check-in  ##
11  #  ##  Revision 1.16  2003/03/27 15:04:52  joko
12  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  minor update: comment
13  #  + new  ##
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
38    ##  + minor update
39    ##
40    ##  Revision 1.7  2003/01/19 03:26:59  joko
41    ##  + added 'sub deep_copy'  -  refactored from libp
42    ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
43    ##
44    ##  Revision 1.6  2002/12/23 11:27:53  jonen
45    ##  + changed behavior WATCH!
46    ##
47    ##  Revision 1.5  2002/12/16 19:57:54  joko
48    ##  + option 'init'
49    ##
50    ##  Revision 1.4  2002/12/05 13:56:49  joko
51    ##  - var_deref
52    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
53    ##
54    ##  Revision 1.3  2002/12/03 05:34:55  joko
55    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
56    ##
57    ##  Revision 1.2  2002/12/01 04:44:07  joko
58    ##  + code from Data::Transform::OO
59    ##
60    ##  Revision 1.1  2002/11/29 04:49:20  joko
61    ##  + initial check-in
62    ##
63    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
64    ##  + new
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 23  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(
76    &var_NumericalHashToArray    &expand
77    &var_deref    &deep_copy
78    &var_mixin    &merge_to
   &object2hash  
   &hash2object  
   &refexpr2perlref  
79  );  );
80  #  &getStructSlotByStringyAddress  
81    
82  use attributes;  use attributes;
83  use Data::Dumper;  use Data::Dumper;
84    use Iterate;
85    
86    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 var_NumericalHashToArray {  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 52  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 62  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;
122    my $result;    my $result;
123    if ((ref $obj) eq 'ARRAY') {    if ((ref $obj) eq 'ARRAY') {
124      foreach (@{$obj}) {      foreach (@{$obj}) {
125        my $ref = ref $_;        my $ref = ref $_;
126        if ($ref) {        if ($ref) {
127          push(@{$result}, var_deref($_));          push(@{$result}, var_deref($_, $options));
128            #undef $_;
129        } else {        } else {
130          push(@{$result}, $_);          #push(@{$result}, $_);
131            push(@{$result}, deep_copy($_));
132        }        }
133          #undef $_ if $options->{destroy};
134          #$options->{destroy}->($_) if $options->{destroy};
135      }      }
136    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???    # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
137    } else {    } else {
# Line 80  sub var_deref { Line 139  sub var_deref {
139        my $key = $_;        my $key = $_;
140        my $ref = ref $obj->{$_};        my $ref = ref $obj->{$_};
141        if ($ref) {        if ($ref) {
142          $result->{$_} = var_deref($obj->{$_});          $result->{$_} = var_deref($obj->{$_}, $options);
143            #undef $obj->{$_};
144        } else {        } else {
145          $result->{$_} = $obj->{$_};          #$result->{$_} = $obj->{$_};
146            $result->{$_} = deep_copy($obj->{$_});
147        }        }
148          #undef $obj->{$_} if $options->{destroy};
149          #$options->{destroy}->($obj->{$_}) if $options->{destroy};
150      }      }
151    }    }
152      #undef $obj if $options->{destroy};
153      $options->{cb_destroy}->($obj) if $options->{cb_destroy};
154    return $result;    return $result;
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 {
161    
162      my $obj = shift;
163      my $options = shift;
164      my $result;
165    
166      #print "ref: ", ref $obj, "\n";
167    
168      if (ref $obj eq 'ARRAY') {
169    
170        IterArray @$obj, sub {
171          my $item;
172          # if current item is a reference ...
173          if (ref $_[0]) {
174            $item = $_[0];
175            # 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
184            #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
185    
186          # ... assume plain scalar
187          } else {
188            #$item = deep_copy($_[0]);
189            $item = $_[0];
190            # conversions/encodings
191            $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)
195          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'; }"  ???
204      } elsif (ref $obj) {
205    
206        IterHash %$obj, sub {
207          my $item;
208          
209          # if current item is a reference ...
210          if (ref $_[1]) {
211            $item = $_[1];
212            # 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
221            #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
222          
223          # ... assume plain scalar
224          } else {
225            #$item = deep_copy($_[1]);
226            $item = $_[1];
227            # conversions/encodings
228            $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)
232          $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)
242        # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
243        # latin_to_utf8($result) if ($options->{utf8});
244    
245      # destroy persistent object from memory to be sure to get a fresh one next time
246      #undef $obj if $options->{destroy};
247      #$options->{cb_destroy}->($obj) if $options->{cb_destroy};
248      #$options->{cb}->{destroy}->($obj) if $options->{destroy};
249      
250      return $result;
251    }
252    
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 137  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.
   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;
312    
313      #print "hash2object", "\n";
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 165  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);    _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 188  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;
356      my $options = shift;
357    
358    # clear our key - stack if we are called from user-code (non-recursively)    # clear our key - stack if we are called from user-code (non-recursively)
359    @indexstack = () if (!$bool_recursion);    @indexstack = () if (!$bool_recursion);
# Line 205  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                    
382        my @fields;
383      # loop through fields of object (Tangram-object)      # loop through fields of object (Tangram-object)
384      foreach (keys %{$object}) {      @fields = keys %{$object};
385        push @indexstack, $_;  
386        # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
387        @fields = keys %{$data} if $options->{init};
388    #    @fields = keys %{$data} if $options->{mixin};
389        
390        foreach (@fields) {
391          my $field = $_;
392          push @indexstack, $field;
393                            
394        # determine type of object        # determine type of object
395        my $ref = ref $object->{$_};        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->{$_}, $data, 1);          _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
399        } else {        } else {
400          my $val = getStructSlotByStringyAddress($data, \@indexstack);          my $val = ref_slot($data, \@indexstack);
401          $object->{$_} = $val;                  
402    #print Dumper($options);
403            my $field_target = $field;
404            if (my $pattern = $options->{pattern_strip_key}) {
405              print "pattern: $pattern", "\n";
406              $field_target =~ s/$pattern//;
407              print "field: $field_target", "\n";
408            }
409    
410            $object->{$field_target} = $val if defined $val;
411        }        }
412        pop @indexstack;        pop @indexstack;
413      }      }
# Line 251  sub hash2object_traverse_mixin { Line 438  sub hash2object_traverse_mixin {
438        push @indexstack, $i;        push @indexstack, $i;
439        my $ref = ref $_;        my $ref = ref $_;
440  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";  #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
441        if ($ref && $_) {  #      if ($ref && $_) {
442          hash2object_traverse_mixin($_, $data, 1);        if ($ref) {
443            _hash2object_traverse_mixin($_, $data, 1, $options);
444        } else {        } else {
445          $object->[$i] = $_;          $object->[$i] = $_ if defined $_;
446        }        }
447        pop @indexstack;        pop @indexstack;
448        $i++;        $i++;
449      }      }
450    
451    =pod
452      # object?
453      } else {
454        print "reference: ", ref $object, "\n";
455        print "reftype: ", $reftype, "\n";
456        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
457    =cut
458      
459    }    }
460    
461  }  }
462    
463    
464  # this function seems to do similar stuff like these below (refexpr2perlref & co.)  # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
465  sub getStructSlotByStringyAddress {  # on the website:
466    my $var = shift;  # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
467    my $indexstack_ref = shift;  # Further distribution or use is not permitted.
468    my @indexstack = @{$indexstack_ref};  # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
469    my $joiner = '->';  sub deep_copy1 {
470    my @evlist;    my $this = shift;
471    foreach (@indexstack) {    if (not ref $this) {
472      my $elem;      $this;
473      if ($_ =~ m/\d+/) { $elem = "[$_]"; }    } elsif (ref $this eq "ARRAY") {
474      if ($_ =~ m/\D+/) { $elem = "{$_}"; }      [map deep_copy1($_), @$this];
475      push @evlist, $elem;    } elsif (ref $this eq "HASH") {
476    }      +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
477    my $evstring = join($joiner, @evlist);    } elsif (ref $this eq "CODE") {
478    $evstring = 'return $var->' . $evstring . ';';      $this;
479    #print "ev: $evstring\n";    } else { die "deep_copy1 asks: what type is $this?" }
480    return eval($evstring);    #} 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    
 sub refexpr2perlref {  
490    
491    sub childObj2string {
492    my $obj = shift;    my $obj = shift;
493    my $expr = shift;    my $option = shift;
494    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;  
495        
496      if($option == 1) {
497        my $string = "o_" . $obj->{guid} . "_" . $classname;
498      }  
499      return $string;
500  }  }
501    
502    
 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);  
 }  
   
503  1;  1;
504    __END__

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

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