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