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

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

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