Crop/Object/Collection.pm untested

filter: Statementstmt 0.0% 0 / 160 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 16 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 314 CC 35 SCAR 34.2
CC
35
Cov
0%
Hash
90.0
new
42.0
_map_out
42.0
CRAP 30.5
1 package Crop::Object::Collection;
2 use base qw/ Crop /;
3  
4 =begin nd
5 Class: Crop::Object::Collection
6 Container contains objects of the same class.
7  
8 All items of a Collection have the same state flags, so you need to use special methods
9 <Set_State ($flags )> and <Remove_State ($flags)> to change it.
10  
11 Common use of a Collection is <Crop::Object::All (@filter)>
12
13 This module do not inherits <Crop::Object>.
14
15 Attributes:
16  
17 elements - items
18 class - class name of items; has getter <Class>
19 simple - an array contains id for <Crop:::Object::Simple> descendents
20 state - has the same semantics as an object <Crop::Object>; inits by <Crop::Object::Constants::OBJINIT>
21 =cut
22  
23 use v5.14;
24 use warnings;
25  
26 use Scalar::Util qw/ blessed /;
27  
28 use Crop::Error;
29 use Crop::Util qw/ expose_hashes load_class /;
30 use Crop::Object::Constants;
31  
32 use Crop::Debug;
33  
34 =begin nd
35 Constructor: new ($bless, $obj)
36 Create a new collection of class $bless based on $obj data.
37  
38 Parameters:
39 $bless - items class name
40 $obj - hashes that contain source data for each item-object; optional
41  
42 Returns:
43 Collection - on success; empty Collection if $obj missed
44 undef - error
45 =cut
46 sub new {
47 my ($class, $bless, $obj) = @_;
48 $obj = [] unless defined $obj;
49
50 load_class($bless) or return warn "OBJECT|CRIT: Collection cannot load class $bless";
51  
52 my $is_simple = $bless->isa('Crop::Object::Simple');
53  
54 my (@id, @element);
55 for (@$obj) {
56 my $item = ref eq $bless ? $_ : $bless->new($_);
57  
58 push @element, $item;
59 push @id, $_->{id} if $is_simple;
60 }
61  
62 my $self = bless {
63 class => $bless,
64 elements => \@element,
65 state => OBJINIT,
66 }, $class;
67  
68 $self->{simple} = [] if $is_simple;
69 $self->{simple} = \@id if @id;
70  
71 $self;
72 }
73  
74 =begin nd
75 Method: Class ( )
76 Get the class name of a Collection.
77
78 Returns:
79 string - class name
80 =cut
81 sub Class { shift->{class} }
82  
83 =begin nd
84 Method: Cleanup ( )
85 Remove all the items from Collection.
86
87 Still alive items in the warehouse.
88 Returns:
89 $self
90 =cut
91 sub Cleanup {
92 my $self = shift;
93
94 $self->{elements} = [];
95 $self->{simple} = [] if exists $self->{simple};
96
97 $self;
98 }
99  
100 =begin nd
101 Method: Find (@filter)
102 Find all the elements of Collection that satisfy the @filter.
103
104 Despite lookup uses string searching, number attributes are processed fine,
105 when the 'eq' operator correctly compares digit.
106  
107 Parameters:
108 @filter - items in key position are names of class attributes and values are values for lookup;
109 will be exposed
110  
111 Returns:
112 Arrayref of items where indexes are in ascending order - if items was found
113 Empty arrayref - if no items found
114 =cut
115 sub Find {
116 my ($self, @filter) = @_;
117 my $filter = expose_hashes \@filter;
118  
119 my @found;
120 ITEM:
121 while (my ($i, $item) = each @{$self->{elements}}) {
122 exists
123 $item->{$_}
124 and
125 defined $item->{$_}
126 and
127 $item->{$_} eq $filter->{$_}
128 or next ITEM for keys %$filter;
129
130 push @found, $i;
131 }
132  
133 \@found;
134 }
135  
136 =begin nd
137 Method: First (@filter)
138 Get a first element of a Collection that satisfy @filter.
139
140 If no @filter specified, this method will return an item with index 0.
141 No checks for range will performed in this case.
142  
143 Parameters:
144 @filter - hash were keys are names of class attributes and values are values for lookup
145
146 Example:
147 > my $obj = $collection->Fist(id => 25, color => 'red', {smoke = 'yes'});
148  
149 Hashrefs in key positions will be exposed for @filter.
150  
151 Returns:
152 an object - if found
153 undef - otherwise
154 =cut
155 sub First {
156 my ($self, @filter) = @_;
157
158 return $self->{elements}[0] unless @filter;
159  
160 my $i = shift @{$self->Find(@filter)};
161  
162 # $i can has legal non-true value, either 0 or empty string
163 defined $i or return undef;
164  
165 $self->{elements}[$i];
166 }
167  
168 =begin nd
169 Method: Get ($ix)
170 Get element by index.
171  
172 Parameters:
173 $ix - index
174  
175 Returns:
176 item - if ok
177 undef - out of range
178 =cut
179 sub Get {
180 my ($self, $ix) = @_;
181  
182 $self->{elements}[$ix];
183 }
184  
185 =begin nd
186 Method: Hash ($key, $ix, $attr)
187 Get hash of items grouped to arrayrefs by $key.
188  
189 Special case is where no $key is specified and Colllection is a child of <Crop::Object::Simple>. Than,
190 'id' key will be used implicitly and method will return a hash with values in form of hashref instead
191 of arrayref.
192 If an 'id' key speicfied, method works as always.
193
194 > $collection->Hash('attr'); # result = {a1=>[], a2=>[]}
195 > $collection->Hash(); # result = {a1=>{}, a2=>{}}
196
197 The result of first call with the same key is stored in $self->{hash}{$key}. Next call will use this cache.
198
199 The $ix optional argument causes the resulting values to be a single object fetched from arrayref at $ix position.
200
201 If the call contains both, $ix and $attr, so result will be {one => $val} where $val is a value of attribute ($attr).
202 Use of $attr without $ix defined, is not yet implemented.
203  
204 Parameters:
205 $key - attribute name; values of the $key produce keys of resulting hash; if missed, 'id' assumed
206 $ix - optional; position (starting from 0) of the target object in arrayref to be returned
207 $attr - attribute name that value go to be the value of resultin hash.
208  
209 Returns:
210 hash of arrays, where keys are values of $key specified and values are arrays of items
211 > Hash(attr1)
212 {
213 one => [{attr1=>'one', attr2=>val00,...}, {attr1=>'one', attr2=>val01, ...}, ...],
214 two => [{attr1=>'two', attr2=>val10,...}, {attr1=>'two', attr2=>val11, ...}, ...],
215 ...,
216 }
217 hash of hash, where keys are the values of $key specified and values are hash of item at index $ix
218 > Hash(attr1, 0)
219 {
220 one => {attr1=>'one', attr2=>val00,...},
221 two => {attr1=>'two', attr2=>val10,...},
222 }
223 hash of value, where keys are the values of $key specified and values are value of $attr at index $ix (0)
224 > Hash(attr1, 0, attr2)
225 {
226 one => val00,
227 two => val10,
228 }
229 hash of value, where keys are the values of $key specified and values are value of $attr at index $ix (1)
230 > Hash(attr1, 1, attr2)
231 {
232 one => val01,
233 two => val11,
234 }
235 =cut
236 sub Hash {
237 my ($self, $key, $ix, $attr) = @_;
238  
239 my $is_flat; # would the values retrned directly without arrayref?
240 unless ($key) {
241 return warn "OBJECT|ALERT: Can't build 'hash-of-exemplar' for Collection of non-simple class: $self->{class}" unless exists $self->{simple};
242 $key = 'id';
243 $is_flat = 1;
244 }
245  
246 return $self->{hash}{$key} if exists $self->{hash}{$key};
247  
248 my %hash;
249 if ($is_flat) {
250 %hash = map +($_->{id} => $_), @{$self->{elements}};
251 } else {
252 for (@{$self->{elements}}) {
253 next unless defined $_->{$key};
254 push @{$hash{$_->{$key}}}, $_;
255 }
256 }
257  
258 if (defined $ix) {
259 while (my ($k, $v) = each %hash) {
260 $hash{$k} = defined $attr ?
261 $v->[$ix]->{$attr}
262 : $v->[$ix];
263 }
264 }
265  
266 $self->{hash}{$key} = \%hash unless defined $ix; # cache turn off
267
268 \%hash;
269 }
270  
271 =begin nd
272 Method: Is_empty
273 Is a Collection empty?
274  
275 Returns:
276 true - Collection is empty
277 false - Collection has at least one element
278 =cut
279 sub Is_empty { not @{+shift->{elements}} }
280  
281 =begin nd
282 Method: Last ( )
283 Get the last item of a Collection.
284
285 Returns:
286 An item - if the Collection is not empty
287 undef - otherwise
288 =cut
289 sub Last {
290 my $self = shift;
291
292 @{$self->{elements}} ? $self->{elements}[-1] : undef;
293 }
294  
295 =begin nd
296 Method: List ($id_marker)
297 Get items list.
298  
299 Parameters:
300 $id_marker - 'id' string specifies that only ids requested for <Crop::Object::Simple> descendent; optional
301  
302 Returns:
303 items arrayref - in scalar context
304 items array - in list context (for convenient)
305  
306 If $id_marker is 'id', the method returns ids only.
307  
308 Example:
309 > my $collection = My::Module->All(arg1=>val)->List;
310 > for ($collection->List) {...}
311 =cut
312 sub List {
313 my ($self, $id) = @_;
314  
315 return wantarray ? @{$self->{simple}} : $self->{simple} if $self->{class}->isa('Crop::Object::Simple') and $id and $id eq 'id';
316  
317 wantarray ? @{$self->{elements}} : $self->{elements};
318 }
319  
320 =begin nd
321 Method: Map (@map)
322 Compose the array of unblessed hashes based on the original items.
323
324 If @map is empty, will return the elements as-is.
325
326 (start code)
327 $collection->Map(
328 qw/ a1, a2, a3 /, # as is
329 {outVar => a4}, # a4 goes to outVar
330 {calcVar => sub { # calculate on each item of a Collection
331 my $item = shift;
332 $item + 2;
333 }},
334 );
335 (end code)
336  
337 Parameters:
338 @map - rules of tranformation for each resulting item
339
340 Single string means no tranformation required, an attribute transpasses to the result as is.
341  
342 Hashref means the value of an item presents tranformation rule. The string with dot performs
343 an access to the nested object(s). And subref will be executed with the entire item as a single argument.
344  
345 Returns:
346 arrayref of unblessed hashes - in a scalar context
347 array of unblessed hashed - in list context
348 =cut
349 sub Map {
350 my ($self, @map) = @_;
351
352 return $self->{elements} unless @map;
353  
354 my %output;
355 for (@map) {
356 if (ref eq 'HASH') {
357 my $cur = \%output;
358
359 while (my ($dst, $src) = each %$_) {
360 my @dst = split /\./, $dst;
361 while (my ($i, $name) = each @dst) {
362 if ($i < @dst - 1) { # not last
363 $cur = $cur->{$name}{inner} = {};
364 } else { # last
365 $cur->{$name}{src} = $src;
366 }
367 }
368 }
369 } else {
370 $output{$_}{src} = $_;
371 }
372 }
373
374 my $res = $self->_map_out(\%output);
375  
376 wantarray ? @$res : $res;
377 }
378  
379 =begin nd
380 Method: _map_out ($output)
381 Transform collection based on specified rules.
382  
383 For recursive use.
384
385 Parameters:
386 $output - hashref of rules
387
388 Returns:
389 arrayref of unblessed objects
390 =cut
391 sub _map_out {
392 my ($self, $output) = @_;
393
394 my @result;
395 for my $item (@{$self->{elements}}) {
396 push @result, { map {
397 if (exists $output->{$_} and exists $output->{$_}{inner}) {
398 $_ => $item->{$_}->_map_out($output->{$_}{inner});
399 } else {
400 my $src = $output->{$_}{src};
401
402 if (ref $src and ref $src eq 'CODE') {
403 $_ => $src->($item);
404 } elsif ($src =~ /\./) {
405 my @chain = split '\.', $src;
406 my $cur = $item;
407 while (my $accessor = shift @chain) {
408 $cur = $cur->{$accessor};
409 }
410
411 $_ => $cur;
412 } elsif (not defined $item->{$src}) {
413 $_ => undef;
414 } elsif (ref $item->{$src} and $item->{$src}->isa('Crop::Object::Collection')) {
415 $_ => scalar $item->{$src}->List;
416 } else {
417 $_ => $item->{$src};
418 }
419 }
420  
421 } keys %$output};
422 }
423
424 \@result;
425 }
426  
427 =begin nd
428 Method: Push ($src)
429 Insert new item(s) to the end of a Collection.
430  
431 Items get the same flags as the Collection has.
432  
433 Parameters:
434 $src - item or arrayref of items; item is a hashref
435  
436 Returns:
437 $self
438 =cut
439 sub Push {
440 my ($self, $src) = @_;
441 my @add = ref $src eq 'ARRAY' ? @$src : $src;
442  
443 for (@add) {
444 my $item;
445 if (blessed $_ and $_->isa($self->{class})) {
446 $item = $_;
447 } else {
448 $item = $self->{class}->new($_);
449 }
450
451 $item->Set_state($self->{state});
452  
453 push @{$self->{elements}}, $item;
454 push @{$self->{simple}}, $item->{id} if exists $self->{simple};
455 }
456  
457 $self;
458 }
459  
460 =begin nd
461 Method: Save ( )
462 Save all the elements to the warehouse.
463  
464 Actual version stores elements in 'one-by-one' fashion.
465  
466 Returns:
467 $self
468 =cut
469 sub Save {
470 my $self = shift;
471
472 return warn 'OBJECT|CRIT: Collection::Save() is only implemented for pure(0) state' if $self->{state};
473
474 my $id;
475 for (@{$self->{elements}}) {
476 $_->Save;
477 if ($self->{simple}) {
478 push @$id, $_->id;
479 }
480 }
481 $self->{simple} = $id if $id;
482
483 $self->{state} |= DWHLINK;
484
485 $self;
486 }
487  
488 =begin nd
489 Method: Set_state ($flags)
490 Set up flags for Collection and all their itmes.
491  
492 Parameters:
493 $flags - See <Crop::Object::Constants>
494  
495 Returns:
496 $self
497 =cut
498 sub Set_state {
499 my ($self, $flags) = @_;
500  
501 $self->{state} |= $flags;
502  
503 $_->Set_state($flags) for @{$self->{elements}};
504  
505 $self;
506 }
507  
508 =begin nd
509 Method: Size ( )
510 Get items number.
511  
512 Returns:
513 integer
514 =cut
515 sub Size { int @{+shift->{elements}} }
516  
517 1;