/[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.13 by joko, Fri Feb 21 01:48:50 2003 UTC
# Line 1  Line 1 
1  ##############################################  ## ---------------------------------------------------------------------------
2  #  ##  $Id$
3  #  $Id$  ## ---------------------------------------------------------------------------
4  #  ##  $Log$
5  #  $Log$  ##  Revision 1.13  2003/02/21 01:48:50  joko
6  #  Revision 1.1  2002/11/29 04:49:20  joko  ##  renamed core function
7  #  + initial check-in  ##
8  #  ##  Revision 1.12  2003/02/20 22:45:19  joko
9  #  Revision 1.1  2002/10/10 03:26:00  cvsjoko  ##  fix regarding new deep_copy
10  #  + new  ##
11  #  ##  Revision 1.11  2003/02/20 21:13:54  joko
12  ##############################################  ##  - removed implementation of deep_copy2 - get this from the Pitonyak namespace (now cloned to repository)
13    ##
14    ##  Revision 1.10  2003/02/20 20:48:00  joko
15    ##  - refactored lots of code to Data::Code::Ref
16    ##  + alternative 'deep_copy' implementation
17    ##
18    ##  Revision 1.9  2003/02/18 19:35:56  joko
19    ##  +- modified 'sub refexpr2perlref': now can get the $delimiter passed, too
20    ##
21    ##  Revision 1.8  2003/02/09 05:10:56  joko
22    ##  + minor update
23    ##
24    ##  Revision 1.7  2003/01/19 03:26:59  joko
25    ##  + added 'sub deep_copy'  -  refactored from libp
26    ##  + add 'sub merge'  -  exported from CPAN's 'Hash::Merge'
27    ##
28    ##  Revision 1.6  2002/12/23 11:27:53  jonen
29    ##  + changed behavior WATCH!
30    ##
31    ##  Revision 1.5  2002/12/16 19:57:54  joko
32    ##  + option 'init'
33    ##
34    ##  Revision 1.4  2002/12/05 13:56:49  joko
35    ##  - var_deref
36    ##  + expand - more sophisticated dereferencing with callbacks using Iterate
37    ##
38    ##  Revision 1.3  2002/12/03 05:34:55  joko
39    ##  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
40    ##
41    ##  Revision 1.2  2002/12/01 04:44:07  joko
42    ##  + code from Data::Transform::OO
43    ##
44    ##  Revision 1.1  2002/11/29 04:49:20  joko
45    ##  + initial check-in
46    ##
47    ##  Revision 1.1  2002/10/10 03:26:00  cvsjoko
48    ##  + new
49    ## ---------------------------------------------------------------------------
50    
51    
52  package Data::Transform::Deep;  package Data::Transform::Deep;
# Line 19  use warnings; Line 56  use warnings;
56    
57  require Exporter;  require Exporter;
58  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
59  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
60    &var_NumericalHashToArray    &expand
61    &var_deref    &deep_copy
62    &var_mixin    &merge_to
   &getStructSlotByStringyAddress  
63  );  );
64    
65    
66  use attributes;  use attributes;
67    use Data::Dumper;
68    use Iterate;
69    
70    use Pitonyak::DeepCopy;
71    use Data::Transform::Encode qw( latin_to_utf8 latin_to_utf8_scalar utf8_to_latin utf8_to_latin_scalar );
72    use Data::Code::Ref qw( ref_slot );
73    
74  sub var_NumericalHashToArray {  sub numhash2list {
75    my $vref = shift;    my $vref = shift;
76    #my $context = shift;    #my $context = shift;
77    if (ref $vref eq 'HASH') {    if (ref $vref eq 'HASH') {
# Line 45  sub var_NumericalHashToArray { Line 87  sub var_NumericalHashToArray {
87                }                }
88                $vref->{$_} = \@arr;                $vref->{$_} = \@arr;
89              }              }
90              var_NumericalHashToArray($vref->{$_});              numhash2list($vref->{$_});
91            }            }
92  #      } else {  #      } else {
93  #        #$vref->{$_} = scalar2iso($vref->{$_});  #        #$vref->{$_} = scalar2iso($vref->{$_});
# Line 55  sub var_NumericalHashToArray { Line 97  sub var_NumericalHashToArray {
97  }  }
98    
99    
100  sub var_deref {  # FIXME: could this be refactored using expand?
101    # btw: "expand": look at scripts@CPAN (System Administration):
102    # there is a perl make with perl
103    sub _var_deref_test {
104    my $obj = shift;    my $obj = shift;
105      my $options = shift;
106    my $result;    my $result;
107    if ((ref $obj) eq 'ARRAY') {    if ((ref $obj) eq 'ARRAY') {
108      foreach (@{$obj}) {      foreach (@{$obj}) {
109        my $ref = ref $_;        my $ref = ref $_;
110        if ($ref) {        if ($ref) {
111          push(@{$result}, var_deref($_));          push(@{$result}, var_deref($_, $options));
112            #undef $_;
113        } else {        } else {
114          push(@{$result}, $_);          #push(@{$result}, $_);
115            push(@{$result}, deep_copy($_));
116        }        }
117          #undef $_ if $options->{destroy};
118          #$options->{destroy}->($_) if $options->{destroy};
119      }      }
120      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
121    } else {    } else {
122      foreach (keys %{$obj}) {      foreach (keys %{$obj}) {
123        my $key = $_;        my $key = $_;
124        my $ref = ref $obj->{$_};        my $ref = ref $obj->{$_};
125        if ($ref) {        if ($ref) {
126          $result->{$_} = var_deref($obj->{$_});          $result->{$_} = var_deref($obj->{$_}, $options);
127            #undef $obj->{$_};
128        } else {        } else {
129          $result->{$_} = $obj->{$_};          #$result->{$_} = $obj->{$_};
130            $result->{$_} = deep_copy($obj->{$_});
131        }        }
132          #undef $obj->{$_} if $options->{destroy};
133          #$options->{destroy}->($obj->{$_}) if $options->{destroy};
134      }      }
135    }    }
136      #undef $obj if $options->{destroy};
137      $options->{cb_destroy}->($obj) if $options->{cb_destroy};
138    return $result;    return $result;
139  }  }
140    
141    
142    # convert values in hash to utf8 (and back) to be ready for (e.g.) encapsulation in XML
143    # but still using the known latin locale stuff
144    sub expand {
145    
146      my $obj = shift;
147      my $options = shift;
148      my $result;
149    
150      #print "ref: ", ref $obj, "\n";
151    
152      if (ref $obj eq 'ARRAY') {
153    
154        IterArray @$obj, sub {
155          my $item;
156          # if current item is a reference ...
157          if (ref $_[0]) {
158            # ... expand structure recursively
159            $item = expand($_[0], $options);
160            # destroy item via seperate callback method (a POST) if requested
161            #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
162    
163          # ... assume plain scalar
164          } else {
165            #$item = deep_copy($_[0]);
166            $item = $_[0];
167            # conversions/encodings
168            $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
169            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
170          }
171          #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
172          push(@{$result}, $item);                 # use item in any case
173    
174        }
175    
176      } elsif (ref $obj eq 'CODE') {
177        #print Dumper($obj);
178        #exit;
179    
180      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
181      } elsif (ref $obj) {
182    
183        IterHash %$obj, sub {
184          my $item;
185          
186          # if current item is a reference ...
187          if (ref $_[1]) {
188            # ... expand structure recursively
189            $item = expand($_[1], $options);
190            # destroy item via seperate callback method (a POST) if requested
191            #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
192          
193          # ... assume plain scalar
194          } else {
195            #$item = deep_copy($_[1]);
196            $item = $_[1];
197            # conversions/encodings
198            $item = latin_to_utf8_scalar($item) if ($item && $options->{utf8});
199            $item = utf8_to_latin_scalar($item) if ($item && $options->{to_latin});
200          }
201          #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
202          $result->{$_[0]} = $item;               # use item in any case
203        }
204    
205      } else {
206        #die ("not a reference!");
207        $result = $obj;
208    
209      }
210    
211      # convert all values to utf8 (inside complex struct)
212        # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
213        # latin_to_utf8($result) if ($options->{utf8});
214    
215      # destroy persistent object from memory to be sure to get a fresh one next time
216      #undef $obj if $options->{destroy};
217      #$options->{cb_destroy}->($obj) if $options->{cb_destroy};
218      #$options->{cb}->{destroy}->($obj) if $options->{destroy};
219      
220      return $result;
221    }
222    
223    
224    
225  my @indexstack;  my @indexstack;
226  sub var_traverse_mixin_update {  sub _var_traverse_mixin_update_old {
227    my $obj = shift;    my $obj = shift;
228    my $data = shift;    my $data = shift;
229    my $bool_recursion = shift;    my $bool_recursion = shift;
# Line 129  sub var_traverse_mixin_update { Line 267  sub var_traverse_mixin_update {
267    #return $result;    #return $result;
268  }  }
269    
270  sub getStructSlotByStringyAddress {  sub merge_to {
271    my $var = shift;    _hash2object(@_);
272    my $indexstack_ref = shift;    # TODO:
273    my @indexstack = @{$indexstack_ref};    # re-implement using CPAN's "Iterate".
274    my $joiner = '->';  }
275    my @evlist;  
276    foreach (@indexstack) {  
277      my $elem;  # todo: maybe do diff(s) here sometimes!?
278      if ($_ =~ m/\d+/) { $elem = "[$_]"; }  sub _hash2object {
279      if ($_ =~ m/\D+/) { $elem = "{$_}"; }    my $object = shift;
280      push @evlist, $elem;    my $data = shift;
281    }    my $options = shift;
282    my $evstring = join($joiner, @evlist);  
283    $evstring = 'return $var->' . $evstring . ';';    #print "hash2object", "\n";
284    #print "ev: $evstring\n";    
285    return eval($evstring);    # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
286      # this method corrects this
287      numhash2list($data) if ($options->{php});
288    
289      # utf8-conversion/-encoding (essential for I18N)
290      var_utf2iso($data) if ($options->{utf8});
291    
292      # get fresh object from database
293      # todo:
294      #   - handle "locked" objects !!!
295      #   - check if already another update occoured (object-revisioning needed!)
296      #my $obj = $self->getObject($oid);
297    
298      # mix changes into fresh object and save it back
299      _hash2object_traverse_mixin($object, $data, 0, $options);
300    
301      # done in core mixin function?
302      #$self->{storage}->update($obj);
303    
304      # we should "undef" some objects here to destroy them in memory and enforce reloading when used next time
305      # simulate:
306      #$self->{storage}->disconnect();
307    
308    }
309    
310    # ------------------------------------
311    #   core mixin function
312    # TODO-FEATURE: make this possible in a reverse way: object is empty (no fields) and gets filled up by mixin-data
313    
314    # remember keys of structures we are traversing
315    # this is a HACK:
316    #  - don't (!!!) "packageglobal" @indexstack
317    #  - it will lead to problems with parallelism!
318    
319    #my @indexstack;
320    
321    # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object
322    sub _hash2object_traverse_mixin {
323      my $object = shift;
324      my $data = shift;
325      my $bool_recursion = shift;
326      my $options = shift;
327    
328      # clear our key - stack if we are called from user-code (non-recursively)
329      @indexstack = () if (!$bool_recursion);
330    
331      my $classname = ref $object;
332    #  if ($classname) {
333    #    print STDERR "*****************", Dumper(Class::Tangram::attribute_types($classname)), "\n";
334    #  }
335    
336      # parser: detected OBJECT (a Tangram one?)   (reftype == HASH) (assume)
337      # what's exactly done here? hmmm.... it works ;)
338      # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!
339      # extend! check!
340      
341      #print attributes::reftype($object), "\n";
342      
343      # V1
344      #if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
345      # V2
346      my $reftype = attributes::reftype($object);
347      #print "reftype: '$reftype'", "\n";
348      if ($reftype eq 'HASH') {
349    
350    #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
351            
352        my @fields;
353        # loop through fields of object (Tangram-object)
354        @fields = keys %{$object};
355    
356        # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
357        @fields = keys %{$data} if $options->{init};
358    #    @fields = keys %{$data} if $options->{mixin};
359        
360        foreach (@fields) {
361          my $field = $_;
362          push @indexstack, $field;
363                
364          # determine type of object
365          my $ref = ref $object->{$field};
366    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
367          if ($ref) {
368            _hash2object_traverse_mixin($object->{$field}, $data, 1, $options);
369          } else {
370            my $val = ref_slot($data, \@indexstack);
371            
372    #print Dumper($options);
373            my $field_target = $field;
374            if (my $pattern = $options->{pattern_strip_key}) {
375              print "pattern: $pattern", "\n";
376              $field_target =~ s/$pattern//;
377              print "field: $field_target", "\n";
378            }
379    
380            $object->{$field_target} = $val if defined $val;
381          }
382          pop @indexstack;
383        }
384    
385        # save object to database ...
386        # ... do an update if it already exists, do an insert if it doesn't
387    #    my $objectId = $self->{storage}->id($obj);
388    #    $logger->debug( __PACKAGE__ . "->saveObjectFromHash_traverse_mixin_update( object $obj objectId $objectId )" );
389    #    if ($objectId) {
390    #      $self->{storage}->update($obj);
391    
392    #print __PACKAGE__ . ":", "\n";
393    #print Dumper($object);
394    
395    #    } else {
396    #      $self->{storage}->insert($obj);
397    #    }
398        
399      }
400    
401    #&& ( ref($obj) ne 'HASH' )
402    
403        # loop through entries of array (IntrArray, isn't it?)
404      if ((ref $object) eq 'ARRAY') {
405    #    print STDERR "===", "refttype ", attributes::reftype($obj), "\n";
406        my $i = 0;
407        foreach (@{$object}) {
408          push @indexstack, $i;
409          my $ref = ref $_;
410    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
411    #      if ($ref && $_) {
412          if ($ref) {
413            _hash2object_traverse_mixin($_, $data, 1, $options);
414          } else {
415            $object->[$i] = $_ if defined $_;
416          }
417          pop @indexstack;
418          $i++;
419        }
420    
421    =pod
422      # object?
423      } else {
424        print "reference: ", ref $object, "\n";
425        print "reftype: ", $reftype, "\n";
426        die(__PACKAGE__ . "->_hash2object_traverse_mixin: can not handle this!");
427    =cut
428      
429      }
430    
431    }
432    
433    
434    # ACK's go to Randal L. Schwartz <merlyn@stonehenge.com>
435    # on the website:
436    # This text is copyright by Miller-Freeman, Inc., and is used with their permission.
437    # Further distribution or use is not permitted.
438    # please visit http://www.stonehenge.com/merlyn/UnixReview/col30.html
439    sub deep_copy1 {
440      my $this = shift;
441      if (not ref $this) {
442        $this;
443      } elsif (ref $this eq "ARRAY") {
444        [map deep_copy1($_), @$this];
445      } elsif (ref $this eq "HASH") {
446        +{map { $_ => deep_copy1($this->{$_}) } keys %$this};
447      } elsif (ref $this eq "CODE") {
448        $this;
449      } else { die "deep_copy1 asks: what type is $this?" }
450      #} else { print "deep_copy asks: what type is $this?", "\n"; }
451    }
452    
453    # ACK's go to Andrew Pitonyak
454    # Copyright 2002, Andrew Pitonyak (perlboy@pitonyak.org)
455    # please visit: http://www.pitonyak.org/code/perl/Pitonyak/DeepCopy.pm.html
456    sub deep_copy {
457      Pitonyak::DeepCopy::deep_copy(@_);
458  }  }
459    
460    
461  1;  1;
462    __END__

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

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