/[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.5 by joko, Mon Dec 16 19:57:54 2002 UTC
# Line 3  Line 3 
3  #  $Id$  #  $Id$
4  #  #
5  #  $Log$  #  $Log$
6    #  Revision 1.5  2002/12/16 19:57:54  joko
7    #  + option 'init'
8    #
9    #  Revision 1.4  2002/12/05 13:56:49  joko
10    #  - var_deref
11    #  + expand - more sophisticated dereferencing with callbacks using Iterate
12    #
13    #  Revision 1.3  2002/12/03 05:34:55  joko
14    #  + bugfix: now utilizing var_utf2iso from Data::Transform::Encode
15    #
16    #  Revision 1.2  2002/12/01 04:44:07  joko
17    #  + code from Data::Transform::OO
18    #
19  #  Revision 1.1  2002/11/29 04:49:20  joko  #  Revision 1.1  2002/11/29 04:49:20  joko
20  #  + initial check-in  #  + initial check-in
21  #  #
# Line 19  use warnings; Line 32  use warnings;
32    
33  require Exporter;  require Exporter;
34  our @ISA = qw( Exporter );  our @ISA = qw( Exporter );
35  our @EXPORT_OK = qw(  our @EXPORT_OK = qw(
36    &var_NumericalHashToArray    &var_NumericalHashToArray
37    &var_deref    &var_mixin
38    &var_mixin    &object2hash
39    &getStructSlotByStringyAddress    &hash2object
40      &refexpr2perlref
41      &expand
42  );  );
43    #  &var_deref
44    #  &getStructSlotByStringyAddress
45    
46  use attributes;  use attributes;
47    use Data::Dumper;
48    use Data::Transform::Encode qw( var_utf2iso var2utf8 scalar2utf8 );
49    use libp qw( deep_copy );
50    use Iterate;
51    
52  sub var_NumericalHashToArray {  sub var_NumericalHashToArray {
53    my $vref = shift;    my $vref = shift;
# Line 57  sub var_NumericalHashToArray { Line 77  sub var_NumericalHashToArray {
77    
78  sub var_deref {  sub var_deref {
79    my $obj = shift;    my $obj = shift;
80      my $options = shift;
81    my $result;    my $result;
82    if ((ref $obj) eq 'ARRAY') {    if ((ref $obj) eq 'ARRAY') {
83      foreach (@{$obj}) {      foreach (@{$obj}) {
84        my $ref = ref $_;        my $ref = ref $_;
85        if ($ref) {        if ($ref) {
86          push(@{$result}, var_deref($_));          push(@{$result}, var_deref($_, $options));
87            #undef $_;
88        } else {        } else {
89          push(@{$result}, $_);          #push(@{$result}, $_);
90            push(@{$result}, deep_copy($_));
91        }        }
92          #undef $_ if $options->{destroy};
93          #$options->{destroy}->($_) if $options->{destroy};
94      }      }
95      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
96    } else {    } else {
97      foreach (keys %{$obj}) {      foreach (keys %{$obj}) {
98        my $key = $_;        my $key = $_;
99        my $ref = ref $obj->{$_};        my $ref = ref $obj->{$_};
100        if ($ref) {        if ($ref) {
101          $result->{$_} = var_deref($obj->{$_});          $result->{$_} = var_deref($obj->{$_}, $options);
102            #undef $obj->{$_};
103        } else {        } else {
104          $result->{$_} = $obj->{$_};          #$result->{$_} = $obj->{$_};
105            $result->{$_} = deep_copy($obj->{$_});
106        }        }
107          #undef $obj->{$_} if $options->{destroy};
108          #$options->{destroy}->($obj->{$_}) if $options->{destroy};
109      }      }
110    }    }
111      #undef $obj if $options->{destroy};
112      $options->{cb_destroy}->($obj) if $options->{cb_destroy};
113    return $result;    return $result;
114  }  }
115    
116    
117    sub expand {
118    
119      my $obj = shift;
120      my $options = shift;
121      my $result;
122    
123      if ((ref $obj) eq 'ARRAY') {
124    
125        IterArray @$obj, sub {
126          my $item;
127          # if current item is a reference ...
128          if (ref $_[0]) {
129            # ... expand structure recursively
130            $item = expand($_[0], $options);
131            # destroy item via seperate callback method (a POST) if requested
132            #$options->{cb}->{destroy}->($_[0]) if $options->{destroy};
133    
134          # ... assume plain scalar
135          } else {
136            #$item = deep_copy($_[0]);
137            $item = $_[0];
138            # conversions/encodings
139            $item = scalar2utf8($item) if ($item && $options->{utf8});
140          }
141          #push(@{$result}, $item) if $item;   # use item only if not undef  (TODO: make configurable via $options)
142          push(@{$result}, $item);                 # use item in any case
143    
144        }
145    
146      # TODO: "} elsif (ref $obj eq 'HASH') { [...] } else { croak 'could not deref blah'; }"  ???
147      } else {
148    
149        IterHash %$obj, sub {
150          my $item;
151          
152          # if current item is a reference ...
153          if (ref $_[1]) {
154            # ... expand structure recursively
155            $item = expand($_[1], $options);
156            # destroy item via seperate callback method (a POST) if requested
157            #$options->{cb}->{destroy}->($_[1]) if $options->{destroy};
158          
159          # ... assume plain scalar
160          } else {
161            #$item = deep_copy($_[1]);
162            $item = $_[1];
163            # conversions/encodings
164            $item = scalar2utf8($item) if ($item && $options->{utf8});
165          }
166          #$result->{$_[0]} = $item if $item;   # use item only if not undef  (TODO: make configurable via $options)
167          $result->{$_[0]} = $item;               # use item in any case
168        }
169    
170      }
171    
172      # convert all values to utf8 (inside complex struct)
173        # now done in core-item-callbacks via Greg London's "Iterate" from CPAN
174        # var2utf8($result) if ($options->{utf8});
175    
176      # destroy persistent object from memory to be sure to get a fresh one next time
177      #undef $obj if $options->{destroy};
178      #$options->{cb_destroy}->($obj) if $options->{cb_destroy};
179      #$options->{cb}->{destroy}->($obj) if $options->{destroy};
180      
181      return $result;
182    }
183    
184    
185    
186  my @indexstack;  my @indexstack;
# Line 129  sub var_traverse_mixin_update { Line 228  sub var_traverse_mixin_update {
228    #return $result;    #return $result;
229  }  }
230    
231    sub object2hash {
232      my $object = shift;
233      my $options = shift;
234      #my $deref = var_deref($object);
235      my $deref = expand($object, $options);
236      #var2utf8($deref) if ($options->{utf8});
237      return $deref;
238    }
239    
240    # todo: maybe do diff(s) here sometimes!?
241    sub hash2object {
242      my $object = shift;
243      my $data = shift;
244      my $options = shift;
245    
246      #print "hash2object", "\n";
247      
248      # "patch" needed 'cause php passes numerical-indexed-arrays as hash-tables,
249      # this method corrects this
250      var_NumericalHashToArray($data) if ($options->{php});
251    
252      # utf8-conversion/-encoding (essential for I18N)
253      var_utf2iso($data) if ($options->{utf8});
254    
255      # get fresh object from database
256      # todo:
257      #   - handle "locked" objects !!!
258      #   - check if already another update occoured (object-revisioning needed!)
259      #my $obj = $self->getObject($oid);
260    
261      # mix changes into fresh object and save it back
262      hash2object_traverse_mixin($object, $data, 0, $options);
263    
264      # done in core mixin function?
265      #$self->{storage}->update($obj);
266    
267      # we should "undef" some objects here to destroy them in memory and enforce reloading when used next time
268      # simulate:
269      #$self->{storage}->disconnect();
270    
271    }
272    
273    # ------------------------------------
274    #   core mixin function
275    # TODO-FEATURE: make this possible in a reverse way: object is empty (no fields) and gets filled up by mixin-data
276    
277    # remember keys of structures we are traversing
278    # this is a HACK:
279    #  - don't (!!!) "packageglobal" @indexstack
280    #  - it will lead to problems with parallelism!
281    
282    #my @indexstack;
283    
284    # traverse a deeply nested structure, mix in values from given hash, update underlying tangram-object
285    sub hash2object_traverse_mixin {
286      my $object = shift;
287      my $data = shift;
288      my $bool_recursion = shift;
289      my $options = shift;
290    
291      # clear our key - stack if we are called from user-code (non-recursively)
292      @indexstack = () if (!$bool_recursion);
293    
294      my $classname = ref $object;
295    #  if ($classname) {
296    #    print STDERR "*****************", Dumper(Class::Tangram::attribute_types($classname)), "\n";
297    #  }
298    
299      # parser: detected OBJECT (a Tangram one?)   (reftype == HASH) (assume)
300      # what's exactly done here? hmmm.... it works ;)
301      # maybe a HACK: please try not to use "IntrHash"es, maybe this cannot handle them!!!
302      # extend! check!
303      if ((attributes::reftype($object) eq 'HASH') && (ref($object) ne 'HASH') && (ref($object) ne 'ARRAY')) {
304    
305    #    print STDERR "===", "reftype: ", attributes::reftype($obj), "\n";
306            
307        my @fields;
308        # loop through fields of object (Tangram-object)
309        @fields = keys %{$object};
310    
311        # loop through fields of to.be.injected-data (arbitrary Perl-data-structure)
312        @fields = keys %{$data} if $options->{init};
313        
314        foreach (@fields) {
315          push @indexstack, $_;
316                
317          # determine type of object
318          my $ref = ref $object->{$_};
319    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
320          if ($ref) {
321            hash2object_traverse_mixin($object->{$_}, $data, 1, $options);
322          } else {
323            my $val = getStructSlotByStringyAddress($data, \@indexstack);
324            $object->{$_} = $val;        
325          }
326          pop @indexstack;
327        }
328    
329        # save object to database ...
330        # ... do an update if it already exists, do an insert if it doesn't
331    #    my $objectId = $self->{storage}->id($obj);
332    #    $logger->debug( __PACKAGE__ . "->saveObjectFromHash_traverse_mixin_update( object $obj objectId $objectId )" );
333    #    if ($objectId) {
334    #      $self->{storage}->update($obj);
335    
336    #print __PACKAGE__ . ":", "\n";
337    #print Dumper($object);
338    
339    #    } else {
340    #      $self->{storage}->insert($obj);
341    #    }
342        
343      }
344    
345    #&& ( ref($obj) ne 'HASH' )
346    
347        # loop through entries of array (IntrArray, isn't it?)
348      if ((ref $object) eq 'ARRAY') {
349    #    print STDERR "===", "refttype ", attributes::reftype($obj), "\n";
350        my $i = 0;
351        foreach (@{$object}) {
352          push @indexstack, $i;
353          my $ref = ref $_;
354    #      print STDERR "attrname: $_  ATTRref: $ref", "\n";
355          if ($ref && $_) {
356            hash2object_traverse_mixin($_, $data, 1, $options);
357          } else {
358            $object->[$i] = $_;
359          }
360          pop @indexstack;
361          $i++;
362        }
363      }
364    
365    }
366    
367    
368    # this function seems to do similar stuff like these below (refexpr2perlref & co.)
369    # TODO: maybe this mechanism can be replaced completely through some nice module from CPAN .... ?   ;-)
370  sub getStructSlotByStringyAddress {  sub getStructSlotByStringyAddress {
371    my $var = shift;    my $var = shift;
372    my $indexstack_ref = shift;    my $indexstack_ref = shift;
# Line 147  sub getStructSlotByStringyAddress { Line 385  sub getStructSlotByStringyAddress {
385    return eval($evstring);    return eval($evstring);
386  }  }
387    
388    
389    sub refexpr2perlref {
390    
391      my $obj = shift;
392      my $expr = shift;
393      my $callbackMap = shift;
394    
395      my $value;
396      # detect for callback (code-reference)
397      if (ref($expr) eq 'CODE') {
398        $value = &$expr($obj);
399    
400      } elsif ($expr =~ m/->/) {
401        # use expr as complex object reference declaration (obj->subObj->subSubObj->0->attribute)
402        (my $objPerlRefString, my $parts) = refexpr2perlref_parts($expr);
403        #print "\n", "expr: $expr";
404        #print "\n", "objPerlRefString: $objPerlRefString";
405        $value = eval('$obj' . '->' . $objPerlRefString);
406        
407        # if value isn't set, try to "fallback" to callbackMap
408        # callbacks are applied this way:
409        #   take the last element of the expression parts and check if this string exists as a key in the callback-map
410        if (!$value && $callbackMap) {
411          #print Dumper($callbackMap);
412          
413          # prepare needle
414          my @parts = @$parts;
415          my $count = $#parts;
416          my $needle = $parts[$count];
417    
418          # prepare haystack
419          my @haystack = keys %$callbackMap;
420          if (grep($needle, @haystack)) {
421            $value = $callbackMap->{$needle}->();
422            #print "value: ", $value, "\n";
423          }
424        }
425    
426      } else {
427        # use expr as simple scalar key (attributename)
428        $value = $obj->{$expr};
429      }
430              
431      return $value;
432      
433    }
434    
435    
436    sub refexpr2perlref_parts {
437      my $expr = shift;
438    
439      # split expression by dereference operators first
440      my @parts_pure = split(/->/, $expr);
441    
442      # wrap []'s around each part, if it consists of numeric characters only (=> numeric = array-index),
443      # use {}'s, if there are word-characters in it (=> alphanumeric = hash-key)
444      my @parts_capsule = @parts_pure;
445      map {
446        m/^\d+$/ && ($_ = "[$_]") || ($_ = "{$_}");
447      } @parts_capsule;
448    
449      # join parts with dereference operators together again and return built string
450      return (join('->', @parts_capsule), \@parts_pure);
451    }
452    
453  1;  1;

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

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