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