Meerkat/Role/Document.pm untested

filter: Statementstmt 0.0% 0 / 167 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 264 CC 17 SCAR 27.8
CC
17
Cov
0%
_deep_field
72.0
update
12.0
__field_type
12.0
CRAP 16.0
1 use v5.10;
2 use strict;
3 use warnings;
4  
5 package Meerkat::Role::Document;
6 # ABSTRACT: Enhances a Moose object with Meerkat methods and metadata
7  
8 our $VERSION = '0.016';
9  
10 use Moose::Role 2;
11 use MooseX::AttributeShortcuts;
12 use MooseX::Storage;
13 use MooseX::Storage::Engine;
14  
15 use Carp qw/croak/;
16 use Scalar::Util qw/blessed/;
17 use Syntax::Keyword::Junction qw/any none/;
18 use BSON::OID;
19 use Type::Params qw/compile/;
20 use Types::Standard qw/slurpy :types/;
21 use Scalar::Util qw/looks_like_number/; # XXX crude but fast
22  
23 use namespace::autoclean;
24  
25 with Storage;
26  
27 # pass through OID's without modification as MongoDB will
28 # consume/provide them; pass through Meerkat::Collection
29 # as Meerkat will strip/add as necessary
30 for my $type (qw/BSON::OID Meerkat::Collection DateTime DateTime::Tiny/) {
31 MooseX::Storage::Engine->add_custom_type_handler(
32 $type => (
33 expand => sub { shift },
34 collapse => sub { shift },
35 )
36 );
37 }
38  
39 #pod =method new
40 #pod
41 #pod B<Don't call this directly!> Create objects through the
42 #pod L<Meerkat::Collection> or they won't be added to the database.
43 #pod
44 #pod my $obj = $person->create( name => "Joe" );
45 #pod
46 #pod =cut
47  
48 has _collection => (
49 is => 'ro',
50 isa => 'Meerkat::Collection',
51 required => 1,
52 );
53  
54 has _id => (
55 is => 'ro',
56 isa => 'BSON::OID',
57 default => sub { BSON::OID->new },
58 );
59  
60 has _removed => (
61 is => 'rw',
62 isa => 'Bool',
63 reader => 'is_removed',
64 writer => '_set_removed',
65 default => 0,
66 );
67  
68 #pod =method update
69 #pod
70 #pod $obj->update( { '$set' => { 'name' => "Moe" } } );
71 #pod
72 #pod Executes a MongoDB update command on the associated document and updates the
73 #pod object's attributes. You must only use MongoDB L<update
74 #pod operators|http://docs.mongodb.org/manual/reference/operator/nav-update/> to
75 #pod modify the document's fields.
76 #pod
77 #pod Returns true if the updates are applied and synchronized. If the document has
78 #pod been removed, the method returns false and the object is marked as removed;
79 #pod subsequent C<update>, C<sync> or C<remove> calls will do nothing and return
80 #pod false.
81 #pod
82 #pod This command is intended for custom updates with unusual logic or operators.
83 #pod Many typical updates can be accomplished with the C<update_*> methods described
84 #pod below.
85 #pod
86 #pod For all update methods, you can use a MongoDB nested field label to modify
87 #pod values deep into a data structure. For example C<parents.father> refers to
88 #pod C<< $obj->parents->{father} >>.
89 #pod
90 #pod =cut
91  
92 sub update {
93 state $check = compile( Object, HashRef );
94 my ( $self, $update ) = $check->(@_);
95 croak "The update method only accepts MongoDB update operators"
96 if grep { /^[^\$]/ } keys %$update;
97 return if $self->is_removed; # NOP
98 return $self->_collection->update( $self, $update );
99 }
100  
101 #pod =method update_set
102 #pod
103 #pod $obj->update_set( name => "Luke Skywalker" );
104 #pod
105 #pod Sets a field to a value. This is the MongoDB C<$set> operator.
106 #pod
107 #pod The field must be undefined or else the existing value and the new value must
108 #pod be of similar types (e.g. scalar or array or hash). For the purpose of this
109 #pod check, an object (e.g. a DateTime) is treated (opaquely) as a scalar value. If
110 #pod the types do not match, an error will be thrown.
111 #pod
112 #pod Note this means that you can't set a defined value to undefined. To remove a
113 #pod field entirely, see L</update_clear>. If you need to make other structural
114 #pod changes, do it manually with the L</update> method.
115 #pod
116 #pod Returns true if the update is applied and synchronized. If the document has
117 #pod been removed, the method returns false and the object is marked as removed.
118 #pod
119 #pod =cut
120  
121 sub update_set {
122 state $check = compile( Object, Defined, Defined );
123 my ( $self, $field, $value ) = $check->(@_);
124 $self->__check_op( $field, any(qw/undef scalar object ARRAY HASH/) );
125 my $type = $self->__field_type( $self->_deep_field($field) );
126 my $target_type = $self->__field_type($value);
127 croak "Can't use update_set to change $type field '$field' to $target_type"
128 if $type eq none(qw/undef object/) && $type ne $target_type;
129  
130 return $self->update( { '$set' => { "$field" => $value } } );
131 }
132  
133 #pod =method update_inc
134 #pod
135 #pod $obj->update_inc( likes => 1 );
136 #pod $obj->update_inc( likes => -1 );
137 #pod
138 #pod Increments a field by a positive or negative value. This is the MongoDB
139 #pod C<$inc> operator. The field must be undefined or a numeric scalar value
140 #pod or an error will be thrown.
141 #pod
142 #pod Returns true if the update is applied and synchronized. If the document has
143 #pod been removed, the method returns false and the object is marked as removed.
144 #pod
145 #pod =cut
146  
147 sub update_inc {
148 state $check = compile( Object, Defined, Defined );
149 my ( $self, $field, $value ) = $check->(@_);
150 $self->__check_op( $field, any(qw/undef scalar/) );
151 my $current = $self->$field;
152 croak "Can't use update_inc on non-numeric field '$field'"
153 if defined $current && !looks_like_number($current);
154 return $self->update( { '$inc' => { "$field" => $value } } );
155 }
156  
157 #pod =method update_push
158 #pod
159 #pod $obj->update_push( tags => qw/cool hot trendy/ );
160 #pod
161 #pod Pushes values onto an array reference field. This is the MongoDB C<$push>
162 #pod operator. The field must be undefined or an array reference or an error
163 #pod is thrown.
164 #pod
165 #pod Returns true if the update is applied and synchronized. If the document has
166 #pod been removed, the method returns false and the object is marked as removed.
167 #pod
168 #pod
169 #pod =cut
170  
171 sub update_push {
172 state $check = compile( Object, Defined, slurpy ArrayRef );
173 my ( $self, $field, $list ) = $check->(@_);
174 $self->__check_op( $field, any(qw/undef ARRAY/) );
175 return $self->update( { '$push' => { "$field" => { '$each' => $list } } } );
176 }
177  
178 #pod =method update_add
179 #pod
180 #pod $obj->update_add( tags => qw/cool hot trendy/ );
181 #pod
182 #pod Pushes values onto an array reference field, but only if they do not already
183 #pod exist in the array. This is the MongoDB C<$addToSet> operator. The field
184 #pod must be undefined or an array reference or an error is thrown.
185 #pod
186 #pod Returns true if the update is applied and synchronized. If the document has
187 #pod been removed, the method returns false and the object is marked as removed.
188 #pod
189 #pod =cut
190  
191 sub update_add {
192 state $check = compile( Object, Defined, slurpy ArrayRef );
193 my ( $self, $field, $list ) = $check->(@_);
194 $self->__check_op( $field, any(qw/undef ARRAY/) );
195 return $self->update( { '$addToSet' => { "$field" => { '$each' => $list } } } );
196 }
197  
198 #pod =method update_pop
199 #pod
200 #pod $obj->update_pop( 'tags' );
201 #pod
202 #pod Removes a value from the end of the array. This is the MongoDB C<$pop>
203 #pod operator with a direction of "1". The field must be undefined or an array
204 #pod reference or an error is thrown.
205 #pod
206 #pod Returns true if the update is applied and synchronized. If the document has
207 #pod been removed, the method returns false and the object is marked as removed.
208 #pod
209 #pod =cut
210  
211 sub update_pop {
212 state $check = compile( Object, Defined );
213 my ( $self, $field ) = $check->(@_);
214 $self->__check_op( $field, any(qw/undef ARRAY/) );
215 return $self->update( { '$pop' => { "$field" => 1 } } );
216 }
217  
218 #pod =method update_shift
219 #pod
220 #pod $obj->update_shift( 'tags' );
221 #pod
222 #pod Removes a value from the front of the array. This is the MongoDB C<$pop>
223 #pod operator with a direction of "-1". The field must be undefined or an array
224 #pod reference or an error is thrown.
225 #pod
226 #pod Returns true if the update is applied and synchronized. If the document has
227 #pod been removed, the method returns false and the object is marked as removed.
228 #pod
229 #pod
230 #pod =cut
231  
232 sub update_shift {
233 state $check = compile( Object, Defined );
234 my ( $self, $field ) = $check->(@_);
235 $self->__check_op( $field, any(qw/undef ARRAY/) );
236 return $self->update( { '$pop' => { "$field" => -1 } } );
237 }
238  
239 #pod =method update_remove
240 #pod
241 #pod $obj->update_remove( tags => qw/cool hot/ );
242 #pod
243 #pod Removes a list of values from the array. This is the MongoDB C<$pullAll>
244 #pod operator. The field must be undefined or an array reference or an error is
245 #pod thrown.
246 #pod
247 #pod Returns true if the update is applied and synchronized. If the document has
248 #pod been removed, the method returns false and the object is marked as removed.
249 #pod
250 #pod
251 #pod =cut
252  
253 sub update_remove {
254 state $check = compile( Object, Defined, slurpy ArrayRef );
255 my ( $self, $field, $list ) = $check->(@_);
256 $self->__check_op( $field, any(qw/undef ARRAY/) );
257 return $self->update( { '$pullAll' => { "$field" => $list } } );
258 }
259  
260 #pod =method update_clear
261 #pod
262 #pod $obj->update_clear( 'tags' );
263 #pod
264 #pod Removes a field from a document. This is the MongoDB C<$unset> operator.
265 #pod Returns true if the update is applied and synchronized. If the document has
266 #pod been removed, the method returns false and the object is marked as removed.
267 #pod
268 #pod Be sure not to clear any required fields.
269 #pod
270 #pod =cut
271  
272 sub update_clear {
273 state $check = compile( Object, Defined );
274 my ( $self, $field ) = $check->(@_);
275 $self->__check_op( $field, any(qw/undef scalar object ARRAY HASH/) );
276 return $self->update( { '$unset' => { "$field" => undef } } );
277 }
278  
279 #pod =method sync
280 #pod
281 #pod $obj->sync;
282 #pod
283 #pod Updates object attributes from the database. Returns true if synced. If the
284 #pod document has been removed, the method returns false and the object is marked as
285 #pod removed; subsequent C<update>, C<sync> or C<remove> calls will do nothing and
286 #pod return false.
287 #pod
288 #pod =cut
289  
290 sub sync {
291 state $check = compile(Object);
292 my ($self) = $check->(@_);
293 return $self->_collection->sync($self);
294 }
295  
296 #pod =method remove
297 #pod
298 #pod $obj->remove;
299 #pod
300 #pod Removes the associated document from the database. The object is marked as
301 #pod removed; subsequent C<update>, C<sync> or C<remove> calls will do nothing and
302 #pod return false.
303 #pod
304 #pod =method is_removed
305 #pod
306 #pod if ( $obj->is_removed ) { ... }
307 #pod
308 #pod Returns true or false indicating whether the associated document was removed
309 #pod from the database.
310 #pod
311 #pod =cut
312  
313 sub remove {
314 state $check = compile(Object);
315 my ($self) = $check->(@_);
316 return 1 if $self->is_removed; # NOP
317 return $self->_collection->remove($self);
318 }
319  
320 #pod =method reinsert
321 #pod
322 #pod $obj->reinsert;
323 #pod $obj->reinsert( force => 1 );
324 #pod
325 #pod Reinserts a removed document. If the C<force> option is true, then it will be
326 #pod reinserted even if the document has not been removed, overwriting any existing
327 #pod document in the database. Returns false if the document is not removed (unless
328 #pod the force option is true). Returns true if the document has been reinserted.
329 #pod
330 #pod =cut
331  
332 sub reinsert {
333 state $check = compile( Object, slurpy Dict [ force => Optional [Bool] ] );
334 my ( $self, $options ) = $check->(@_);
335 return if !$self->is_removed and !$options->{force}; # NOP
336 return $self->_collection->reinsert($self);
337 }
338  
339 #--------------------------------------------------------------------------#
340 # semi private methods
341 #--------------------------------------------------------------------------#
342  
343 #pod =method _indexes
344 #pod
345 #pod $class->_indexes;
346 #pod
347 #pod Returns an empty list. If you want to define indexes for use with the
348 #pod L<ensure_indexes|Meerkat::Collection/ensure_indexes> method of
349 #pod L<Meerkat::Collection>, create your own C<_indexes> method that returns a list
350 #pod of array references. The array references can have an optional initial hash
351 #pod reference of indexing options, followed by ordered key & value pairs in the
352 #pod usual MongoDB way.
353 #pod
354 #pod You must provide index fields in an array reference because Perl hashes are not
355 #pod ordered and a compound index requires an order.
356 #pod
357 #pod For example:
358 #pod
359 #pod sub _indexes {
360 #pod return (
361 #pod [ { unique => 1 }, name => 1 ],
362 #pod [ name => 1, zip_code => 1 ]
363 #pod [ likes => -1 ],
364 #pod [ location => '2dsphere' ],
365 #pod );
366 #pod }
367 #pod
368 #pod See the L<Meerkat::Cookbook> for more information.
369 #pod
370 #pod =cut
371  
372 sub _indexes { return }
373  
374 #pod =method _deep_field
375 #pod
376 #pod my $value = $obj->_deep_field( "parents.father" ); # hash key
377 #pod my $value = $obj->_deep_field( "tags.0" ); # array index
378 #pod
379 #pod Retrieves a field deep in the object's data structure using MongoDB's dot
380 #pod notation. Returns undef if the field does not exist. Throws an error if the
381 #pod dot notation would do an illegal dereference.
382 #pod
383 #pod This is far less efficient than accessing an attribute and dereferencing
384 #pod directly. It is used internally for validation of update_* field arguments.
385 #pod
386 #pod =cut
387  
388 sub _deep_field {
389 my ( $self, $field ) = @_;
390 my ( $head, @tail ) = split /\./, $field;
391 my $target = eval { $self->$head };
392 croak "Invalid attribute '$head'" if $@;
393 return unless defined $target;
394 while ( defined( my $p = shift @tail ) ) {
395 my $ref = ref $target;
396 if ( $ref eq 'ARRAY' ) {
397 croak
398 "Invalid subdocument '$head.$p': '$head' is an array but $p is not positive integer"
399 unless $p =~ /^\d+$/;
400 return if $p > $#{$target}; # doesn't exist yet
401 $target = $target->[$p];
402 }
403 elsif ( $ref eq 'HASH' ) {
404 return unless exists $target->{$p};
405 $target = $target->{$p};
406 }
407 else {
408 croak "Invalid subdocument '$head.$p': '$head' is not a reference";
409 }
410 $head .= ".$p";
411 }
412 return $target;
413 }
414  
415 #--------------------------------------------------------------------------#
416 # really private methods
417 #--------------------------------------------------------------------------#
418  
419 sub __check_op {
420 my ( $self, $field, $allowed ) = @_; # $allowed could be a junction
421 my $type = $self->__field_type( $self->_deep_field($field) );
422 unless ( $type eq $allowed ) {
423 my ( undef, undef, undef, $sub ) = caller(1);
424 $sub =~ s/.*::(\w+)$/$1/;
425 croak "Can't use $sub on $type field '$field'";
426 }
427 }
428  
429 sub __field_type {
430 my ( $self, $value ) = @_;
431 return 'undef' unless defined $value;
432 return 'object' if blessed($value);
433 return ref($value) || 'scalar';
434 }
435  
436 1;
437  
438  
439 # vim: ts=4 sts=4 sw=4 et:
440  
441 __END__