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