Add mysteriously-missing Bool handling
[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     'Bool'     => { expand => sub { shift }, collapse => sub { shift } },
208     # These are the trickier ones, (see notes)
209     # NOTE:
210     # Because we are nice guys, we will check 
211     # your ArrayRef and/or HashRef one level 
212     # down and inflate any objects we find. 
213     # But this is where it ends, it is too
214     # expensive to try and do this any more  
215     # recursively, when it is probably not 
216     # nessecary in most of the use cases.
217     # However, if you need more then this, subtype 
218     # and add a custom handler.    
219     'ArrayRef' => { 
220         expand => sub {
221             my ( $array, @args ) = @_;
222             foreach my $i (0 .. $#{$array}) {
223                 next unless ref($array->[$i]) eq 'HASH' 
224                          && exists $array->[$i]->{$CLASS_MARKER};
225                 $array->[$i] = $OBJECT_HANDLERS{expand}->($array->[$i], @args);
226             }
227             $array;
228         }, 
229         collapse => sub {
230             my ( $array, @args ) = @_;
231             # NOTE:         
232             # we need to make a copy cause
233             # otherwise it will affect the 
234             # other real version.
235             [ map {
236                 blessed($_)
237                     ? $OBJECT_HANDLERS{collapse}->($_, @args)
238                     : $_
239             } @$array ] 
240         } 
241     },
242     'HashRef'  => { 
243         expand   => sub {
244             my ( $hash, @args ) = @_;
245             foreach my $k (keys %$hash) {
246                 next unless ref($hash->{$k}) eq 'HASH' 
247                          && exists $hash->{$k}->{$CLASS_MARKER};
248                 $hash->{$k} = $OBJECT_HANDLERS{expand}->($hash->{$k}, @args);
249             }
250             $hash;            
251         }, 
252         collapse => sub {
253             my ( $hash, @args ) = @_;
254             # NOTE:         
255             # we need to make a copy cause
256             # otherwise it will affect the 
257             # other real version.
258             +{ map {
259                 blessed($hash->{$_})
260                     ? ($_ => $OBJECT_HANDLERS{collapse}->($hash->{$_}, @args))
261                     : ($_ => $hash->{$_})
262             } keys %$hash }            
263         } 
264     },
265     'Object'   => \%OBJECT_HANDLERS,
266     # NOTE:
267     # The sanity of enabling this feature by 
268     # default is very questionable.
269     # - SL
270     #'CodeRef' => {
271     #    expand   => sub {}, # use eval ...
272     #    collapse => sub {}, # use B::Deparse ...        
273     #} 
274 );
275
276 sub add_custom_type_handler {
277     my ($class, $type_name, %handlers) = @_;
278     (exists $handlers{expand} && exists $handlers{collapse})
279         || confess "Custom type handlers need an expand *and* a collapse method";
280     $TYPES{$type_name} = \%handlers;
281 }
282
283 sub remove_custom_type_handler {
284     my ($class, $type_name) = @_;
285     delete $TYPES{$type_name} if exists $TYPES{$type_name};
286 }
287
288 sub find_type_handler {
289     my ($self, $type_constraint) = @_;
290     
291     # this should handle most type usages
292     # since they they are usually just 
293     # the standard set of built-ins
294     return $TYPES{$type_constraint->name} 
295         if exists $TYPES{$type_constraint->name};
296       
297     # the next possibility is they are 
298     # a subtype of the built-in types, 
299     # in which case this will DWIM in 
300     # most cases. It is probably not 
301     # 100% ideal though, but until I 
302     # come up with a decent test case 
303     # it will do for now.
304     foreach my $type (keys %TYPES) {
305         return $TYPES{$type} 
306             if $type_constraint->is_subtype_of($type);
307     }
308     
309     # NOTE:
310     # the reason the above will work has to 
311     # do with the fact that custom subtypes
312     # are mostly used for validation of 
313     # the guts of a type, and not for some
314     # weird structural thing which would 
315     # need to be accomidated by the serializer.
316     # Of course, mst or phaylon will probably  
317     # do something to throw this assumption 
318     # totally out the door ;)
319     # - SL
320     
321     # NOTE:
322     # if this method hasnt returned by now
323     # then we have no been able to find a 
324     # type constraint handler to match 
325     confess "Cannot handle type constraint (" . $type_constraint->name . ")";    
326 }
327
328 1;
329
330 __END__
331
332 =pod
333
334 =head1 NAME
335
336 MooseX::Storage::Engine - The meta-engine to handle collapsing and expanding objects
337
338 =head1 DESCRIPTION
339
340 No user serviceable parts inside. If you really want to know, read the source :)
341
342 =head1 METHODS
343
344 =head2 Accessors
345
346 =over 4
347
348 =item B<class>
349
350 =item B<object>
351
352 =item B<storage>
353
354 =item B<seen>
355
356 =back
357
358 =head2 API
359
360 =over 4
361
362 =item B<expand_object>
363
364 =item B<collapse_object>
365
366 =back
367
368 =head2 ...
369
370 =over 4
371
372 =item B<collapse_attribute>
373
374 =item B<collapse_attribute_value>
375
376 =item B<expand_attribute>
377
378 =item B<expand_attribute_value>
379
380 =item B<check_for_cycle_in_collapse>
381
382 =item B<check_for_cycle_in_expansion>
383
384 =item B<map_attributes>
385
386 =back
387
388 =head2 Type Constraint Handlers
389
390 =over 4
391
392 =item B<find_type_handler>
393
394 =item B<add_custom_type_handler>
395
396 =item B<remove_custom_type_handler>
397
398 =back
399
400 =head2 Introspection
401
402 =over 4
403
404 =item B<meta>
405
406 =back
407
408 =head1 BUGS
409
410 All complex software has bugs lurking in it, and this module is no 
411 exception. If you find a bug please either email me, or add the bug
412 to cpan-RT.
413
414 =head1 AUTHOR
415
416 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
417
418 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
419
420 =head1 COPYRIGHT AND LICENSE
421
422 Copyright 2007 by Infinity Interactive, Inc.
423
424 L<http://www.iinteractive.com>
425
426 This library is free software; you can redistribute it and/or modify
427 it under the same terms as Perl itself.
428
429 =cut
430
431
432