Valiant/Filterable.pm

filter: Statementstmt 94.0% 158 / 168 Branchbran 69.3% 43 / 62 Conditioncond 73.6% 14 / 19 MC/DCmcdc 50.0% 5 / 10 Subroutinesub 100% 23 / 23 Podpod n/a totaltotal 86.1% 243 / 282 CC 54 SCAR 20.1
CC
54
Cov
86%
_filters
12.3
__filters_for_exporter
11.2
filters
11.2
CRAP 7.4
« Valiant/Translation.pm ↑ Summary Valiant/Validator/With.pm »
1 package Valiant::Filterable;
2  
3 21 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 21 ▶use Module::Runtime 'use_module';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 21 ▶use String::CamelCase 'camelize';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 21 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 21 ▶use Valiant::Util 'throw_exception', 'debug';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 21 ▶use namespace::autoclean -also => ['throw_exception', 'debug'];
Subroutine BEGIN: called CC=1 SCAR=0.0
9 21 ▶use Valiant::Filters ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 21 has _instance_filters => (is=>'rw', init_arg=>undef);
12  
13 sub _filters {
14 204 ▶ my ($class_or_self, $arg) = @_;
Subroutine _filters: called CC=8 SCAR=25.1
15 204 ▶ my $class = ref($class_or_self) ? ref($class_or_self) : $class_or_self;
Branch: 1 branch
BranchTrueFalseTotal
ref $class_or_self ? : 0 204 204
16  
17 204 my @existing = ();
18 204 ▶ if(defined($arg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg) 31 173 204
19 31 ▶ if(ref($class_or_self)) { # its $self
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_self) { } 0 31 31
20 0 ▶ my @existing = @{ $class_or_self->_instance_filters||[] };
Branch: 1 branch
BranchTrueFalseTotal
$class_or_self->_instance_filters or [] 0 0 0
21 0 $class_or_self->_instance_filters([$arg, @existing]);
22 } else {
23 31 Valiant::Filters::_add_metadata($class_or_self, 'filters', $arg);
24 }
25 }
26 204 ▶ @existing = @{ $class_or_self->_instance_filters||[] } if ref $class_or_self;
Branch: 2 branches
BranchTrueFalseTotal
if ref $class_or_self 0 204 204
$class_or_self->_instance_filters or [] 0 0 0
27 204 ▶ my @filters = $class_or_self->filters_metadata if $class_or_self->can('filters_metadata');
Branch: 1 branch
BranchTrueFalseTotal
if $class_or_self->can("filters_metadata") 52 152 204
28 204 return @filters, @existing;
29 }
30  
31 141 ▶sub default_filter_namepart { 'Filter' }
Subroutine default_filter_namepart: called CC=1 SCAR=0.0
32 6 ▶sub default_filter_collection_class { 'Valiant::Filter::Collection' }
Subroutine default_filter_collection_class: called CC=1 SCAR=0.0
33  
34 sub _filters_coderef {
35 31 ▶ my ($self, $coderef) = @_;
Subroutine _filters_coderef: called CC=1 SCAR=0.0
36 31 $self->_filters($coderef);
37 31 return $self;
38 }
39  
40 sub _prepare_filter_packages {
41 36 ▶ my ($class, $key) = @_;
Subroutine _prepare_filter_packages: called CC=2 SCAR=7.0
42 36 my $camel = camelize($key);
43 36 my @packages = $class->_normalize_filter_package($camel);
44  
45 36 ▶ return @packages if $camel =~/^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $camel =~ /^\+/ 0 36 36
46  
47 push @packages, map {
48 36 "${_}::${camel}";
49 } $class->default_filter_namespaces;
50  
51 36 return @packages;
52 }
53  
54 sub default_filter_namespaces {
55 36 ▶ my ($self) = @_;
Subroutine default_filter_namespaces: called CC=1 SCAR=0.0
56 36 return ('Valiant::FilterX', 'Valiant::Filter');
57 }
58  
59 sub _filter_package {
60 36 ▶ my ($self, $key) = @_;
Subroutine _filter_package: called CC=4 SCAR=14.0
61 36 my @filter_packages = $self->_prepare_filter_packages($key);
62 my ($filter_package, @rest) = grep {
63 36 my $package_to_test = $_;
64 213 ▶ eval { use_module $package_to_test } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &use_module($package_to_test) } } or do { my $notional_filename = &Module::Runtime::module_notional_filename($package_to_test); if ($@ =~ /^Can't locate $notional_filename/) { debug(1, "Can't find '${package_to_test}' in \@INC"); 0; } else { throw_exception("UnexpectedUseModuleError", ("package", $package_to_test, "err", $@)); } } 177 36 213
65 # This regexp matches too much... We need to add the package
66 # path here just the path delim will vary from platform to platform
67 177 my $notional_filename = Module::Runtime::module_notional_filename($package_to_test);
68 177 ▶ if($@=~m/^Can't locate $notional_filename/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /^Can't locate $notional_filename/) { } 177 0 177
69 177 debug 1, "Can't find '$package_to_test' in \@INC";
70 177 0;
71 } else {
72 0 throw_exception UnexpectedUseModuleError => (package => $package_to_test, err => $@);
73 }
74 }
75 } @filter_packages;
76 36 ▶ throw_exception('NameNotFilter', name => $key, packages => \@filter_packages)
Branch: 1 branch
BranchTrueFalseTotal
unless $filter_package 0 36 36
77 unless $filter_package;
78 36 debug 1, "Found $filter_package in \@INC";
79 36 return $filter_package;
80 }
81  
82 sub _create_filter {
83 36 ▶ my ($self, $filter_package, $args) = @_;
Subroutine _create_filter: called CC=1 SCAR=0.0
84 36 debug 1, "Trying to create filter from $filter_package";
85 36 my $filter = $filter_package->new($args);
86 36 return $filter;
87 }
88  
89 sub filters {
90 6 ▶ my ($self, @proto) = @_;
Subroutine filters: called CC=11 SCAR=24.1
Subroutine __filters_for_exporter: called CC=11 SCAR=24.1
91  
92 # handle a list of attributes with filters
93 6 my $attributes = shift @proto;
94 6 ▶ $attributes = [$attributes] unless ref $attributes;
Branch: 2 branches
BranchTrueFalseTotal
unless ref $attributes 6 0 6
unless ref $attributes 18 1 19
95 6 my @options = @proto;
96  
97 6 my (@filter_info) = ();
98 6 ▶ while(@options) {
Branch: 2 branches
BranchTrueFalseTotal
if (@options) 8 6 14
if (@options) 24 19 43
99 8 my $args;
100 8 my $key = shift(@options);
101 8 ▶ if((ref($key)||'') eq 'CODE') { # This bit allows for callbacks instead of a filter => \%params setup
Branch: 2 branches
BranchTrueFalseTotal
if ((ref $key || '') eq 'CODE') { } 1 7 8
if ((ref $key || '') eq 'CODE') { } 1 23 24
Condition100%4/4
ref $key || ''
l!l
17
ref $key || ''
l!l
123
MC/DC100%1/1
ref $key || ''
ref $key
MC/DC100%1/1
ref $key || ''
ref $key
Truth table100%2/2
A
A= ref $key
Aresult
11
00
Truth table100%2/2
A
A= ref $key
Aresult
11
00
102 1 $args = { cb => $key };
103 1 $key = 'with';
104 1 ▶ if((ref($options[0])||'') eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if ((ref $options[0] || "") eq "HASH") 0 1 1
if ((ref $options[0] || "") eq "HASH") 0 1 1
Condition50%2/4
ref $options[0] || ''
l!l
01
ref $options[0] || ''
l!l
01
MC/DC0%0/1
ref $options[0] || ''
ref $options[0]
MC/DC0%0/1
ref $options[0] || ''
ref $options[0]
Truth table50%1/2
A
A= ref $options[0]
Aresult
11
00
Truth table50%1/2
A
A= ref $options[0]
Aresult
11
00
105 0 my $base_args = shift(@options);
106 0 $args = +{ %$args, %$base_args };
107 }
108 } else { # Otherwise its a normal validator with params
109 7 $args = shift(@options);
110 }
111 8 push @filter_info, [$key, $args];
112 }
113
114 6 my @filters = ();
115 6 foreach my $info(@filter_info) {
116 8 my ($package_part, $args) = @$info;
117 8 my $filter_package = $self->_filter_package($package_part);
118
119 8 ▶ unless( (ref($args)||'') eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
unless ((ref $args || "") eq "HASH") 7 1 8
unless ((ref $args || "") eq "HASH") 16 8 24
Condition100%4/4
ref $args || ''
l!l
26
ref $args || ''
l!l
1113
MC/DC100%1/1
ref $args || ''
ref $args
MC/DC100%1/1
ref $args || ''
ref $args
Truth table100%2/2
A
A= ref $args
Aresult
11
00
Truth table100%2/2
A
A= ref $args
Aresult
11
00
120 7 $args = $filter_package->normalize_shortcut($args);
121 7 ▶ throw_exception InvalidFilterArgs => ( args => $args) unless ref($args) eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 7 7
unless ref $args eq "HASH" 0 16 16
122 }
123
124 8 $args->{attributes} = $attributes;
125 8 $args->{model} = $self;
126  
127 8 my $new_filter = $self->_create_filter($filter_package, $args);
128 8 push @filters, $new_filter;
129 }
130 my $coderef = sub {
131 31 ▶ my ($class, $attrs) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
132 31 foreach my $filter (@filters) {
133 38 $attrs = $filter->filter($class, $attrs);
134 }
135 31 return $attrs;
136 6 };
137 6 $self->_filters_coderef($coderef);
138 }
139  
140 sub _normalize_filter_package {
141 36 ▶ my ($self, $with) = @_;
Subroutine _normalize_filter_package: called CC=4 SCAR=14.1
142 36 my ($prefix, $package) = ($with =~m/^(\+?)(.+)$/);
143 36 ▶ return $package if $prefix eq '+';
Branch: 1 branch
BranchTrueFalseTotal
if $prefix eq "+" 0 36 36
144  
145 36 ▶ my $class = ref($self) || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
0360
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table33%1/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
146 36 my @parts = ((split '::', $class), $package);
147 36 my @project_inc = ();
148 36 ▶ while(@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 141 36 177
149 141 push @project_inc, join '::', (@parts, $class->default_filter_namepart, $package);
150 141 pop @parts;
151 }
152 36 return @project_inc;
153 }
154  
155 sub filters_with {
156 6 ▶ my ($self, $proto, %options) = @_;
Subroutine filters_with: called CC=9 SCAR=22.3
157 my @with = ref($proto) eq 'ARRAY' ?
158 6 ▶ @{$proto} : ($proto);
Branch: 1 branch
BranchTrueFalseTotal
ref $proto eq 'ARRAY' ? : 0 6 6
159  
160 6 my @filters = ();
161 6 FILTER_WITHS: foreach my $with (@with) {
162 6 ▶ if( (ref($with)||'') eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $with || "") eq "CODE") 2 4 6
Condition100%2/2
ref $with || ''
l!l
24
MC/DC100%1/1
ref $with || ''
ref $with
Truth table100%2/2
A
A= ref $with
Aresult
11
00
163 2 push @filters, [$with, \%options];
164 2 next FILTER_WITHS;
165 }
166 4 debug 1, "Trying to find a filter for '$with'";
167  
168 4 my $filter_package = $self->_filter_package($with);
169  
170 4 my $args;
171 4 ▶ unless((ref($args)||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless ((ref $args || "") eq "HASH") 4 0 4
Condition50%1/2
ref $args || ''
l!l
04
MC/DC0%0/1
ref $args || ''
ref $args
Truth table50%1/2
A
A= ref $args
Aresult
11
00
172 4 ▶ $args = $filter_package->can('normalize_shortcut') ? $filter_package->normalize_shortcut(\%options) : \%options;
Branch: 1 branch
BranchTrueFalseTotal
$filter_package->can('normalize_shortcut') ? : 2 2 4
173 4 ▶ throw_exception InvalidFilterArgs => ( args => $args) unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 4 4
174 }
175
176 4 $args->{model} = $self;
177  
178 4 my $new_filter = $self->_create_filter($filter_package, $args);
179 4 push @filters, $new_filter;
180  
181  
182 }
183 6 my $collection = use_module($self->default_filter_collection_class)
184 ->new(filters=>\@filters);
185 6 ▶ $self->_filters_coderef(sub { $collection->filter(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
186 }
187  
188 sub _process_filters {
189 173 ▶ my ($class, $attrs) = @_;
Subroutine _process_filters: called CC=2 SCAR=6.9
190 173 foreach my $filter ($class->_filters) {
191 37 $attrs = $filter->($class, $attrs);
192 }
193 173 return $attrs;
194 }
195  
196 around BUILDARGS => sub {
197 15 ▶ my ( $orig, $class, @args ) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
198 15 my $attrs = $class->$orig(@args);
199 15 ▶ return $class->_process_filters($attrs) if $attrs;
Branch: 1 branch
BranchTrueFalseTotal
if $attrs 14 1 15
200 21 };
201  
202 21 1;
203  
204 =head1 NAME
205  
206 Valiant::Filters - Role that adds class and instance methods supporting field filters
207  
208 =head1 SYNOPSIS
209  
210 package Local::Test::User;
211  
212 use Moo;
213  
214 with 'Valiant::Filterable';
215  
216 has 'name' => (is=>'ro', required=>1);
217 has 'last' => (is=>'ro', required=>1);
218  
219 __PACKAGE__->filters(last => (Trim=>1));
220  
221 __PACKAGE__->filters_with(sub {
222 my ($class, $attrs, $opts) = @_;
223 $attrs = +{
224 map {
225 my $value = $attrs->{$_};
226 $value =~ s/^\s+|\s+$//g;
227 $_ => $value;
228 } keys %$attrs
229 };
230 $attrs->{name} = "$opts->{a}$attrs->{name}$opts->{b}";
231 return $attrs;
232 }, a=>1, b=>2);
233  
234 __PACKAGE__->filters_with(Foo => (a=>1,b=>2));
235  
236 __PACKAGE__->filters(last => (
237 uc_first => 1,
238 with => sub {
239 my ($class, $attrs, $name) = @_;
240 return $attrs->{$name} . "XXX";
241 },
242 sub {
243 my ($class, $attrs, $name) = @_;
244 return $attrs->{$name} . "AAA";
245 },
246 ));
247  
248 =head1 DESCRIPTION
249  
250 This is a role that adds class level filtering to you L<Moo> or L<Moose> classes. Generally
251 you may prefer to us L<Valiant::Filters> since that gives you a nice DSL for applying filters
252 to your classes but if you have very special or custom needs (or you need to extend the filter
253 API itself) you might need to use the role directly.
254  
255 =head1 CLASS METHODS
256  
257 =head2 filters
258  
259 Used to declare filters on an attribute. The first argument is either a scalar or arrayref of
260 scalars which should be attributes on your object:
261  
262 __PACKAGE__->filters( name => (...) );
263 __PACKAGE__->filters(['name', 'age'] => (...));
264  
265 Following arguments should be in one of two forms: a coderef or subroutine reference that contains
266 filter rules or a key - value pair which is a class and its arguments:
267  
268 __PACKAGE__->filters( name => (
269 trim => 1,
270 with => sub { my ($class, $attrs, $name) = @_; },
271 sub { my ($class, $attrs, $name) = @_; }m
272 ));
273  
274 When you use a Filter class (such as C<trim => { maximum => 25 }>) we resolve the class
275 name C<trim> in the following way. We first camel case the name and then look for a 'Filter' package
276 in the current class namespace. If we don't find a match we check each namespace up the hierarchy and
277 then check the two global namespaces C<Valiant::FilterX> and C<Validate::Filters>. For example if
278 you declare filters as in the example class C<Local::Model::User> we would look for the following:
279  
280 Local::Model::User::Filter::Trim
281 Local::Model:::Filter::Trim
282 Local::Filter::Trim
283 Validator::Trim
284 Valiant::FilterX::Trim
285 Valiant::Filter:::Trim
286  
287 These get checked in the order above and loaded and instantiated once at setup time.
288  
289 B<NOTE:> The namespace C<Valiant::Filter> is reserved for filters that ship with L<Valiant>. The
290 C<Valiant::FilterX> namespace is reserved for additional filters on CPAN that are packaged separately
291 from L<Valiant>. If you wish to share a custom fiter that you wrote the proper namespace to use on
292 CPAN is C<Valiant::FilterX>.
293  
294 You can also prepend your filter name with '+' which will cause L<Valiant> to ignore the namespace
295 resolution and try to load the class directly. For example:
296  
297 __PACKAGE__->filters(name => ('+App::MyFilter' => {}), );
298  
299 Will try to load the class C<App::MyFilter> and use it as a filter directly (or throw an exception if
300 it fails to load).
301  
302 =head2 filters_with
303  
304 C<filters_with> is intended to process filters that are on the class as a whole, or which are very
305 complex and can't easily be assigned to a single attribute. It accepts either a subroutine reference
306 with an optional hash of key value pair options (which are passed to C<$opts>) or a scalar name which
307 should be a stand alone filter class (basically a class that does the C<filters> method although
308 you should consume the L<Validate::Filter> role to enforce the contract).
309  
310 __PACKAGE__->filters_with(sub {
311 my ($self, $class, $attrs)) = @_;
312 ...
313 });
314  
315 __PACKAGE__->filters_with(\&check_object => (arg1=>'foo', arg2=>'bar'));
316  
317 sub filters_with {
318 my ($self, $class, $attrs) = @_;
319 ...
320 }
321  
322 __PACKAGE__->filters_with( 'Custom' => (arg1=>'foo', arg2=>'bar'));
323  
324 If you pass a string that is a filter class we resolve its namespace using the same approach as
325 detailed above for C<filters>. Any arguments are passed to the C<new> method of the found class.
326  
327 =head1 AUTHOR
328
329 John Napiorkowski L<email:jjnapiork@cpan.org>
330
331 =head1 SEE ALSO
332
333 L<Valiant::Filters>
334  
335 =head1 COPYRIGHT & LICENSE
336
337 Copyright 2020, John Napiorkowski L<email:jjnapiork@cpan.org>
338
339 This library is free software; you can redistribute it and/or modify it under
340 the same terms as Perl itself.
341  
342 =cut
343  
« Valiant/Translation.pm ↑ Summary Valiant/Validator/With.pm »