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