/[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.1 by joko, Fri Nov 29 04:49:20 2002 UTC revision 1.22 by jonen, Sat May 10 17:09:18 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.22  2003/05/10 17:09:18  jonen
6  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  + added keep of empty arrays/hashes if 'expand' for php
7  #  + initial check-in  ##
8  #  ##  Revision 1.21  2003/04/09 07:21:56  joko
9  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  childObj2string now inside Encode.pm, renamed to 'twingle_reference'
10  #  + new  ##
11  #  ##  Revision 1.20  2003/04/04 17:31:23  joko
12  ##############################################  ##  minor update to 'childObj2string'
13    ##
14    ##  Revision 1.19  2003/03/28 03:11:25  jonen
15    ##  + bugfix
16    ##
17    ##  Revision 1.18  2003/03/28 03:07:26  jonen
18    ##  + minor changes
19    ##
20    ##  Revision 1.17  2003/03/27 15:17:07  joko
21    ##  namespace fixes for Data::Mungle::*
22    ##
23    ##  Revision 1.16  2003/03/27 15:04:52  joko
24    ##  minor update: comment
25    ##
26    ##  Revision 1.15  2003/02/27 14:39:48  jonen
27    ##  + fixed bug at _hash2object()
28    ##
29    ##  Revision 1.14  2003/02/22 17:13:55  jonen
30    ##  + added function 'childObject2string()' to encode 'child'-references to option related string
31    ##  + use new option at 'expand()' for replacing 'childObject2string'
32    ##
33    ##  Revision 1.13  2003/02/21 01:48:50  joko
34    ##  renamed core function
35    ##
36    ##  Revision 1.12  2003/02/20 22:45:19  joko
37    ##  fix regarding new deep_copy
38    ##
39    ##  Revision 1.11  2003/02/20 21:13:54  joko
40    ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
41    ##
42    ##  Revision 1.10  2003/02/20 20:48:00  joko
43    ##  - refactored lots of code to Data::Code::Ref
44    ##  + alternative 'deep_copy' implementation
45    ##
46    ##  Revision 1.9  2003/02/18 19:35:56  joko
47    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
48    ##
49    ##  Revision 1.8  2003/02/09 05:10:56  joko
50    ##  + minor update
51    ##
52    ##  Revision 1.7  2003/01/19 03:26:59  joko
53    ##  + added 'sub deep_copy'  -  refactored from libp
54    ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
55    ##
56    ##  Revision 1.6  2002/12/23 11:27:53  jonen
57    ##  + changed behavior WATCH!
58    ##
59    ##  Revision 1.5  2002/12/16 19:57:54  joko
60    ##  + option 'init'
61    ##
62    ##  Revision 1.4  2002/12/05 13:56:49  joko
63    ##  - var_deref
64    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
65    ##
66    ##  Revision 1.3  2002/12/03 05:34:55  joko
67    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
68    ##
69    ##  Revision 1.2  2002/12/01 04:44:07  joko
70    ##  + code from Data::Transform::OO
71    ##
72    ##  Revision 1.1  2002/11/29 04:49:20  joko
73    ##  + initial check-in
74    ##
75    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
76    ##  + new
77    ## ---------------------------------------------------------------------------
78    
79    
80  package Data::Transform::Deep;  package Data::Mungle::Transform::Deep;
81    
82  use strict;  use strict;
83  use warnings;  use warnings;
84    
85  require Exporter;  require Exporter;
86  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
87  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
88    &var_NumericalHashToArray    &expand
89    &var_deref    &deep_copy
90    &var_mixin    &merge_to
   &getStructSlotByStringyAddress  
91  );  );
92    
93    
94  use attributes;  use attributes;
95    use Data::Dumper;
96    use Iterate;
97    
98    use Pitonyak::DeepCopy;
99    use Data::Mungle::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar twingle_reference );
100    use Data::Mungle::Code::Ref qw( ref_slot );
101    
102  sub var_NumericalHashToArray {  sub numhash2list {
103    my $vref = shift;    my $vref = shift;
104    #my $context = shift;    #my $context = shift;
105    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 45  sub var_NumericalHashToArray { Line 115  sub var_NumericalHashToArray {
115                }                }
116                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
117              }              }
118              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
119            }            }
120  #      } else {  #      } else {
121  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 55  sub var_NumericalHashToArray { Line 125  sub var_NumericalHashToArray {
125  }  }
126    
127    
128  sub var_deref {  # FIXME: could this be refactored using expand?
129    # btw: "expand": look at scripts@CPAN (System Administration):
130    # there is a perl make with perl
131    sub _var_deref_test {
132    my $obj = shift;    my $obj = shift;
133      my $options = shift;
134    my $result;    my $result;
135    if ((ref $obj) eq 'ARRAY') {    if ((ref $obj) eq 'ARRAY') {
136      foreach (@{$obj}) {      foreach (@{$obj}) {
137        my $ref = ref $_;        my $ref = ref $_;
138        if ($ref) {        if ($ref) {
139          push(@{$result}, var_deref($_));          push(@{$result}, var_deref($_, $options));
140            #undef $_;
141        } else {        } else {
142          push(@{$result}, $_);          #push(@{$result}, $_);
143            push(@{$result}, deep_copy($_));
144        }        }
145          #undef $_ if $options->{destroy};
146          #$options->{destroy}->($_) if $options->{destroy};
147      }      }
148      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
149    } else {    } else {
150      foreach (keys %{$obj}) {      foreach (keys %{$obj}) {
151        my $key = $_;        my $key = $_;
152        my $ref = ref $obj->{$_};        my $ref = ref $obj->{$_};
153        if ($ref) {        if ($ref) {
154          $result->{$_} = var_deref($obj->{$_});          $result->{$_} = var_deref($obj->{$_}, $options);
155            #undef $obj->{$_};
156        } else {        } else {
157          $result->{$_} = $obj->{$_};          #$result->{$_} = $obj->{$_};
158            $result->{$_} = deep_copy($obj->{$_});
159        }        }
160          #undef $obj->{$_} if $options->{destroy};
161          #$options->{destroy}->($obj->{$_}) if $options->{destroy};
162      }      }
163    }    }
164      #undef $obj if $options->{destroy};
165      $options->{cb_destroy}->($obj) if $options->{cb_destroy};
166    return $result;    return $result;
167  }  }
168    
169    
170    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
171    # but still using the known latin locale stuff
172    sub expand {
173    
174      my $obj = shift;
175      my $options = shift;
176      my $result;
177    
178      #print "ref: ", ref $obj, "\n";
179    
180      if (ref $obj eq 'ARRAY') {
181      
182       # if we expand for php, keep empty ARRAY
183       if($#$obj == -1 && $options->{childObj2string}) {
184         $result = $obj;
185       } else {
186        IterArray @$obj, sub {
187          my $item;
188          # if current item is a reference ...
189          if (ref $_[0]) {
190            $item = $_[0];
191            # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
192            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
193            if ($item && $options->{childObj2string}) {
194              $item = twingle_reference($item);
195            } else {
196              # ... expand structure recursively
197              $item = expand($_[0], $options);
198            }
199            # destroy item via seperate callback method (a POST) if requested
200            #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
201    
202          # ... assume plain scalar
203          } else {
204            #$item = deep_copy($_[0]);
205            $item = $_[0];
206            # conversions/encodings
207            $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
208            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
209          }
210          #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
211          push(@{$result}, $item);                 # use item in any case
212    
213        }
214       }
215    
216      } elsif (ref $obj eq 'CODE') {
217        #print Dumper($obj);
218        #exit;
219    
220      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
221      } elsif (ref $obj) {
222      
223       # if we expand for php, keep empty HASH
224       my @tmp = keys %$obj;
225       if($#tmp == -1 && $options->{childObj2string}) {
226         $result = $obj;
227       } else {
228        IterHash %$obj, sub {
229          my $item;
230          
231          # if current item is a reference ...
232          if (ref $_[1]) {
233            $item = $_[1];
234            # if $options->{childObj2string} is TRUE or STRING don't expand referenced object,
235            # instead replace it by per option choosed string (default: o_<classname>_<ref type>_<guid> )
236            if ($item && $options->{childObj2string} && !(ref $_[1] eq "ARRAY") && !(ref $_[1] eq "HASH") && !(ref $_[1] eq "Set::Object")) {
237              $item = twingle_reference($item);
238            } else {
239              # ... expand structure recursively
240              $item = expand($_[1], $options);
241            }
242            # destroy item via seperate callback method (a POST) if requested
243            #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
244          
245          # ... assume plain scalar
246          } else {
247            #$item = deep_copy($_[1]);
248            $item = $_[1];
249            # conversions/encodings
250            $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
251            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
252          }
253          #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
254          $result->{$_[0]} = $item;               # use item in any case
255        }
256       }
257    
258      } else {
259        #die ("not a reference!");
260        $result = $obj;
261    
262      }
263    
264      # convert all values to utf8 (inside complex struct)
265        # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
266        # latin_to_utf8($result) if ($options->{utf8});
267    
268      # destroy persistent object from memory to be sure to get a fresh one next time
269      #undef $obj if $options->{destroy};
270      #$options->{cb_destroy}->($obj) if $options->{cb_destroy};
271      #$options->{cb}->{destroy}->($obj) if $options->{destroy};
272      
273      return $result;
274    }
275    
276    
277    
278  my @indexstack;  my @indexstack;
279  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
280    my $obj = shift;    my $obj = shift;
281    my $data = shift;    my $data = shift;
282    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 129  sub var_traverse_mixin_update { Line 320  sub var_traverse_mixin_update {
320    #return $result;    #return $result;
321  }  }
322    
323  sub getStructSlotByStringyAddress {  sub merge_to {
324    my $var = shift;    _hash2object(@_);
325    my $indexstack_ref = shift;    # TODO:
326    my @indexstack = @{$indexstack_ref};    # re-implement using CPAN's "Iterate" and/or a modified Hash::Merge.
   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);  
327  }  }
328    
329    
330    # todo: maybe do diff(s) here sometimes!?
331    sub _hash2object {
332      my $object = shift;
333      my $data = shift;
334      my $options = shift;
335    
336      #print "hash2object", "\n";
337      
338      # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
339      # this method corrects this
340      numhash2list($data) if ($options->{php});
341    
342      # utf8-conversion/-encoding (essential for I18N)
343      utf8_to_latin($data) if ($options->{utf8});
344    
345      # get fresh object from database
346      # todo:
347      #   - handle "locked" objects !!!
348      #   - check if already another update occoured (object-revisioning needed!)
349      #my $obj = $self->getObject($oid);
350    
351      # mix changes into fresh object and save it back
352      _hash2object_traverse_mixin($object, $data, 0, $options);
353    
354      # done in core mixin function?
355      #$self->{storage}->update($obj);
356    
357      # we should "undef" some objects here to destroy them in memory and enforce reloading when used next time
358      # simulate:
359      #$self->{storage}->disconnect();
360    
361    }
362    
363    # ------------------------------------
364    #   core mixin function
365    # TODO-FEATURE: make this possible in a reverse way: object is empty (no fields) and gets filled up by mixin-data
366    
367    # remember keys of structures we are traversing
368    # this is a HACK:
369    #  - don't (!!!) "packageglobal" @indexstack
370    #  - it will lead to problems with parallelism!
371    
372    #my @indexstack;
373    
374    # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object
375    sub _hash2object_traverse_mixin {
376      my $object = shift;
377      my $data = shift;
378      my $bool_recursion = shift;
379      my $options = shift;
380    
381      # clear our key - stack if we are called from user-code (non-recursively)
382      @indexstack = () if (!$bool_recursion);
383    
384      my $classname = ref $object;
385    #  if ($classname) {
386    #    print STDERR "*****************", Dumper(Class::Tangram::attribute_types($classname)), "\n";
387    #  }
388    
389      # parser: detected OBJECT (a Tangram one?)   (reftype == HASH) (assume)
390      # what's exactly done here? hmmm.... it works ;)
391      # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!
392      # extend! check!
393      
394      #print attributes::reftype($object), "\n";
395      
396      # V1
397      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
398      # V2
399      my $reftype = attributes::reftype($object);
400      #print "reftype: '$reftype'", "\n";
401      if ($reftype eq 'HASH') {
402    
403    #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
404            
405        my @fields;
406        # loop through fields of object (Tangram-object)
407        @fields = keys %{$object};
408    
409        # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
410        @fields = keys %{$data} if $options->{init};
411    #    @fields = keys %{$data} if $options->{mixin};
412        
413        foreach (@fields) {
414          my $field = $_;
415          push @indexstack, $field;
416                
417          # determine type of object
418          my $ref = ref $object->{$field};
419    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
420          if ($ref) {
421            _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
422          } else {
423            my $val = ref_slot($data, \@indexstack);
424            
425    #print Dumper($options);
426            my $field_target = $field;
427            if (my $pattern = $options->{pattern_strip_key}) {
428              print "pattern: $pattern", "\n";
429              $field_target =~ s/$pattern//;
430              print "field: $field_target", "\n";
431            }
432    
433            $object->{$field_target} = $val if defined $val;
434          }
435          pop @indexstack;
436        }
437    
438        # save object to database ...
439        # ... do an update if it already exists, do an insert if it doesn't
440    #    my $objectId = $self->{storage}->id($obj);
441    #    $logger->debug( __PACKAGE__ . "->saveObjectFromHash_traverse_mixin_update( object $obj objectId $objectId )" );
442    #    if ($objectId) {
443    #      $self->{storage}->update($obj);
444    
445    #print __PACKAGE__ . ":", "\n";
446    #print Dumper($object);
447    
448    #    } else {
449    #      $self->{storage}->insert($obj);
450    #    }
451        
452      }
453    
454    #&& ( ref($obj) ne 'HASH' )
455    
456        # loop through entries of array (IntrArray, isn't it?)
457      if ((ref $object) eq 'ARRAY') {
458    #    print STDERR "===", "refttype ", attributes::reftype($obj), "\n";
459        my $i = 0;
460        foreach (@{$object}) {
461          push @indexstack, $i;
462          my $ref = ref $_;
463    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
464    #      if ($ref && $_) {
465          if ($ref) {
466            _hash2object_traverse_mixin($_, $data, 1, $options);
467          } else {
468            $object->[$i] = $_ if defined $_;
469          }
470          pop @indexstack;
471          $i++;
472        }
473    
474    =pod
475      # object?
476      } else {
477        print "reference: ", ref $object, "\n";
478        print "reftype: ", $reftype, "\n";
479        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
480    =cut
481      
482      }
483    
484    }
485    
486    
487    # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
488    # on the website:
489    # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
490    # Further distribution or use is not permitted.
491    # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
492    sub deep_copy1 {
493      my $this = shift;
494      if (not ref $this) {
495        $this;
496      } elsif (ref $this eq "ARRAY") {
497        [map deep_copy1($_), @$this];
498      } elsif (ref $this eq "HASH") {
499        +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
500      } elsif (ref $this eq "CODE") {
501        $this;
502      } else { die "deep_copy1 asks: what type is $this?" }
503      #} else { print "deep_copy asks: what type is $this?", "\n"; }
504    }
505    
506    # ACK's go to Andrew Pitonyak
507    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
508    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
509    sub deep_copy {
510      Pitonyak::DeepCopy::deep_copy(@_);
511    }
512    
513    
514  1;  1;
515    __END__

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.22

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