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