MooseX::Storage - added peek()
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Engine.pm
1
2 package MooseX::Storage::Engine;
3 use Moose;
4
5 our $VERSION   = '0.02';
6 our $AUTHORITY = 'cpan:STEVAN';
7
8 # the class marker when 
9 # serializing an object. 
10 our $CLASS_MARKER = '__CLASS__';
11
12 has 'storage' => (
13     is      => 'ro',
14     isa     => 'HashRef',
15     default => sub {{}}
16 );
17
18 has 'seen' => (
19     is      => 'ro',
20     isa     => 'HashRef',
21     default => sub {{}}
22 );
23
24 has 'object' => (is => 'rw', isa => 'Object');
25 has 'class'  => (is => 'rw', isa => 'Str');
26
27 ## this is the API used by other modules ...
28
29 sub collapse_object {
30     my ( $self, %options ) = @_;
31
32         # NOTE:
33         # mark the root object as seen ...
34         $self->seen->{$self->object} = undef;
35         
36     $self->map_attributes('collapse_attribute', \%options);
37     $self->storage->{$CLASS_MARKER} = $self->object->meta->identifier;    
38         return $self->storage;
39 }
40
41 sub expand_object {
42     my ($self, $data, %options) = @_;
43     
44     $options{check_version}   = 1 unless exists $options{check_version};
45     $options{check_authority} = 1 unless exists $options{check_authority};   
46     
47         # NOTE:
48         # mark the root object as seen ...
49         $self->seen->{$data} = undef;    
50     
51     $self->map_attributes('expand_attribute', $data, \%options);
52         return $self->storage;    
53 }
54
55 ## this is the internal API ...
56
57 sub collapse_attribute {
58     my ($self, $attr, $options)  = @_;
59     $self->storage->{$attr->name} = $self->collapse_attribute_value($attr, $options) || return;
60 }
61
62 sub expand_attribute {
63     my ($self, $attr, $data, $options)  = @_;
64     $self->storage->{$attr->name} = $self->expand_attribute_value($attr, $data->{$attr->name}, $options) || return;
65 }
66
67 sub collapse_attribute_value {
68     my ($self, $attr, $options)  = @_;
69         my $value = $attr->get_value($self->object);
70         
71         # NOTE:
72         # this might not be enough, we might 
73         # need to make it possible for the 
74         # cycle checker to return the value
75     $self->check_for_cycle_in_collapse($attr, $value)
76         if ref $value;
77         
78     if (defined $value && $attr->has_type_constraint) {
79         my $type_converter = $self->find_type_handler($attr->type_constraint);
80         (defined $type_converter)
81             || confess "Cannot convert " . $attr->type_constraint->name;
82         $value = $type_converter->{collapse}->($value, $options);
83     }
84         return $value;
85 }
86
87 sub expand_attribute_value {
88     my ($self, $attr, $value, $options)  = @_;
89
90         # NOTE:
91         # (see comment in method above ^^)
92     $self->check_for_cycle_in_expansion($attr, $value) 
93         if ref $value;    
94     
95     if (defined $value && $attr->has_type_constraint) {
96         my $type_converter = $self->find_type_handler($attr->type_constraint);
97         $value = $type_converter->{expand}->($value, $options);
98     }
99         return $value;
100 }
101
102 # NOTE:
103 # possibly these two methods will 
104 # be used by a cycle supporting 
105 # engine. However, I am not sure 
106 # if I can make a cycle one work 
107 # anyway.
108
109 sub check_for_cycle_in_collapse {
110     my ($self, $attr, $value) = @_;
111     (!exists $self->seen->{$value})
112         || confess "Basic Engine does not support cycles in class(" 
113                  . ($attr->associated_class->name) . ").attr("
114                  . ($attr->name) . ") with $value";
115     $self->seen->{$value} = undef;
116 }
117
118 sub check_for_cycle_in_expansion {
119     my ($self, $attr, $value) = @_;
120     (!exists $self->seen->{$value})
121     || confess "Basic Engine does not support cycles in class(" 
122              . ($attr->associated_class->name) . ").attr("
123              . ($attr->name) . ") with $value";
124     $self->seen->{$value} = undef;
125 }
126
127 # util methods ...
128
129 sub map_attributes {
130     my ($self, $method_name, @args) = @_;
131     map { 
132         $self->$method_name($_, @args) 
133     } grep {
134         # Skip our special skip attribute :)
135         !$_->isa('MooseX::Storage::Meta::Attribute::DoNotSerialize')
136     } ($self->object || $self->class)->meta->compute_all_applicable_attributes;
137 }
138
139 ## ------------------------------------------------------------------
140 ## This is all the type handler stuff, it is in a state of flux
141 ## right now, so this may change, or it may just continue to be 
142 ## improved upon. Comments and suggestions are welcomed.
143 ## ------------------------------------------------------------------
144
145 # NOTE:
146 # these are needed by the 
147 # ArrayRef and HashRef handlers
148 # below, so I need easy access 
149 my %OBJECT_HANDLERS = (
150     expand => sub {
151         my ($data, $options) = @_;   
152         (exists $data->{$CLASS_MARKER})
153             || confess "Serialized item has no class marker";
154         # check the class more thoroughly here ...
155         my ($class, $version, $authority) = (split '-' => $data->{$CLASS_MARKER});
156         my $meta = eval { $class->meta };
157         confess "Class ($class) is not loaded, cannot unpack" if $@;     
158         
159         if ($options->{check_version}) {
160             my $meta_version = $meta->version;
161             if (defined $meta_version && $version) {            
162                 if ($options->{check_version} eq 'allow_less_than') {
163                     ($meta_version <= $version)
164                         || confess "Class ($class) versions is not less than currently available." 
165                                  . " got=($version) available=($meta_version)";                
166                 }
167                 elsif ($options->{check_version} eq 'allow_greater_than') {
168                     ($meta->version >= $version)
169                         || confess "Class ($class) versions is not greater than currently available." 
170                                  . " got=($version) available=($meta_version)";                
171                 }            
172                 else {
173                     ($meta->version == $version)
174                         || confess "Class ($class) versions don't match." 
175                                  . " got=($version) available=($meta_version)";
176                 }
177             }
178         }
179         
180         if ($options->{check_authority}) {
181             my $meta_authority = $meta->authority;
182             ($meta->authority eq $authority)
183                 || confess "Class ($class) authorities don't match." 
184                          . " got=($authority) available=($meta_authority)"
185                 if defined $meta_authority && defined $authority;            
186         }
187             
188         # all is well ...
189         $class->unpack($data, %$options);
190     },
191     collapse => sub {
192         my ( $obj, $options ) = @_;
193 #        ($obj->can('does') && $obj->does('MooseX::Storage::Basic'))
194 #            || confess "Bad object ($obj) does not do MooseX::Storage::Basic role";
195         ($obj->can('pack'))
196             || confess "Object does not have a &pack method, cannot collapse";
197         $obj->pack(%$options);
198     },
199 );
200
201
202 my %TYPES = (
203     # These are boring ones, so they use the identity function ...
204     'Int'      => { expand => sub { shift }, collapse => sub { shift } },
205     'Num'      => { expand => sub { shift }, collapse => sub { shift } },
206     'Str'      => { expand => sub { shift }, collapse => sub { shift } },
207     # These are the trickier ones, (see notes)
208     # NOTE:
209     # Because we are nice guys, we will check 
210     # your ArrayRef and/or HashRef one level 
211     # down and inflate any objects we find. 
212     # But this is where it ends, it is too
213     # expensive to try and do this any more  
214     # recursively, when it is probably not 
215     # nessecary in most of the use cases.
216     # However, if you need more then this, subtype 
217     # and add a custom handler.    
218     'ArrayRef' => { 
219         expand => sub {
220             my ( $array, @args ) = @_;
221             foreach my $i (0 .. $#{$array}) {
222                 next unless ref($array->[$i]) eq 'HASH' 
223                          && exists $array->[$i]->{$CLASS_MARKER};
224                 $array->[$i] = $OBJECT_HANDLERS{expand}->($array->[$i], @args);
225             }
226             $array;
227         }, 
228         collapse => sub {
229             my ( $array, @args ) = @_;
230             # NOTE:         
231             # we need to make a copy cause
232             # otherwise it will affect the 
233             # other real version.
234             [ map {
235                 blessed($_)
236                     ? $OBJECT_HANDLERS{collapse}->($_, @args)
237                     : $_
238             } @$array ] 
239         } 
240     },
241     'HashRef'  => { 
242         expand   => sub {
243             my ( $hash, @args ) = @_;
244             foreach my $k (keys %$hash) {
245                 next unless ref($hash->{$k}) eq 'HASH' 
246                          && exists $hash->{$k}->{$CLASS_MARKER};
247                 $hash->{$k} = $OBJECT_HANDLERS{expand}->($hash->{$k}, @args);
248             }
249             $hash;            
250         }, 
251         collapse => sub {
252             my ( $hash, @args ) = @_;
253             # NOTE:         
254             # we need to make a copy cause
255             # otherwise it will affect the 
256             # other real version.
257             +{ map {
258                 blessed($hash->{$_})
259                     ? ($_ => $OBJECT_HANDLERS{collapse}->($hash->{$_}, @args))
260                     : ($_ => $hash->{$_})
261             } keys %$hash }            
262         } 
263     },
264     'Object'   => \%OBJECT_HANDLERS,
265     # NOTE:
266     # The sanity of enabling this feature by 
267     # default is very questionable.
268     # - SL
269     #'CodeRef' => {
270     #    expand   => sub {}, # use eval ...
271     #    collapse => sub {}, # use B::Deparse ...        
272     #} 
273 );
274
275 sub add_custom_type_handler {
276     my ($class, $type_name, %handlers) = @_;
277     (exists $handlers{expand} && exists $handlers{collapse})
278         || confess "Custom type handlers need an expand *and* a collapse method";
279     $TYPES{$type_name} = \%handlers;
280 }
281
282 sub remove_custom_type_handler {
283     my ($class, $type_name) = @_;
284     delete $TYPES{$type_name} if exists $TYPES{$type_name};
285 }
286
287 sub find_type_handler {
288     my ($self, $type_constraint) = @_;
289     
290     # this should handle most type usages
291     # since they they are usually just 
292     # the standard set of built-ins
293     return $TYPES{$type_constraint->name} 
294         if exists $TYPES{$type_constraint->name};
295       
296     # the next possibility is they are 
297     # a subtype of the built-in types, 
298     # in which case this will DWIM in 
299     # most cases. It is probably not 
300     # 100% ideal though, but until I 
301     # come up with a decent test case 
302     # it will do for now.
303     foreach my $type (keys %TYPES) {
304         return $TYPES{$type} 
305             if $type_constraint->is_subtype_of($type);
306     }
307     
308     # NOTE:
309     # the reason the above will work has to 
310     # do with the fact that custom subtypes
311     # are mostly used for validation of 
312     # the guts of a type, and not for some
313     # weird structural thing which would 
314     # need to be accomidated by the serializer.
315     # Of course, mst or phaylon will probably  
316     # do something to throw this assumption 
317     # totally out the door ;)
318     # - SL
319     
320     # NOTE:
321     # if this method hasnt returned by now
322     # then we have no been able to find a 
323     # type constraint handler to match 
324     confess "Cannot handle type constraint (" . $type_constraint->name . ")";    
325 }
326
327 1;
328
329 __END__
330
331 =pod
332
333 =head1 NAME
334
335 MooseX::Storage::Engine - The meta-engine to handle collapsing and expanding objects
336
337 =head1 DESCRIPTION
338
339 No user serviceable parts inside. If you really want to know, read the source :)
340
341 =head1 METHODS
342
343 =head2 Accessors
344
345 =over 4
346
347 =item B<class>
348
349 =item B<object>
350
351 =item B<storage>
352
353 =item B<seen>
354
355 =back
356
357 =head2 API
358
359 =over 4
360
361 =item B<expand_object>
362
363 =item B<collapse_object>
364
365 =back
366
367 =head2 ...
368
369 =over 4
370
371 =item B<collapse_attribute>
372
373 =item B<collapse_attribute_value>
374
375 =item B<expand_attribute>
376
377 =item B<expand_attribute_value>
378
379 =item B<check_for_cycle_in_collapse>
380
381 =item B<check_for_cycle_in_expansion>
382
383 =item B<map_attributes>
384
385 =back
386
387 =head2 Type Constraint Handlers
388
389 =over 4
390
391 =item B<find_type_handler>
392
393 =item B<add_custom_type_handler>
394
395 =item B<remove_custom_type_handler>
396
397 =back
398
399 =head2 Introspection
400
401 =over 4
402
403 =item B<meta>
404
405 =back
406
407 =head1 BUGS
408
409 All complex software has bugs lurking in it, and this module is no 
410 exception. If you find a bug please either email me, or add the bug
411 to cpan-RT.
412
413 =head1 AUTHOR
414
415 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
416
417 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
418
419 =head1 COPYRIGHT AND LICENSE
420
421 Copyright 2007 by Infinity Interactive, Inc.
422
423 L<http://www.iinteractive.com>
424
425 This library is free software; you can redistribute it and/or modify
426 it under the same terms as Perl itself.
427
428 =cut
429
430
431