reworking tests
[gitmo/MooseX-Storage.git] / lib / MooseX / Storage / Engine.pm
1
2 package MooseX::Storage::Engine;
3 use Moose;
4
5 our $VERSION = '0.01';
6
7 # the class marker when 
8 # serializing an object. 
9 our $CLASS_MARKER = '__CLASS__';
10
11 has 'storage' => (
12     is      => 'rw',
13     isa     => 'HashRef',
14     default => sub {{}}
15 );
16
17 has 'object' => (is => 'rw', isa => 'Object');
18 has 'class'  => (is => 'rw', isa => 'Str');
19
20 ## this is the API used by other modules ...
21
22 sub collapse_object {
23         my $self = shift;
24     $self->map_attributes('collapse_attribute');
25     $self->storage->{$CLASS_MARKER} = $self->object->meta->name;    
26         return $self->storage;
27 }
28
29 sub expand_object {
30     my ($self, $data) = @_;
31     $self->map_attributes('expand_attribute', $data);
32         return $self->storage;    
33 }
34
35 ## this is the internal API ...
36
37 sub collapse_attribute {
38     my ($self, $attr)  = @_;
39     $self->storage->{$attr->name} = $self->collapse_attribute_value($attr) || return;
40 }
41
42 sub expand_attribute {
43     my ($self, $attr, $data)  = @_;
44     $self->storage->{$attr->name} = $self->expand_attribute_value($attr, $data->{$attr->name}) || return;
45 }
46
47 sub collapse_attribute_value {
48     my ($self, $attr)  = @_;
49         my $value = $attr->get_value($self->object);
50     if (defined $value && $attr->has_type_constraint) {
51         my $type_converter = $self->find_type_handler($attr->type_constraint);
52         (defined $type_converter)
53             || confess "Cannot convert " . $attr->type_constraint->name;
54         $value = $type_converter->{collapse}->($value);
55     }
56         return $value;
57 }
58
59 sub expand_attribute_value {
60     my ($self, $attr, $value)  = @_;
61     if (defined $value && $attr->has_type_constraint) {
62         my $type_converter = $self->find_type_handler($attr->type_constraint);
63         $value = $type_converter->{expand}->($value);
64     }
65         return $value;
66 }
67
68 # util methods ...
69
70 sub map_attributes {
71     my ($self, $method_name, @args) = @_;
72     map { 
73         $self->$method_name($_, @args) 
74     } ($self->object || $self->class)->meta->compute_all_applicable_attributes;
75 }
76
77 ## ------------------------------------------------------------------
78 ## This is all the type handler stuff, it is in a state of flux
79 ## right now, so this may change, or it may just continue to be 
80 ## improved upon. Comments and suggestions are welcomed.
81 ## ------------------------------------------------------------------
82
83 # NOTE:
84 # these are needed by the 
85 # ArrayRef and HashRef handlers
86 # below, so I need easy access 
87 my %OBJECT_HANDLERS = (
88     expand => sub {
89         my $data = shift;   
90         (exists $data->{$CLASS_MARKER})
91             || confess "Serialized item has no class marker";
92         $data->{$CLASS_MARKER}->unpack($data);
93     },
94     collapse => sub {
95         my $obj = shift;
96         ($obj->can('does') && $obj->does('MooseX::Storage::Basic'))
97             || confess "Bad object ($obj) does not do MooseX::Storage::Basic role";
98         $obj->pack();
99     },
100 );
101
102
103 my %TYPES = (
104     # These are boring ones, so they use the identity function ...
105     'Int'      => { expand => sub { shift }, collapse => sub { shift } },
106     'Num'      => { expand => sub { shift }, collapse => sub { shift } },
107     'Str'      => { expand => sub { shift }, collapse => sub { shift } },
108     # These are the trickier ones, (see notes)
109     # NOTE:
110     # Because we are nice guys, we will check 
111     # your ArrayRef and/or HashRef one level 
112     # down and inflate any objects we find. 
113     # But this is where it ends, it is too
114     # expensive to try and do this any more  
115     # recursively, when it is probably not 
116     # nessecary in most of the use cases.
117     # However, if you need more then this, subtype 
118     # and add a custom handler.    
119     'ArrayRef' => { 
120         expand => sub {
121             my $array = shift;
122             foreach my $i (0 .. $#{$array}) {
123                 next unless ref($array->[$i]) eq 'HASH' 
124                          && exists $array->[$i]->{$CLASS_MARKER};
125                 $array->[$i] = $OBJECT_HANDLERS{expand}->($array->[$i])
126             }
127             $array;
128         }, 
129         collapse => sub { 
130             my $array = shift;   
131             # NOTE:         
132             # we need to make a copy cause
133             # otherwise it will affect the 
134             # other real version.
135             [ map {
136                 blessed($_)
137                     ? $OBJECT_HANDLERS{collapse}->($_)
138                     : $_
139             } @$array ] 
140         } 
141     },
142     'HashRef'  => { 
143         expand   => sub {
144             my $hash = shift;
145             foreach my $k (keys %$hash) {
146                 next unless ref($hash->{$k}) eq 'HASH' 
147                          && exists $hash->{$k}->{$CLASS_MARKER};
148                 $hash->{$k} = $OBJECT_HANDLERS{expand}->($hash->{$k})
149             }
150             $hash;            
151         }, 
152         collapse => sub {
153             my $hash = shift;   
154             # NOTE:         
155             # we need to make a copy cause
156             # otherwise it will affect the 
157             # other real version.
158             +{ map {
159                 blessed($hash->{$_})
160                     ? ($_ => $OBJECT_HANDLERS{collapse}->($hash->{$_}))
161                     : ($_ => $hash->{$_})
162             } keys %$hash }            
163         } 
164     },
165     'Object'   => \%OBJECT_HANDLERS,
166     # NOTE:
167     # The sanity of enabling this feature by 
168     # default is very questionable.
169     # - SL
170     #'CodeRef' => {
171     #    expand   => sub {}, # use eval ...
172     #    collapse => sub {}, # use B::Deparse ...        
173     #}       
174 );
175
176 sub add_custom_type_handler {
177     my ($class, $type_name, %handlers) = @_;
178     (exists $handlers{expand} && exists $handlers{collapse})
179         || confess "Custom type handlers need an expand *and* a collapse method";
180     $TYPES{$type_name} = \%handlers;
181 }
182
183 sub remove_custom_type_handler {
184     my ($class, $type_name) = @_;
185     delete $TYPES{$type_name} if exists $TYPES{$type_name};
186 }
187
188 sub find_type_handler {
189     my ($self, $type_constraint) = @_;
190     
191     # this should handle most type usages
192     # since they they are usually just 
193     # the standard set of built-ins
194     return $TYPES{$type_constraint->name} 
195         if exists $TYPES{$type_constraint->name};
196       
197     # the next possibility is they are 
198     # a subtype of the built-in types, 
199     # in which case this will DWIM in 
200     # most cases. It is probably not 
201     # 100% ideal though, but until I 
202     # come up with a decent test case 
203     # it will do for now.
204     foreach my $type (keys %TYPES) {
205         return $TYPES{$type} 
206             if $type_constraint->is_subtype_of($type);
207     }
208     
209     # NOTE:
210     # the reason the above will work has to 
211     # do with the fact that custom subtypes
212     # are mostly used for validation of 
213     # the guts of a type, and not for some
214     # weird structural thing which would 
215     # need to be accomidated by the serializer.
216     # Of course, mst or phaylon will probably  
217     # do something to throw this assumption 
218     # totally out the door ;)
219     # - SL
220     
221     # NOTE:
222     # if this method hasnt returned by now
223     # then we have no been able to find a 
224     # type constraint handler to match 
225     confess "Cannot handle type constraint (" . $type_constraint->name . ")";    
226 }
227
228 1;
229
230 __END__
231
232 =pod
233
234 =head1 NAME
235
236 MooseX::Storage::Engine
237
238 =head1 SYNOPSIS
239
240 =head1 DESCRIPTION
241
242 =head1 METHODS
243
244 =head2 Accessors
245
246 =over 4
247
248 =item B<class>
249
250 =item B<object>
251
252 =item B<storage>
253
254 =back
255
256 =head2 API
257
258 =over 4
259
260 =item B<expand_object>
261
262 =item B<collapse_object>
263
264 =back
265
266 =head2 ...
267
268 =over 4
269
270 =item B<collapse_attribute>
271
272 =item B<collapse_attribute_value>
273
274 =item B<expand_attribute>
275
276 =item B<expand_attribute_value>
277
278 =item B<map_attributes>
279
280 =back
281
282 =head2 Type Constraint Handlers
283
284 =over 4
285
286 =item B<find_type_handler>
287
288 =item B<add_custom_type_handler>
289
290 =item B<remove_custom_type_handler>
291
292 =back
293
294 =head2 Introspection
295
296 =over 4
297
298 =item B<meta>
299
300 =back
301
302 =head1 BUGS
303
304 All complex software has bugs lurking in it, and this module is no 
305 exception. If you find a bug please either email me, or add the bug
306 to cpan-RT.
307
308 =head1 AUTHOR
309
310 Chris Prather E<lt>chris.prather@iinteractive.comE<gt>
311
312 Stevan Little E<lt>stevan.little@iinteractive.comE<gt>
313
314 =head1 COPYRIGHT AND LICENSE
315
316 Copyright 2007 by Infinity Interactive, Inc.
317
318 L<http://www.iinteractive.com>
319
320 This library is free software; you can redistribute it and/or modify
321 it under the same terms as Perl itself.
322
323 =cut
324
325
326