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