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