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