blib/lib/Class/Tiny/ConstrainedAccessor.pm

filter: Statementstmt 99.0% 101 / 102 Branchbran 97.6% 41 / 42 Conditioncond 88.8% 8 / 9 MC/DCmcdc 83.3% 5 / 6 Subroutinesub 94.4% 17 / 18 Podpod n/a totaltotal 97.1% 172 / 177 CC 27 SCAR 16.9
CC
27
Cov
98%
_get_constraint_sub
10.0
import
8.0
__ANON__
6.0
CRAP 5.4
↑ Summary
1 package Class::Tiny::ConstrainedAccessor;
2  
3 13 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 13 ▶use Class::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 13 ▶use Types::TypeTiny ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 13 our $VERSION = '0.000015';
10  
11 # Docs {{{1
12  
13 =head1 NAME
14  
15 Class::Tiny::ConstrainedAccessor - Generate Class::Tiny accessors that apply type constraints
16  
17 =head1 SYNOPSIS
18  
19 L<Class::Tiny> uses custom accessors if they are defined before the
20 C<use Class::Tiny> statement in a package. This module creates custom
21 accessors that behave as standard C<Class::Tiny> accessors except that
22 they apply type constraints (C<isa> relationships). Type constraints
23 can come from L<Type::Tiny>, L<MooseX::Types>, L<MooX::Types::MooseLike>,
24 L<MouseX::Types>, or L<Specio>. Alternatively, constraints can be applied
25 using the technique described in
26 L<"Constraints without a type system"|/CONSTRAINTS WITHOUT A TYPE SYSTEM>.
27  
28 Example of a class using this package:
29  
30 package SampleClass;
31 use Scalar::Util qw(looks_like_number);
32  
33 use Type::Tiny;
34  
35 # Create the type constraint
36 use vars::i '$MediumInteger' = Type::Tiny->new(
37 name => 'MediumInteger',
38 constraint => sub { looks_like_number($_) and $_ >= 10 and $_ < 20 }
39 );
40  
41 use Class::Tiny::ConstrainedAccessor {
42 medint => $MediumInteger, # create accessor sub medint()
43 med_with_default => $MediumInteger,
44 };
45  
46 # After using ConstrainedAccessor, actually define the class attributes.
47 use Class::Tiny qw(medint regular), {
48 med_with_default => 12,
49 };
50  
51 =head1 CONSTRAINTS WITHOUT A TYPE SYSTEM
52  
53 If you don't want to use L<Type::Tiny> or one of the other type systems listed
54 above, you can create your own constraints as two-element arrayrefs. Example:
55  
56 use Class::Tiny::ConstrainedAccessor
57 'field' => [ \&checker_sub, \&message_sub ];
58  
59 C<checker_sub> and C<message_sub> are used as follows to check C<$value>:
60  
61 checker_sub($value) or die get_message($value);
62  
63 Therefore, C<checker_sub> must return truthy if C<$_[0]> passes the constraint,
64 or else falsy. C<get_message> must return something that can be passed to
65 C<die()>, when given a C<$_[0]> that has failed the constraint.
66  
67 If your profile ever tells you that constraint-checks are on the critical
68 path, try custom constraints. They may give you more control or opportunity
69 for optimization than general-purpose type systems.
70  
71 =head1 SUBROUTINES
72  
73 =head2 import
74  
75 Creates the accessors you have requested. Constraints can be passed as a list
76 or hashref of variable/constraint pairs. Basic usage:
77  
78 # Constraints are passed as a list of pairs
79 use Class::Tiny::ConstrainedAccessor
80 name => constraint
81 [, name2 => constraint ...]; # ... any number of name=>constraint pairs
82  
83 # Constraints are passed as a hashref
84 use Class::Tiny::ConstrainedAccessor {
85 name => constraint,
86 [, name2 => constraint ...]; # ... any number of name=>constraint pairs
87 };
88  
89 This also creates a L<BUILD()|Class::Tiny/BUILD> subroutine to check the
90 constructor parameters, if a C<BUILD()> doesn't already exist.
91  
92 If a C<BUILD()> does exist (e.g., you said C<use subs 'BUILD';>), this package
93 will create the same function, taking the same parameters as C<BUILD()> would,
94 but call it C<_check_all_constraints()>. You can call this checker from your
95 own C<BUILD()> if you want to.
96  
97 =head1 OPTIONS
98  
99 To specify options, pass an B<arrayref> as the first argument on the `use`
100 line. This is because a hashref carries attributes and constraints.
101 For example:
102  
103 use Class::Tiny::ConstrainedAccessor [ OPTION=>value ],
104 name => constraint ...;
105  
106 Valid options are:
107  
108 =over
109  
110 =item NOBUILD
111  
112 If C<< NOBUILD => 1 >> is given, the constructor-parameter-checker
113 is created as C<_check_all_constraints> regardless of whether C<BUILD()>
114 exists or not. Example:
115  
116 package MyClass;
117 use Class::Tiny::ConstrainedAccessor
118 [NOBUILD => 1],
119 foo => SomeConstraint;
120 # Now $object->_check_all_constraints($args) exists, but not BUILD().
121  
122 =back
123  
124 =cut
125  
126 # }}}1
127  
128 25 ▶sub import {
Subroutine import: called CC=8 SCAR=20.8
129 25 my $target = caller;
130 25 my $package = shift;
131  
132 25 my %opts = ();
133 25 ▶ %opts = @{+shift} if ref $_[0] eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $_[0] eq "ARRAY" 1 24 25
134  
135 25 my %constraints;
136 25 ▶ if (ref $_[0] eq 'HASH' && scalar @_ == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH' and scalar @_ == 1) { } 1 24 25
Condition66%2/3
ref $_[0] eq "HASH" and scalar @_ == 1
!ll&&!rl&&r
2401
MC/DC50%1/2
ref $_[0] eq "HASH" and scalar @_ == 1
ref $_[0] eq "HASH" scalar @_ == 1
Truth table66%2/3
A and B
A= ref $_[0] eq "HASH"B= scalar @_ == 1
ABresult
0X0
100
111
137 1 %constraints = %{$_[0]};
138 } else {
139 24 ▶ die "Need 'name => \$Constraint' pairs" if @_%2;
Branch: 1 branch
BranchTrueFalseTotal
if @_ % 2 2 22 24
140 22 %constraints = @_;
141 }
142  
143 # --- Make the accessors ---
144 23 my %accessors; # constraint => [checker, get_message]
145 23 foreach my $k (keys(%constraints)) {
146 44 my $constraint = $constraints{$k};
147  
148 44 my ($checker, $get_message) =
149 _get_constraint_sub($k, $constraint); # dies on failure
150  
151 33 my $accessor = _make_accessor($k, $checker, $get_message);
152 33 $accessors{$k} = [$checker, $get_message]; # Save for BUILD()
153  
154 { # Install the accessor
155 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
156 33 *{ "$target\::$k" } = $accessor;
157 }
158 } #foreach constraint
159  
160 # --- Make BUILD ---
161 my $has_build =
162 13 ▶ do { no warnings 'once'; no strict 'refs'; *{"$target\::BUILD"}{CODE} }
Subroutine BEGIN: called CC=1 SCAR=0.0
Subroutine BEGIN: called CC=1 SCAR=0.0
163 12 ▶ || $opts{NOBUILD}; # NOBUILD => pretend BUILD() already exists.
Condition100%3/3
do { BEGIN {${^WARNING_BITS} = "\x55\x55\x55\x45\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} no strict 'refs'; *{"${target}::BUILD";}{'CODE'} } || $opts{'NOBUILD'}
l!l&&r!l&&!r
1110
MC/DC100%2/2
do { BEGIN {${^WARNING_BITS} = "\x55\x55\x55\x45\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} no strict 'refs'; *{"${target}::BUILD";}{'CODE'} } || $opts{'NOBUILD'}
do { BEGIN {${^WARNING_BITS} = "\x55\x55\x55\x45\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} no strict 'refs'; *{"${target}::BUILD";}{'CODE'} } $opts{'NOBUILD'}
Truth table100%3/3
A || B
A= do { BEGIN {${^WARNING_BITS} = "\x55\x55\x55\x45\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55\x55"} no strict 'refs'; *{"${target}::BUILD";}{'CODE'} }B= $opts{'NOBUILD'}
ABresult
1X1
011
000
164 12 my $build = _make_build(%accessors);
165 {
166 13 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
167 12 ▶ *{ $has_build ? "$target\::_check_all_constraints" :
Branch: 1 branch
BranchTrueFalseTotal
$has_build ? : 2 10 12
168 "$target\::BUILD" } = $build;
169 }
170  
171 } #import()
172  
173 # _get_constraint_sub: Get the subroutine for a constraint.
174 # Takes the constraint name (for debug messages) and the constraint.
175 # Returns two coderefs: checker and get_message.
176 44 ▶sub _get_constraint_sub {
Subroutine _get_constraint_sub: called CC=10 SCAR=23.0
177 44 my ($type_name, $type) = @_;
178  
179 # Get type's name, if any
180 44 ▶ my $name = eval { $type->can('name') || $type->can('description') };
Condition100%3/3
$type->can('name') || $type->can('description')
l!l&&r!l&&!r
2515
MC/DC100%2/2
$type->can('name') || $type->can('description')
$type->can('name') $type->can('description')
Truth table100%3/3
A || B
A= $type->can('name')B= $type->can('description')
ABresult
1X1
011
000
181 44 ▶ $name = $type->$name() if $name;
Branch: 1 branch
BranchTrueFalseTotal
if $name 26 18 44
182  
183 # Set default message
184 44 ▶ $name = $type_name unless $name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 22 22 44
185 0 ▶ my $default_get_message = sub { "Value is not a $name" };
Subroutine __ANON__: not called CC=1 SCAR=1.2
186  
187 # Handle the custom-constraint format
188 44 ▶ if(ref $type eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type eq "ARRAY") 7 37 44
189 7 ▶ die "Custom constraint $type_name must have two elements: checker, get_message"
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$type == 2 2 5 7
190 unless scalar @$type == 2;
191 5 ▶ die "$type_name: checker must be a subroutine" unless ref($type->[0]) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $type->[0] eq "CODE" 1 4 5
192 4 ▶ die "$type_name: get_message must be a subroutine" unless ref($type->[1]) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $type->[1] eq "CODE" 1 3 4
193 3 return @$type;
194 }
195  
196 # Handle MooX::Types::MooseLike as well as other types of coderef.
197 # $orig_coderef may indicate failure by dying or returning 0 ---
198 # there's no way to know. We assume that:
199 # - Express undef is success (e.g., MooX::Types::MooseLike)
200 # - die() is failure (ditto)
201 # - Returning a defined value is a success/failure indication
202 # (as expected by Types::TypeTiny::to_TypeTiny(\&)).
203 37 ▶ if(ref $type eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type eq "CODE") 3 34 37
204 3 my $orig_coderef = $type;
205 229 ▶ my $new_type = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
206 229 local $@;
207 229 my $is_ok = eval { $orig_coderef->(@_) };
208 229 ▶ if($@) {
Branch: 2 branches
BranchTrueFalseTotal
if ($@) { } 182 47 229
elsif (not defined $is_ok) { } 47 0 47
209 182 $is_ok = 0; # die() => failure
210 } elsif(!defined $is_ok) {
211 47 $is_ok = 1; # undef => success
212 }
213 229 return $is_ok;
214 3 };
215 3 $type = $new_type;
216 }
217  
218 37 my $impl = Types::TypeTiny::to_TypeTiny($type);
219 37 ▶ die "I couldn't understand the constraint for $type_name"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $impl eq "Type::Tiny" 7 30 37
220 unless ref $impl eq 'Type::Tiny';
221  
222 30 ▶ return ( $impl->compiled_check(), sub { $impl->get_message($_[0]) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
223 } #_get_constraint_sub()
224  
225 # _make_accessor($name, \&checker, \&get_message): Make an accessor.
226 33 ▶sub _make_accessor {
Subroutine _make_accessor: called CC=1 SCAR=0.0
227 33 my ($k, $checker, $get_message) = @_;
228  
229 # The accessor --- modified from the Class::Tiny docs based on
230 # the source for C::T::__gen_accessor() and C::T::__gen_sub_body().
231 1326 ▶ return sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
232 1326 my $self_ = shift;
233 1326 ▶ if (@_) { # Set
Branch: 2 branches
BranchTrueFalseTotal
if (@_) { } 1260 66 1326
elsif (exists $self_->{$k}) { } 23 43 66
234 1260 ▶ $checker->($_[0]) or die $get_message->($_[0]);
Branch: 1 branch
BranchTrueFalseTotal
&$checker($_[0]) or die &$get_message($_[0]) 400 860 1260
235 400 return $self_->{$k} = $_[0];
236  
237 } elsif ( exists $self_->{$k} ) { # Get
238 23 return $self_->{$k};
239  
240 } else { # Get default
241 43 my $defaults_ =
242 Class::Tiny->get_all_attribute_defaults_for( ref $self_ );
243  
244 43 my $def_ = $defaults_->{$k};
245 43 ▶ $def_ = $def_->() if ref $def_ eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $def_ eq "CODE" 21 22 43
246  
247 43 ▶ $checker->($def_) or die $get_message->($def_);
Branch: 1 branch
BranchTrueFalseTotal
&$checker($def_) or die &$get_message($def_) 40 3 43
248 40 return $self_->{$k} = $def_;
249 }
250 33 }; #accessor()
251 } #_make_accessor()
252  
253 # _make_build(%accessors): Make a BUILD subroutine that will check
254 # the constraints from the constructor arguments.
255 # The resulting subroutine takes ($self, {args}).
256 12 ▶sub _make_build {
Subroutine _make_build: called CC=1 SCAR=0.0
257 12 my %accessors = @_;
258  
259 76 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
260 76 my ($self, $args) = @_;
261 76 foreach my $k (keys %$args) {
262 126 ▶ next unless exists $accessors{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $accessors{$k} 50 76 126
263 76 my ($checker, $get_message) = @{$accessors{$k}};
264 76 ▶ $checker->($args->{$k}) or die $get_message->($args->{$k});
Branch: 1 branch
BranchTrueFalseTotal
&$checker($args->{$k}) or die &$get_message($args->{$k}) 31 45 76
265 }
266 } #BUILD()
267 12 } #_make_build()
268  
269 13 1; # End of Class::Tiny::ConstrainedAccessor
270 # Rest of the docs {{{1
271 __END__
↑ Summary