Mandel/Document.pm

filter: Statementstmt 64.0% 107 / 167 Branchbran 57.5% 38 / 66 Conditioncond 50.0% 7 / 14 MC/DCmcdc 22.2% 2 / 9 Subroutinesub 57.1% 24 / 42 Podpod 100% 13 / 13 totaltotal 61.4% 191 / 311 CC 42 SCAR 20.0
CC
42
Cov
62%
save
30.0
patch
20.0
set
14.4
CRAP 7.4
« Mandel/Collection.pm ↑ Summary andel.pm »
1 package Mandel::Document;
2 15 ▶use Mojo::Base 'Mojo::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
3 15 ▶use Mojo::JSON::Pointer;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 15 ▶use Mojo::Util 'monkey_patch';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use Mandel::Model;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 15 ▶use Mango::BSON ':bson';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 15 ▶use Scalar::Util 'looks_like_number';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 15 ▶use Carp 'confess';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 15 ▶use constant DEBUG => $ENV{MANDEL_CURSOR_DEBUG} ? eval 'require Data::Dumper;1' : 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
$ENV{'MANDEL_CURSOR_DEBUG'} ? : 0 15 15
10  
11 15 my $POINTER = Mojo::JSON::Pointer->new;
12  
13 10 ▶sub id {
Subroutine id: called CC=4 SCAR=13.9
Pod documented
14 10 my $self = shift;
15 10 my $raw = $self->data;
16  
17 10 ▶ if (@_) {
Branch: 2 branches
BranchTrueFalseTotal
if (@_) { } 3 7 10
elsif ($raw->{'_id'}) { } 5 2 7
18 3 $self->dirty->{_id} = 1;
19 3 ▶ $raw->{_id} = ref $_[0] ? $_[0] : bson_oid $_[0];
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 1 2 3
20 3 return $self;
21 }
22 elsif ($raw->{_id}) {
23 5 return $raw->{_id};
24 }
25 else {
26 2 $self->dirty->{_id} = 1;
27 2 return $raw->{_id} = bson_oid;
28 }
29 }
30  
31 0 ▶has connection => sub { confess "connection required in constructor" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
32 0 ▶has model => sub { confess "model required in constructor" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
33 3 ▶has dirty => sub { +{} };
Subroutine __ANON__: called CC=1 SCAR=0.0
34 15 has in_storage => 0;
35  
36 0 ▶has _storage_collection => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
37 0 my $self = shift;
38 0 $self->connection->_storage_collection($self->model->collection_name);
39 15 };
40  
41 9 ▶has data => sub { shift->_build_data }; # raw mongodb document data
Subroutine __ANON__: called CC=1 SCAR=0.0
42  
43 8 ▶sub _build_data { +{} }
Subroutine _build_data: called CC=1 SCAR=0.0
44  
45 14 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
46 14 my $self = shift->SUPER::new(@_);
47 14 ▶ $self->id(delete $self->{id}) if $self->{id};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"id"} 1 13 14
48 14 $self;
49 }
50  
51 1 ▶sub initialize {shift}
Subroutine initialize: called CC=1 SCAR=0.0
Pod documented
52  
53 3 ▶sub contains {
Subroutine contains: called CC=1 SCAR=0.0
Pod documented
54 3 my $self = shift;
55 3 $POINTER->data($self->data)->contains(@_);
56 }
57  
58 0 ▶sub fresh {
Subroutine fresh: not called CC=1 SCAR=6.9
Pod documented
59 0 $_[0]->{fresh} = 1;
60 0 $_[0];
61 }
62  
63 2 ▶sub get {
Subroutine get: called CC=1 SCAR=0.0
Pod documented
64 2 my $self = shift;
65 2 $POINTER->data($self->data)->get(@_);
66 }
67  
68 2 ▶sub is_changed {
Subroutine is_changed: called CC=3 SCAR=11.0
Pod documented
69 2 ▶ return 0 unless $_[0]->{dirty};
Branch: 1 branch
BranchTrueFalseTotal
unless $_[0]{"dirty"} 1 1 2
70 1 ▶ return 0 unless keys %{$_[0]->{dirty}};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$_[0]{"dirty"};} 0 1 1
71 1 return 1;
72 }
73  
74 0 ▶sub patch {
Subroutine patch: not called CC=4 SCAR=30.0
Pod documented
75 0 my ($self, $changes, $cb) = @_;
76 0 my $data = $self->data;
77  
78 0 ▶ if ($changes) {
Branch: 1 branch
BranchTrueFalseTotal
if ($changes) 0 0 0
79 0 @$data{keys %$changes} = values %$changes;
80 }
81  
82 0 $data = {%$data};
83 0 delete $data->{_id}; # Mod on _id not allowed
84  
85 $self->_storage_collection->update(
86 {_id => $self->id},
87 {'$set' => $data},
88 {upsert => bson_true},
89 $cb
90 ? (
91 0 ▶ sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
92 0 ▶ $self->_mark_stored_clean unless $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless $_[1] 0 0 0
93 0 $self->$cb($_[1]);
94 }
95 )
96 0 ▶ : (),
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 0 0 0
97 );
98  
99 0 ▶ $self->_mark_stored_clean unless $cb;
Branch: 1 branch
BranchTrueFalseTotal
unless $cb 0 0 0
100 0 $self;
101 }
102  
103 0 ▶sub remove {
Subroutine remove: not called CC=2 SCAR=17.9
Pod documented
104 0 my ($self, $cb) = @_;
105 0 my $c = $self->_storage_collection;
106 0 my @args = ({_id => $self->id}, {single => 1});
107  
108 0 warn "[$self\::remove] @{[$self->id]}\n" if DEBUG;
109  
110 0 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 0 0 0
111 $c->remove(
112 @args,
113 0 ▶ sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
114 0 my ($collection, $err, $doc) = @_;
115 0 ▶ $self->_mark_removed_dirty unless $err;
Branch: 1 branch
BranchTrueFalseTotal
unless $err 0 0 0
116 0 $self->$cb($err);
117 }
118 0 );
119 }
120 else {
121 0 $c->remove(@args);
122 0 $self->_mark_removed_dirty;
123 }
124  
125 0 return $self;
126 }
127  
128 0 ▶sub _mark_removed_dirty {
Subroutine _mark_removed_dirty: not called CC=2 SCAR=17.9
129 0 my $self = shift;
130 0 $self->dirty->{$_} = 1 for keys %{$self->data};
131 0 $self->in_storage(0);
132 }
133  
134 0 ▶sub save {
Subroutine save: not called CC=5 SCAR=34.0
Pod documented
135 0 my ($self, $cb) = @_;
136  
137 0 ▶ if (!$self->is_changed and $self->in_storage) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $self->is_changed and $self->in_storage) 0 0 0
Condition0%0/3
not $self->is_changed and $self->in_storage
!ll&&!rl&&r
000
MC/DC0%0/2
not $self->is_changed and $self->in_storage
not $self->is_changed $self->in_storage
Truth table0%0/3
not(A) and B
A= not $self->is_changedB= $self->in_storage
ABresult
0X0
100
111
138 0 ▶ $self->$cb('') if $cb;
Branch: 1 branch
BranchTrueFalseTotal
if $cb 0 0 0
139 0 return $self;
140 }
141  
142 0 $self->id; # make sure we have an ObjectID
143  
144 0 warn "[$self\::save] ", Data::Dumper->new([$self->data])->Indent(1)->Sortkeys(1)->Terse(1)->Dump if DEBUG;
145 0 my $c = $self->_storage_collection;
146  
147 0 ▶ if ($cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb) { } 0 0 0
148 $c->save(
149 $self->data,
150 0 ▶ sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
151 0 my ($collection, $err, $doc) = @_;
152 0 ▶ $self->_mark_stored_clean unless $err;
Branch: 1 branch
BranchTrueFalseTotal
unless $err 0 0 0
153 0 $self->$cb($err);
154 }
155 0 );
156 }
157 else {
158 0 $c->save($self->data);
159 0 $self->_mark_stored_clean;
160 }
161  
162 0 return $self;
163 }
164  
165 0 ▶sub _mark_stored_clean {
Subroutine _mark_stored_clean: not called CC=1 SCAR=6.9
166 0 my $self = shift;
167 0 delete $self->{dirty};
168 0 $self->in_storage(1);
169 }
170  
171 8 ▶sub set {
Subroutine set: called CC=14 SCAR=26.6
Pod documented
172 8 my ($self, $pointer, $val) = @_;
173 8 my $raw = $self->data;
174 8 my (@path, $field);
175  
176 8 ▶ return $self unless $pointer =~ s!^/!!;
Branch: 1 branch
BranchTrueFalseTotal
unless $pointer =~ s[^/][]u 0 8 8
177 8 @path = split '/', $pointer;
178 8 $field = $path[0];
179  
180 8 ▶ while (@path) {
Branch: 1 branch
BranchTrueFalseTotal
if (@path) 26 5 31
181 26 my $p = shift @path;
182 26 my $type = ref $raw;
183 26 ▶ my $want = looks_like_number $p ? 'INDEX' : 'KEY';
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($p) ? : 8 18 26
184  
185 26 ▶ if ($type eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'HASH') { } 16 10 26
elsif ($type eq 'ARRAY') { } 8 2 10
186 16 ▶ if (@path) {
Branch: 1 branch
BranchTrueFalseTotal
if (@path) { } 13 3 16
187 13 ▶ $raw = $raw->{$p} ||= looks_like_number $path[0] ? [] : {};
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($path[0]) ? : 1 0 1
Condition66%2/3
$raw->{$p} ||= &looks_like_number($path[0]) ? [] : {}
l!l&&r!l&&!r
1210
MC/DC0%0/2
$raw->{$p} ||= &looks_like_number($path[0]) ? [] : {}
$raw->{$p} &looks_like_number($path[0]) ? [] : {}
Truth table66%2/3
A ||= B
A= $raw->{$p}B= &looks_like_number($path[0]) ? [] : {}
ABresult
1X1
011
000
188 }
189 else {
190 3 $raw->{$p} = $val;
191 }
192 }
193 elsif ($type eq 'ARRAY') {
194 8 ▶ if ($want ne 'INDEX') {
Branch: 2 branches
BranchTrueFalseTotal
if ($want ne 'INDEX') { } 1 7 8
elsif (@path) { } 5 2 7
195 1 confess "Cannot set $want in $type for /$pointer ($p)";
196 }
197 elsif (@path) {
198 5 ▶ $raw = $raw->[$p] ||= looks_like_number $path[0] ? [] : {};
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($path[0]) ? : 0 2 2
Condition66%2/3
$raw->[$p] ||= &looks_like_number($path[0]) ? [] : {}
l!l&&r!l&&!r
320
MC/DC0%0/2
$raw->[$p] ||= &looks_like_number($path[0]) ? [] : {}
$raw->[$p] &looks_like_number($path[0]) ? [] : {}
Truth table66%2/3
A ||= B
A= $raw->[$p]B= &looks_like_number($path[0]) ? [] : {}
ABresult
1X1
011
000
199 }
200 else {
201 2 $raw->[$p] = $val;
202 }
203 }
204 else {
205 2 confess "Cannot set $want in SCALAR for /$pointer ($p)";
206 }
207 }
208  
209 5 ▶ $self->dirty->{$field} = 1 if defined $field;
Branch: 1 branch
BranchTrueFalseTotal
if defined $field 5 0 5
210 5 $self;
211 }
212  
213 13 ▶sub import {
Subroutine import: called CC=6 SCAR=18.1
214 13 my $class = shift;
215 13 ▶ my %args = @_ == 1 ? (name => shift) : @_;
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 ? : 3 10 13
216 13 my $caller = caller;
217 13 my $model = Mandel::Model->new(document_class => $caller, %args);
218 13 my $base_class = 'Mandel::Document';
219  
220 13 for (qw(name extends)) {
221 26 ▶ if ($args{$_} and $args{$_} =~ /::/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{$_} and $args{$_} =~ /::/u) 1 25 26
Condition100%3/3
$args{$_} and $args{$_} =~ /::/u
!ll&&!rl&&r
2321
MC/DC100%2/2
$args{$_} and $args{$_} =~ /::/u
$args{$_} $args{$_} =~ /::/u
Truth table100%3/3
A and B
A= $args{$_}B= $args{$_} =~ /::/u
ABresult
0X0
100
111
222 1 $base_class = delete $args{$_};
223 }
224 }
225 13 ▶ if (!$args{name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"name"}) 11 2 13
226 11 $args{name} = Mojo::Util::decamelize(($caller =~ /(\w+)$/)[0]);
227 11 $model->name($args{name});
228 }
229  
230 0 ▶ monkey_patch $caller, belongs_to => sub { $model->relationship(belongs_to => @_)->monkey_patch };
Subroutine __ANON__: not called CC=1 SCAR=2.6
Subroutine belongs_to: not called CC=1 SCAR=2.6
231 13 ▶ monkey_patch $caller, field => sub { $model->field(shift, {@_}) };
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine field: called CC=1 SCAR=0.0
232 0 ▶ monkey_patch $caller, has_many => sub { $model->relationship(has_many => @_)->monkey_patch };
Subroutine __ANON__: not called CC=1 SCAR=1.2
233 0 ▶ monkey_patch $caller, has_one => sub { $model->relationship(has_one => @_)->monkey_patch };
Subroutine __ANON__: not called CC=1 SCAR=1.2
234 0 ▶ monkey_patch $caller, list_of => sub { $model->relationship(list_of => @_)->monkey_patch };
Subroutine __ANON__: not called CC=1 SCAR=1.2
235 13 ▶ monkey_patch $caller, model => sub {$model};
Subroutine __ANON__: called CC=1 SCAR=0.0
236  
237 13 @_ = ($class, $base_class);
238 13 goto &Mojo::Base::import;
239 }
240  
241 1 ▶sub TO_JSON { shift->data }
Subroutine TO_JSON: called CC=1 SCAR=0.0
Pod documented
242  
243 5 ▶sub validate_fields {
Subroutine validate_fields: called CC=3 SCAR=11.0
Pod documented
244 5 my $self = shift;
245 5 ▶ if (ref $self->{data} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"data"} eq "HASH") 4 1 5
246 4 for (grep { $self->can($_) } keys %{ $self->{data} }) {
247 1 $self->$_($self->{data}{$_});
248 }
249 }
250 4 return $self;
251 }
252  
253 0 ▶sub _cache {
Subroutine _cache: not called CC=3 SCAR=24.8
254 0 my $self = shift;
255 0 ▶ my $cache = $self->{cache} ||= {};
Condition0%0/2
$self->{"cache"} ||= {}
l!l
00
MC/DC0%0/1
$self->{"cache"} ||= {}
$self->{"cache"}
Truth table0%0/2
A
A= $self->{"cache"}
Aresult
11
00
256  
257 0 ▶ return $cache->{$_[0]} if @_ == 1; # get
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 1 0 0 0
258 0 return $cache->{$_[0]} = $_[1]; # set
259 }
260  
261 15 1;
262  
263 =encoding utf8
264  
265 =head1 NAME
266  
267 Mandel::Document - A single MongoDB document with logic
268  
269 =head1 SYNOPSIS
270  
271 Extend a class with C<MyDocument::Class> instead of L<Mandel::Document>:
272  
273 package MyModel::Person;
274 use Mandel::Document "MyDocument::Class";
275  
276 Specify a default collection name, instead of the
277 L<default|Mandel::Model/collection>. L</import> will think you meant a base
278 class, if this argument contains "::".
279  
280 package MyModel::Person;
281 use Mandel::Document "some_collection_name";
282 use Types::Standard 'Str';
283  
284 field "foo";
285  
286 field "foo" => (
287 isa => Str,
288 builder => sub {
289 my $self = shift;
290 return "default value";
291 },
292 );
293  
294  
295 Spell out the options with a list:
296  
297 package MyModel::Person;
298  
299 use Mandel::Document (
300 extends => "My::Document::Class",
301 collection_name => "some_collection_name",
302 collection_class => "My::Custom::Collection",
303 );
304  
305 =head1 DESCRIPTION
306  
307 L<Mandel> is a simplistic model layer using the L<Mango> module to interact
308 with a MongoDB backend. The L<Mandel> class defines the overall model,
309 including high level interaction. Individual results, called Types inherit
310 from L<Mandel::Document>.
311  
312 An object of this class gets automatically serialized by L<Mojo::JSON>.
313 See L</TO_JSON> and L<Mojo::JSON#DESCRIPTION> for details.
314  
315 Example:
316  
317 use Mojolicious::Lite;
318 # ...
319 get '/some/resource' => sub {
320 my $c = shift;
321 # find some document...
322 $c->render(json => $mandel_doc_object);
323 };
324  
325 =head1 ATTRIBUTES
326  
327 L<Mandel> inherits all attributes from L<Mojo::Base> and implements the
328 following new ones.
329  
330 =head2 id
331  
332 $object_id = $self->id;
333 $self = $self->id("507f1f77bcf86cd799439011");
334 $self = $self->id(Mango::BSON::ObjectID->new);
335  
336 Returns the L<Mango::BSON::ObjectID> object for this document.
337 Will create one if it does not already exist.
338  
339 This can field can also be set.
340  
341 =head2 data
342  
343 $hash = $self->data;
344 $self = $self->data($hash);
345  
346 Holds the raw mongodb document. It is possible to define default values for
347 this attribute by defining L<builder|Mandel::Model::Field/builder> for the
348 fields.
349  
350 =head2 in_storage
351  
352 Boolean true if this document has been fetched from storage or L<saved|/save>
353 to storage.
354  
355 =head2 connection
356  
357 An instance of L<Mandel>. This is required.
358  
359 =head2 model
360  
361 Returns a L<Mandel::Model> object. This object is a class variable and
362 therefor shared between all instances.
363  
364 =head2 dirty
365  
366 This attribute holds a hash-ref where the keys are name of fields that has
367 been updated or otherwise not stored in database.
368  
369 TODO: Define what the values should hold. Timestamp? A counter for how
370 many times the field has been updated before saved..?
371  
372 =head1 METHODS
373  
374 L<Mandel::Document> inherits all of the methods from L<Mojo::Base> and
375 implements the following new ones.
376  
377 =head2 new
378  
379 Constructs a new object.
380  
381 =head2 initialize
382  
383 A no-op placeholder useful for initialization. See L<Mandel/initialize>.
384  
385 =head2 contains
386  
387 $bool = $self->contains('/json/2/pointer');
388  
389 Use L<Mojo::JSON::Pointer/contains> to check if a value exists inside the raw
390 mongodb document.
391  
392 =head2 fresh
393  
394 $self = $self->fresh;
395  
396 Calling this method will force the next relationship call to return fresh
397 data from database instead of cached. Example:
398  
399 $self->fresh->cats(sub {
400 my($self, $err, $cats) = @_;
401 });
402  
403 =head2 get
404  
405 $any = $self->get('/json/2/pointer');
406  
407 Use L<Mojo::JSON::Pointer/get> to retrieve a value inside the raw mongodb
408 document.
409  
410 =head2 is_changed
411  
412 Returns true if L</dirty> contains any field names.
413  
414 =head2 patch
415  
416 $self = $self->patch(\%changes, sub { my($self, $err) = @_ });
417 $self = $self->patch(\%changes);
418  
419 This method will insert/update a partial document. This is useful if C</data>
420 does not contain a complete document.
421  
422 It will also insert the document if a document with L</id> does not already
423 exist.
424  
425 =head2 remove
426  
427 $self = $self->remove(sub { my($self, $err) = @_; });
428 $self = $self->remove;
429  
430 Will remove this object from the L</collection> and set mark
431 all fields as L</dirty>.
432  
433 =head2 save
434  
435 $self = $self->save(sub { my($self, $err) = @_; });
436 $self = $self->save;
437  
438 This method stores the raw data in the database and collection. It clear
439 the L</dirty> attribute.
440  
441 NOTE: This method will call the callback (with $err set to empty string)
442 immediately unless L</is_changed> is true and L</in_storage> is false.
443  
444 =head2 set
445  
446 $self = $self->set('/json/2/pointer', $val);
447  
448 Use a JSON pointer to set data in the raw mongodb document. This method will
449 die if the pointer points to non-compatible data.
450  
451 =head2 import
452  
453 See L</SYNOPSIS>.
454  
455 =head2 TO_JSON
456  
457 Alias for L</data>.
458  
459 This method allow the document to get automatically serialized by
460 L<Mojo::JSON>.
461  
462 =head2 validate_fields
463  
464 $self = $self->validate_fields;
465  
466 This method can be used to validate the content of the fields of a document
467 againt the types defined in the model. It can be called after a document has
468 been loaded from MongoDB, e.g. via L<Mandel::Collection/single>. It can be
469 useful if the data in MongoDB might have been altered by something else after
470 it was stored there.
471  
472 =head1 SEE ALSO
473  
474 L<Mojolicious>, L<Mango>, L<Mandel>
475  
476 =head1 AUTHOR
477  
478 Jan Henning Thorsen - C<jhthorsen@cpan.org>
479  
480 =cut
« Mandel/Collection.pm ↑ Summary andel.pm »