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

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

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