blib/lib/Class/MakeMethods/Composite/Array.pm untested

filter: Statementstmt 0.0% 0 / 206 Branchbran 0.0% 0 / 58 Conditioncond 0.0% 0 / 62 MC/DCmcdc 0.0% 0 / 40 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 386 CC 3 SCAR 13.5
CC
3
Cov
0%
_array_index
12.0
new
2.0
scalar
2.0
CRAP 3.9
1 =head1 NAME
2  
3 Class::MakeMethods::Composite::Array - Basic array methods
4  
5 =head1 SYNOPSIS
6  
7 package MyObject;
8 use Class::MakeMethods::Composite::Array (
9 new => 'new',
10 scalar => [ 'foo', 'bar' ],
11 array => 'my_list',
12 hash => 'my_index',
13 );
14 ...
15
16 my $obj = MyObject->new( foo => 'Foozle' );
17 print $obj->foo();
18
19 $obj->bar('Barbados');
20 print $obj->bar();
21
22 $obj->my_list(0 => 'Foozle', 1 => 'Bang!');
23 print $obj->my_list(1);
24
25 $obj->my_index('broccoli' => 'Blah!', 'foo' => 'Fiddle');
26 print $obj->my_index('foo');
27  
28 =head1 DESCRIPTION
29  
30 The Composite::Array suclass of MakeMethods provides a basic
31 constructor and accessors for blessed-array object instances.
32  
33 =head2 Class::MakeMethods Calling Conventions
34  
35 When you C<use> this package, the method declarations you provide
36 as arguments cause subroutines to be generated and installed in
37 your module.
38  
39 You can also omit the arguments to C<use> and instead make methods
40 at runtime by passing the declarations to a subsequent call to
41 C<make()>.
42  
43 You may include any number of declarations in each call to C<use>
44 or C<make()>. If methods with the same name already exist, earlier
45 calls to C<use> or C<make()> win over later ones, but within each
46 call, later declarations superceed earlier ones.
47  
48 You can install methods in a different package by passing C<-TargetClass =E<gt> I<package>> as your first arguments to C<use> or C<make>.
49  
50 See L<Class::MakeMethods> for more details.
51  
52 =head2 Class::MakeMethods::Basic Declaration Syntax
53  
54 The following types of Basic declarations are supported:
55  
56 =over 4
57  
58 =item *
59  
60 I<generator_type> => "I<method_name>"
61  
62 =item *
63  
64 I<generator_type> => "I<name_1> I<name_2>..."
65  
66 =item *
67  
68 I<generator_type> => [ "I<name_1>", "I<name_2>", ...]
69  
70 =back
71  
72 See the "METHOD GENERATOR TYPES" section below for a list of the supported values of I<generator_type>.
73  
74 For each method name you provide, a subroutine of the indicated
75 type will be generated and installed under that name in your module.
76  
77 Method names should start with a letter, followed by zero or more
78 letters, numbers, or underscores.
79  
80 =head2 Class::MakeMethods::Composite Declaration Syntax
81  
82 The Composite syntax also provides several ways to optionally
83 associate a hash of additional parameters with a given method
84 name.
85  
86 =over 4
87  
88 =item *
89  
90 I<generator_type> => [ "I<name_1>" => { I<param>=>I<value>... }, ... ]
91  
92 A hash of parameters to use just for this method name.
93  
94 (Note: to prevent confusion with self-contained definition hashes,
95 described below, parameter hashes following a method name must not
96 contain the key 'name'.)
97  
98 =item *
99  
100 I<generator_type> => [ [ "I<name_1>", "I<name_2>", ... ] => { I<param>=>I<value>... } ]
101  
102 Each of these method names gets a copy of the same set of parameters.
103  
104 =item *
105  
106 I<generator_type> => [ { "name"=>"I<name_1>", I<param>=>I<value>... }, ... ]
107  
108 By including the reserved parameter C<name>, you create a self
109 contained declaration with that name and any associated hash values.
110  
111 =back
112  
113 Basic declarations, as described above, are treated as having an empty parameter hash.
114  
115 =cut
116  
117 package Class::MakeMethods::Composite::Array;
118  
119 $VERSION = 1.000;
120 use strict;
121 use Class::MakeMethods::Composite '-isasubclass';
122  
123 ########################################################################
124  
125 =head2 Positional Accessors and %FIELDS
126  
127 Each accessor method is assigned the next available array index at
128 which to store its value.
129  
130 The mapping between method names and array positions is stored in
131 a hash named %FIELDS in the declaring package. When a package
132 declares its first positional accessor, its %FIELDS are initialized
133 by searching its inheritance tree.
134  
135 B<Warning>: Subclassing packages that use positional accessors is
136 somewhat fragile, since you may end up with two distinct methods assigned to the same position. Specific cases to avoid are:
137  
138 =over 4
139  
140 =item *
141  
142 If you inherit from more than one class with positional accessors,
143 the positions used by the two sets of methods will overlap.
144  
145 =item *
146  
147 If your superclass adds additional positional accessors after you
148 declare your first, they will overlap yours.
149  
150 =back
151  
152 =cut
153  
154 sub _array_index {
155 my $class = shift;
156 my $name = shift;
157 no strict;
158 local $^W = 0;
159 if ( ! scalar %{$class . "::FIELDS"} ) {
160 my @classes = @{$class . "::ISA"};
161 my @fields;
162 while ( @classes ) {
163 my $superclass = shift @classes;
164 if ( scalar %{$superclass . "::FIELDS"} ) {
165 push @fields, %{$superclass . "::FIELDS"};
166 } else {
167 unshift @classes, @{$superclass . "::ISA"}
168 }
169 }
170 %{$class . "::FIELDS"} = @fields
171 }
172 my $field_hash = \%{$class . "::FIELDS"};
173 $field_hash->{$name} or $field_hash->{$name} = scalar keys %$field_hash
174 }
175  
176 ########################################################################
177  
178 =head1 METHOD GENERATOR TYPES
179  
180 =head2 new - Constructor
181  
182 For each method name passed, returns a subroutine with the following characteristics:
183  
184 =over 4
185  
186 =item *
187  
188 Has a reference to a sample item to copy. This defaults to a reference to an empty array, but you may override this with the C<'defaults' => I<array_ref>> method parameter.
189  
190 =item *
191  
192 If called as a class method, makes a new array containing values from the sample item, and blesses it into that class.
193  
194 =item *
195  
196 If called on an array-based instance, makes a copy of it and blesses the copy into the same class as the original instance.
197  
198 =item *
199  
200 If passed a list of method-value pairs, calls each named method with the associated value as an argument.
201  
202 =item *
203  
204 Returns the new instance.
205  
206 =back
207  
208 Sample declaration and usage:
209  
210 package MyObject;
211 use Class::MakeMethods::Composite::Array (
212 new => 'new',
213 );
214 ...
215
216 # Bare constructor
217 my $empty = MyObject->new();
218
219 # Constructor with initial sequence of method calls
220 my $obj = MyObject->new( foo => 'Foozle', bar => 'Barbados' );
221
222 # Copy with overriding sequence of method calls
223 my $copy = $obj->new( bar => 'Bob' );
224  
225 =cut
226  
227 use vars qw( %ConstructorFragments );
228  
229 sub new {
230 (shift)->_build_composite( \%ConstructorFragments, @_ );
231 }
232  
233 %ConstructorFragments = (
234 '' => [
235 '+init' => sub {
236 my $method = pop @_;
237 $method->{target_class} ||= $Class::MethodMaker::CONTEXT{TargetClass};
238 $method->{defaults} ||= [];
239 },
240 'do' => sub {
241 my $method = pop @_;
242 my $self = shift @_;
243 my $obj = ref($self) ? bless( [ @$self ], ref $self )
244 : bless( { @[$method->{defaults}] }, $self );
245 @_ = %{$_[0]}
246 if ( scalar @_ == 1 and ref $_[0] eq 'HASH' );
247 while ( scalar @_ ) {
248 my $method = shift @_;
249 $obj->$method( shift @_ );
250 }
251 $obj;
252 },
253 ],
254 'with_values' => [
255 'do' => sub {
256 my $method = pop @_;
257 my $self = shift @_;
258 @_ = @[$_[0]]
259 if ( scalar @_ == 1 and ref $_[0] eq 'ARRAY' );
260 bless( [ @_ ], ref($self) || $self );
261 }
262 ],
263 );
264  
265 ########################################################################
266  
267 =head2 new_with_values - Constructor
268  
269 For each method name passed, returns a subroutine with the following characteristics:
270  
271 =over 4
272  
273 =item *
274  
275 May be called as a class method, or (equivalently) on any existing object of that class.
276  
277 =item *
278  
279 Creates an array, blesses it into the class, and returns the new instance.
280  
281 =item *
282  
283 If no arguments are provided, the returned array will be empty. If passed a single array-ref argument, copies its contents into the new array. If called with multiple arguments, copies them into the new array. (Note that this is a "shallow" copy, not a "deep" clone.)
284  
285 =back
286  
287 Sample declaration and usage:
288  
289 package MyObject;
290 use Class::MakeMethods::Composite::Array (
291 new => 'new',
292 );
293 ...
294
295 # Bare constructor
296 my $empty = MyObject->new();
297
298 # Constructor with initial sequence of method calls
299 my $obj = MyObject->new( foo => 'Foozle', bar => 'Barbados' );
300
301 # Copy with overriding sequence of method calls
302 my $copy = $obj->new( bar => 'Bob' );
303  
304 =cut
305  
306 ########################################################################
307  
308 =head2 scalar - Instance Accessor
309  
310 For each method name passed, uses a closure to generate a subroutine with the following characteristics:
311  
312 =over 4
313  
314 =item *
315  
316 Must be called on an array-based instance.
317  
318 =item *
319  
320 Determines the array position associated with the method name, and uses that as an index into each instance to access the related value. This defaults to the next available slot in %FIELDS, but you may override this with the C<'array_index' => I<number>> method parameter, or by pre-filling the contents of %FIELDS.
321  
322 =item *
323  
324 If called without any arguments returns the current value (or undef).
325  
326 =item *
327  
328 If called with an argument, stores that as the value, and returns it,
329  
330 =item *
331  
332 If called with multiple arguments, stores a reference to a new array with those arguments as contents, and returns that array reference.
333  
334 =back
335  
336 Sample declaration and usage:
337  
338 package MyObject;
339 use Class::MakeMethods::Composite::Array (
340 scalar => 'foo',
341 );
342 ...
343
344 # Store value
345 $obj->foo('Foozle');
346
347 # Retrieve value
348 print $obj->foo;
349  
350 =cut
351  
352 use vars qw( %ScalarFragments );
353  
354 sub scalar {
355 (shift)->_build_composite( \%ScalarFragments, @_ );
356 }
357  
358 %ScalarFragments = (
359 '' => [
360 '+init' => sub {
361 my ($method) = @_;
362 $method->{target_class} ||= $Class::MethodMaker::CONTEXT{TargetClass};
363 $method->{array_index} ||=
364 _array_index( $method->{target_class}, $name );
365 },
366 'do' => sub {
367 my $method = pop @_;
368 my $self = shift @_;
369 if ( scalar(@_) == 0 ) {
370 $self->[$method->{array_index}];
371 } elsif ( scalar(@_) == 1 ) {
372 $self->[$method->{array_index}] = shift;
373 } else {
374 $self->[$method->{array_index}] = [@_];
375 }
376 },
377 ],
378 'rw' => [],
379 'p' => [
380 '+pre' => sub {
381 my $method = pop @_;
382 my $self = shift @_;
383 my $args = \@_;
384 unless ( UNIVERSAL::isa((caller(1))[0], $method->{target_class}) ) {
385 croak "Method $method->{name} is protected";
386 }
387 },
388 ],
389 'pp' => [
390 '+pre' => sub {
391 my $method = pop @_;
392 my $self = shift @_;
393 my $args = \@_;
394 unless ( (caller(1))[0] eq $method->{target_class} ) {
395 croak "Method $method->{name} is private";
396 }
397 },
398 ],
399 'pw' => [
400 '+pre' => sub {
401 my $method = pop @_;
402 my $self = shift @_;
403 my $args = \@_;
404 unless ( @$args == 0 or UNIVERSAL::isa((caller(1))[0], $method->{target_class}) ) {
405 croak "Method $method->{name} is write-protected";
406 }
407 },
408 ],
409 'ppw' => [
410 '+pre' => sub {
411 my $method = pop @_;
412 my $self = shift @_;
413 my $args = \@_;
414 unless ( @$args == 0 or (caller(1))[0] eq $method->{target_class} ) {
415 croak "Method $method->{name} is write-private";
416 }
417 },
418 ],
419 'r' => [
420 '+pre' => sub {
421 my $method = pop @_;
422 my $self = shift @_;
423 my $args = \@_;
424 @$args = ();
425 },
426 ],
427 'ro' => [
428 '+pre' => sub {
429 my $method = pop @_;
430 my $self = shift @_;
431 my $args = \@_;
432 unless ( @$args == 0 ) {
433 croak("Method $method->{name} is read-only");
434 }
435 },
436 ],
437 'wo' => [
438 '+pre' => sub {
439 my $method = pop @_;
440 my $self = shift @_;
441 my $args = \@_;
442 if ( @$args == 0 ) {
443 croak("Method $method->{name} is write-only");
444 }
445 },
446 ],
447 'return_original' => [
448 '+pre' => sub {
449 my $method = pop @_;
450 my $self = shift @_;
451 my $args = \@_;
452 $method->{scratch}{return_original} = $self->[$method->{array_index}];
453 },
454 '+post' => sub {
455 my $method = pop @_;
456 my $self = shift @_;
457 my $args = \@_;
458 $method->{result} = \{ $method->{scratch}{return_original} };
459 },
460 ],
461 );
462  
463 ########################################################################
464  
465 =head2 array - Instance Ref Accessor
466  
467 For each method name passed, uses a closure to generate a subroutine with the following characteristics:
468  
469 =over 4
470  
471 =item *
472  
473 Must be called on an array-based instance.
474  
475 =item *
476  
477 Determines the array position associated with the method name, and uses that as an index into each instance to access the related value. This defaults to the next available slot in %FIELDS, but you may override this with the C<'array_index' => I<number>> method parameter, or by pre-filling the contents of %FIELDS.
478  
479 =item *
480  
481 The value for each instance will be a reference to an array (or undef).
482  
483 =item *
484  
485 If called without any arguments, returns the current array-ref value (or undef).
486  
487 =item *
488  
489 If called with a single non-ref argument, uses that argument as an index to retrieve from the referenced array, and returns that value (or undef).
490  
491 =item *
492  
493 If called with a single array ref argument, uses that list to return a slice of the referenced array.
494  
495 =item *
496  
497 If called with a list of argument pairs, each with a non-ref index and an associated value, stores the value at the given index in the referenced array. If the instance's value was previously undefined, a new array is autovivified. The current value in each position will be overwritten, and later arguments with the same index will override earlier ones. Returns the current array-ref value.
498  
499 =item *
500  
501 If called with a list of argument pairs, each with the first item being a reference to an array of up to two numbers, loops over each pair and uses those numbers to splice the value array.
502  
503 The first controlling number is the position at which the splice will begin. Zero will start before the first item in the list. Negative numbers count backwards from the end of the array.
504  
505 The second number is the number of items to be removed from the list. If it is omitted, or undefined, or zero, no items are removed. If it is a positive integer, that many items will be returned.
506  
507 If both numbers are omitted, or are both undefined, they default to containing the entire value array.
508  
509 If the second argument is undef, no values will be inserted; if it is a non-reference value, that one value will be inserted; if it is an array-ref, its values will be copied.
510  
511 The method returns the items that removed from the array, if any.
512  
513 =back
514  
515 Sample declaration and usage:
516
517 package MyObject;
518 use Class::MakeMethods::Composite::Array (
519 array => 'bar',
520 );
521 ...
522
523 # Clear and set contents of list
524 print $obj->bar([ 'Spume', 'Frost' ] );
525
526 # Set values by position
527 $obj->bar(0 => 'Foozle', 1 => 'Bang!');
528
529 # Positions may be overwritten, and in any order
530 $obj->bar(2 => 'And Mash', 1 => 'Blah!');
531
532 # Retrieve value by position
533 print $obj->bar(1);
534
535 # Direct access to referenced array
536 print scalar @{ $obj->bar() };
537  
538 There are also calling conventions for slice and splice operations:
539  
540 # Retrieve slice of values by position
541 print join(', ', $obj->bar( undef, [0, 2] ) );
542
543 # Insert an item at position in the array
544 $obj->bar([3], 'Potatoes' );
545
546 # Remove 1 item from position 3 in the array
547 $obj->bar([3, 1], undef );
548
549 # Set a new value at position 2, and return the old value
550 print $obj->bar([2, 1], 'Froth' );
551  
552 =cut
553  
554  
555 use vars qw( %ArrayFragments );
556  
557 sub array {
558 (shift)->_build_composite( \%ArrayFragments, @_ );
559 }
560  
561 %ArrayFragments = (
562 '' => [
563 '+init' => sub {
564 my ($method) = @_;
565 $method->{target_class} ||= $Class::MethodMaker::CONTEXT{TargetClass};
566 $method->{array_index} ||=
567 _array_index( $method->{target_class}, $name );
568 },
569 'do' => sub {
570 my $method = pop @_;
571 my $self = shift @_;
572 my $args = \@_;
573 if ( scalar(@$args) == 0 ) {
574 if ( $method->{auto_init} and
575 ! defined $self->[$method->{array_index}] ) {
576 $self->[$method->{array_index}] = [];
577 }
578 wantarray ? @{ $self->[$method->{array_index}] } : $self->[$method->{array_index}];
579 } elsif ( scalar(@_) == 1 and ref $_[0] eq 'ARRAY' ) {
580 $self->[$method->{array_index}] = [ @{ $_[0] } ];
581 wantarray ? @{ $self->[$method->{array_index}] } : $self->[$method->{array_index}];
582 } else {
583 $self->[$method->{array_index}] ||= [];
584 Class::MakeMethods::Composite::__array_ops(
585 $self->[$method->{array_index}], @$args );
586 }
587 },
588 ],
589 );
590  
591 ########################################################################
592  
593 =head2 hash - Instance Ref Accessor
594  
595 For each method name passed, uses a closure to generate a subroutine with the following characteristics:
596  
597 =over 4
598  
599 =item *
600  
601 Must be called on an array-based instance.
602  
603 =item *
604  
605 Determines the array position associated with the method name, and uses that as an index into each instance to access the related value. This defaults to the next available slot in %FIELDS, but you may override this with the C<'array_index' => I<number>> method parameter, or by pre-filling the contents of %FIELDS.
606  
607 =item *
608  
609 The value for each instance will be a reference to a hash (or undef).
610  
611 =item *
612  
613 If called without any arguments, returns the contents of the hash in list context, or a hash reference in scalar context (or undef).
614  
615 =item *
616  
617 If called with one non-ref argument, uses that argument as an index to retrieve from the referenced hash, and returns that value (or undef).
618  
619 =item *
620  
621 If called with one array-ref argument, uses the contents of that array to retrieve a slice of the referenced hash.
622  
623 =item *
624  
625 If called with one hash-ref argument, sets the contents of the referenced hash to match that provided.
626  
627 =item *
628  
629 If called with a list of key-value pairs, stores the value under the given key in the referenced hash. If the instance's value was previously undefined, a new hash is autovivified. The current value under each key will be overwritten, and later arguments with the same key will override earlier ones. Returns the contents of the hash in list context, or a hash reference in scalar context.
630  
631 =back
632  
633 Sample declaration and usage:
634  
635 package MyObject;
636 use Class::MakeMethods::Composite::Array (
637 hash => 'baz',
638 );
639 ...
640
641 # Set values by key
642 $obj->baz('foo' => 'Foozle', 'bar' => 'Bang!');
643
644 # Values may be overwritten, and in any order
645 $obj->baz('broccoli' => 'Blah!', 'foo' => 'Fiddle');
646
647 # Retrieve value by key
648 print $obj->baz('foo');
649
650 # Retrive slice of values by position
651 print join(', ', $obj->baz( ['foo', 'bar'] ) );
652
653 # Direct access to referenced hash
654 print keys %{ $obj->baz() };
655
656 # Reset the hash contents to empty
657 @{ $obj->baz() } = ();
658  
659 =cut
660  
661  
662 use vars qw( %HashFragments );
663  
664 sub hash {
665 (shift)->_build_composite( \%HashFragments, @_ );
666 }
667  
668 %HashFragments = (
669 '' => [
670 '+init' => sub {
671 my ($method) = @_;
672 $method->{hash_key} ||= $_->{name};
673 },
674 'do' => sub {
675 my $method = pop @_;
676 my $self = shift @_;
677 my $args = \@_;
678 if ( scalar(@$args) == 0 ) {
679 if ( $method->{auto_init} and ! defined $self->[$method->{array_index}] ) {
680 $self->[$method->{array_index}] = {};
681 }
682 wantarray ? %{ $self->[$method->{array_index}] } : $self->[$method->{array_index}];
683 } elsif ( scalar(@$args) == 1 ) {
684 if ( ref($_[0]) eq 'HASH' ) {
685 %{$self->[$method->{array_index}]} = %{$_[0]};
686 } elsif ( ref($_[0]) eq 'ARRAY' ) {
687 return @{$self->[$method->{array_index}]}{ @{$_[0]} }
688 } else {
689 return $self->[$method->{array_index}]->{ $_[0] }
690 }
691 } elsif ( scalar(@$args) % 2 ) {
692 croak "Odd number of items in assigment to $method->{name}";
693 } else {
694 while ( scalar(@$args) ) {
695 my $key = shift @$args;
696 $self->[$method->{array_index}]->{ $key} = shift @$args;
697 }
698 wantarray ? %{ $self->[$method->{array_index}] } : $self->[$method->{array_index}];
699 }
700 },
701 ],
702 );
703  
704 ########################################################################
705  
706 =head2 object - Instance Ref Accessor
707  
708 For each method name passed, uses a closure to generate a subroutine with the following characteristics:
709  
710 =over 4
711  
712 =item *
713  
714 Must be called on an array-based instance.
715  
716 =item *
717  
718 Determines the array position associated with the method name, and uses that as an index into each instance to access the related value. This defaults to the next available slot in %FIELDS, but you may override this with the C<'array_index' => I<number>> method parameter, or by pre-filling the contents of %FIELDS.
719  
720 =item *
721  
722 The value for each instance will be a reference to an object (or undef).
723  
724 =item *
725  
726 If called without any arguments returns the current value.
727  
728 =item *
729  
730 If called with an argument, stores that as the value, and returns it,
731  
732 =back
733  
734 Sample declaration and usage:
735  
736 package MyObject;
737 use Class::MakeMethods::Composite::Hash (
738 object => 'foo',
739 );
740 ...
741
742 # Store value
743 $obj->foo( Foozle->new() );
744
745 # Retrieve value
746 print $obj->foo;
747  
748 =cut
749  
750 use vars qw( %ObjectFragments );
751  
752 sub object {
753 (shift)->_build_composite( \%ObjectFragments, @_ );
754 }
755  
756 %ObjectFragments = (
757 '' => [
758 '+init' => sub {
759 my ($method) = @_;
760 $method->{hash_key} ||= $_->{name};
761 },
762 'do' => sub {
763 my $method = pop @_;
764 my $self = shift;
765 if ( scalar @_ ) {
766 my $value = shift;
767 if ( $method->{class} and ! UNIVERSAL::isa( $value, $method->{class} ) ) {
768 croak "Wrong argument type ('$value') in assigment to $method->{name}";
769 }
770 $self->[$method->{array_index}] = $value;
771 } else {
772 if ( $method->{auto_init} and ! defined $self->[$method->{array_index}] ) {
773 my $class = $method->{class}
774 or die "Can't auto_init without a class";
775 my $new_method = $method->{new_method} || 'new';
776 $self->[$method->{array_index}] = $class->$new_method();
777 }
778 $self->[$method->{array_index}];
779 }
780 },
781 ],
782 );
783  
784 ########################################################################
785  
786 =head1 SEE ALSO
787  
788 See L<Class::MakeMethods> for general information about this distribution.
789  
790 See L<Class::MakeMethods::Composite> for more about this family of subclasses.
791  
792 =cut
793  
794 1;