Valiant/Filterable.pm

filter: Statementstmt 94.0% 158 / 168 Branchbran 71.4% 40 / 56 Conditioncond 61.5% 16 / 26 MC/DCmcdc 42.8% 6 / 14 Subroutinesub 100% 23 / 23 Podpod 25.0% 1 / 4 totaltotal 83.8% 244 / 291 CC 54 SCAR 20.1
CC
54
Cov
86%
_filters
12.3
__filters_for_exporter
11.2
filters
11.2
CRAP 7.4
« Valiant/JSON/JSONBuilder.pm ↑ Summary Valiant/Translation.pm »
1 package Valiant::Filterable;
2  
3 12 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 12 ▶use Module::Runtime 'use_module';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 12 ▶use String::CamelCase 'camelize';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 12 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 12 ▶use Valiant::Util 'throw_exception', 'debug';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 12 ▶use namespace::autoclean -also => ['throw_exception', 'debug'];
Subroutine BEGIN: called CC=1 SCAR=0.0
9 12 ▶use Valiant::Filters ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 12 has _instance_filters => (is=>'rw', init_arg=>undef);
12  
13 42 ▶sub _filters {
Subroutine _filters: called CC=8 SCAR=25.1
14 42 my ($class_or_self, $arg) = @_;
15 42 ▶ my $class = ref($class_or_self) ? ref($class_or_self) : $class_or_self;
Branch: 1 branch
BranchTrueFalseTotal
ref $class_or_self ? : 0 42 42
16  
17 42 my @existing = ();
18 42 ▶ if(defined($arg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg) 28 14 42
19 28 ▶ if(ref($class_or_self)) { # its $self
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_self) { } 0 28 28
20 0 ▶ my @existing = @{ $class_or_self->_instance_filters||[] };
Condition0%0/2
$class_or_self->_instance_filters || []
l!l
00
MC/DC0%0/1
$class_or_self->_instance_filters || []
$class_or_self->_instance_filters
Truth table0%0/2
A
A= $class_or_self->_instance_filters
Aresult
11
00
21 0 $class_or_self->_instance_filters([$arg, @existing]);
22 } else {
23 28 Valiant::Filters::_add_metadata($class_or_self, 'filters', $arg);
24 }
25 }
26 0 ▶ @existing = @{ $class_or_self->_instance_filters||[] } if ref $class_or_self;
Branch: 1 branch
BranchTrueFalseTotal
if ref $class_or_self 0 42 42
Condition0%0/2
$class_or_self->_instance_filters || []
l!l
00
MC/DC0%0/1
$class_or_self->_instance_filters || []
$class_or_self->_instance_filters
Truth table0%0/2
A
A= $class_or_self->_instance_filters
Aresult
11
00
27 42 ▶ 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") 41 1 42
28 42 return @filters, @existing;
29 }
30  
31 124 ▶sub default_filter_namepart { 'Filter' }
Subroutine default_filter_namepart: called CC=1 SCAR=0.0
Pod undocumented
32 5 ▶sub default_filter_collection_class { 'Valiant::Filter::Collection' }
Subroutine default_filter_collection_class: called CC=1 SCAR=0.0
Pod undocumented
33  
34 28 ▶sub _filters_coderef {
Subroutine _filters_coderef: called CC=1 SCAR=0.0
35 28 my ($self, $coderef) = @_;
36 28 $self->_filters($coderef);
37 28 return $self;
38 }
39  
40 33 ▶sub _prepare_filter_packages {
Subroutine _prepare_filter_packages: called CC=2 SCAR=7.0
41 33 my ($class, $key) = @_;
42 33 my $camel = camelize($key);
43 33 my @packages = $class->_normalize_filter_package($camel);
44  
45 33 ▶ return @packages if $camel =~/^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $camel =~ /^\+/ 0 33 33
46  
47 push @packages, map {
48 33 "${_}::${camel}";
49 } $class->default_filter_namespaces;
50  
51 33 return @packages;
52 }
53  
54 33 ▶sub default_filter_namespaces {
Subroutine default_filter_namespaces: called CC=1 SCAR=0.0
Pod undocumented
55 33 my ($self) = @_;
56 33 return ('Valiant::FilterX', 'Valiant::Filter');
57 }
58  
59 33 ▶sub _filter_package {
Subroutine _filter_package: called CC=4 SCAR=14.1
60 33 my ($self, $key) = @_;
61 33 my @filter_packages = $self->_prepare_filter_packages($key);
62 my ($filter_package, @rest) = grep {
63 33 my $package_to_test = $_;
64 190 ▶ eval { use_module $package_to_test } || do {
Condition66%2/3
eval { do { &use_module($package_to_test) } } || 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', $@)); } }
l!l&&r!l&&!r
330157
MC/DC50%1/2
eval { do { &use_module($package_to_test) } } || 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', $@)); } }
eval { do { &use_module($package_to_test) } } 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', $@)); } }
Truth table66%2/3
A || B
A= eval { do { &use_module($package_to_test) } }B= 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', $@)); } }
ABresult
1X1
011
000
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 157 my $notional_filename = Module::Runtime::module_notional_filename($package_to_test);
68 157 ▶ if($@=~m/^Can't locate $notional_filename/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /^Can't locate $notional_filename/) { } 157 0 157
69 157 debug 1, "Can't find '$package_to_test' in \@INC";
70 157 0;
71 } else {
72 0 throw_exception UnexpectedUseModuleError => (package => $package_to_test, err => $@);
73 }
74 }
75 } @filter_packages;
76 33 ▶ throw_exception('NameNotFilter', name => $key, packages => \@filter_packages)
Branch: 1 branch
BranchTrueFalseTotal
unless $filter_package 0 33 33
77 unless $filter_package;
78 33 debug 1, "Found $filter_package in \@INC";
79 33 return $filter_package;
80 }
81  
82 33 ▶sub _create_filter {
Subroutine _create_filter: called CC=1 SCAR=0.0
83 33 my ($self, $filter_package, $args) = @_;
84 33 debug 1, "Trying to create filter from $filter_package";
85 33 my $filter = $filter_package->new($args);
86 33 return $filter;
87 }
88  
89 21 ▶sub filters {
Subroutine __filters_for_exporter: called CC=11 SCAR=24.1
Subroutine filters: called CC=11 SCAR=24.1
Pod documented
90 21 my ($self, @proto) = @_;
91  
92 # handle a list of attributes with filters
93 21 my $attributes = shift @proto;
94 21 ▶ $attributes = [$attributes] unless ref $attributes;
Branch: 2 branches
BranchTrueFalseTotal
unless ref $attributes 20 1 21
unless ref $attributes 2 0 2
95 21 my @options = @proto;
96  
97 21 my (@filter_info) = ();
98 21 ▶ while(@options) {
Branch: 2 branches
BranchTrueFalseTotal
if (@options) 26 21 47
if (@options) 4 2 6
99 26 my $args;
100 26 my $key = shift(@options);
101 26 ▶ 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 25 26
if ((ref $key || '') eq 'CODE') { } 1 3 4
Condition100%4/4
ref $key || ''
l!l
125
ref $key || ''
l!l
13
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 25 $args = shift(@options);
110 }
111 26 push @filter_info, [$key, $args];
112 }
113
114 21 my @filters = ();
115 21 foreach my $info(@filter_info) {
116 26 my ($package_part, $args) = @$info;
117 26 my $filter_package = $self->_filter_package($package_part);
118
119 26 ▶ unless( (ref($args)||'') eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
unless ((ref $args || "") eq "HASH") 18 8 26
unless ((ref $args || "") eq "HASH") 3 1 4
Condition100%4/4
ref $args || ''
l!l
1115
ref $args || ''
l!l
22
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 18 $args = $filter_package->normalize_shortcut($args);
121 18 ▶ throw_exception InvalidFilterArgs => ( args => $args) unless ref($args) eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 18 18
unless ref $args eq "HASH" 0 3 3
122 }
123
124 26 $args->{attributes} = $attributes;
125 26 $args->{model} = $self;
126  
127 26 my $new_filter = $self->_create_filter($filter_package, $args);
128 26 push @filters, $new_filter;
129 }
130 25 ▶ my $coderef = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
131 25 my ($class, $attrs) = @_;
132 25 foreach my $filter (@filters) {
133 32 $attrs = $filter->filter($class, $attrs);
134 }
135 25 return $attrs;
136 21 };
137 21 $self->_filters_coderef($coderef);
138 }
139  
140 33 ▶sub _normalize_filter_package {
Subroutine _normalize_filter_package: called CC=4 SCAR=14.1
141 33 my ($self, $with) = @_;
142 33 my ($prefix, $package) = ($with =~m/^(\+?)(.+)$/);
143 33 ▶ return $package if $prefix eq '+';
Branch: 1 branch
BranchTrueFalseTotal
if $prefix eq "+" 0 33 33
144  
145 33 ▶ my $class = ref($self) || $self;
Condition33%1/3
ref $self || $self
l!l&&r!l&&!r
0330
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 33 my @parts = ((split '::', $class), $package);
147 33 my @project_inc = ();
148 33 ▶ while(@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 124 33 157
149 124 push @project_inc, join '::', (@parts, $class->default_filter_namepart, $package);
150 124 pop @parts;
151 }
152 33 return @project_inc;
153 }
154  
155 5 ▶sub filters_with {
Subroutine __filters_with_for_exporter: called CC=9 SCAR=22.3
156 5 my ($self, $proto, %options) = @_;
157 my @with = ref($proto) eq 'ARRAY' ?
158 0 ▶ @{$proto} : ($proto);
Branch: 1 branch
BranchTrueFalseTotal
ref $proto eq 'ARRAY' ? : 0 5 5
159  
160 5 my @filters = ();
161 5 FILTER_WITHS: foreach my $with (@with) {
162 5 ▶ if( (ref($with)||'') eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $with || "") eq "CODE") 2 3 5
Condition100%2/2
ref $with || ''
l!l
23
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 3 debug 1, "Trying to find a filter for '$with'";
167  
168 3 my $filter_package = $self->_filter_package($with);
169  
170 3 my $args;
171 3 ▶ unless((ref($args)||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless ((ref $args || "") eq "HASH") 3 0 3
Condition50%1/2
ref $args || ''
l!l
03
MC/DC0%0/1
ref $args || ''
ref $args
Truth table50%1/2
A
A= ref $args
Aresult
11
00
172 3 ▶ $args = $filter_package->can('normalize_shortcut') ? $filter_package->normalize_shortcut(\%options) : \%options;
Branch: 1 branch
BranchTrueFalseTotal
$filter_package->can('normalize_shortcut') ? : 1 2 3
173 3 ▶ throw_exception InvalidFilterArgs => ( args => $args) unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 3 3
174 }
175
176 3 $args->{model} = $self;
177  
178 3 my $new_filter = $self->_create_filter($filter_package, $args);
179 3 push @filters, $new_filter;
180  
181  
182 }
183 5 my $collection = use_module($self->default_filter_collection_class)
184 ->new(filters=>\@filters);
185 5 ▶ $self->_filters_coderef(sub { $collection->filter(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
186 }
187  
188 14 ▶sub _process_filters {
Subroutine _process_filters: called CC=2 SCAR=6.9
189 14 my ($class, $attrs) = @_;
190 14 foreach my $filter ($class->_filters) {
191 30 $attrs = $filter->($class, $attrs);
192 }
193 14 return $attrs;
194 }
195  
196 14 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
197 14 my ( $orig, $class, @args ) = @_;
198 14 my $attrs = $class->$orig(@args);
199 14 ▶ return $class->_process_filters($attrs) if $attrs;
Branch: 1 branch
BranchTrueFalseTotal
if $attrs 14 0 14
200 12 };
201  
202 12 1;
203  
204 =head1 NAME
205  
206 Valiant::Filterable - 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 =head2 When filters run
256  
257 B<Filters run once, at object construction time> (during C<BUILDARGS>). They
258 transform the values passed to the constructor and nothing more. They do
259 B<not> re-run when you later assign to a C<rw> attribute, and they do B<not>
260 run on ORM write paths such as L<DBIx::Class> C<update>/C<set_column>. If you
261 need a value coerced on every write, use a Moo/Moose attribute C<coerce> (or a
262 type constraint) instead of, or in addition to, a filter.
263  
264 =head1 CLASS METHODS
265  
266 =head2 filters
267  
268 Used to declare filters on an attribute. The first argument is either a scalar or arrayref of
269 scalars which should be attributes on your object:
270  
271 __PACKAGE__->filters( name => (...) );
272 __PACKAGE__->filters(['name', 'age'] => (...));
273  
274 Following arguments should be in one of two forms: a coderef or subroutine reference that contains
275 filter rules or a key - value pair which is a class and its arguments:
276  
277 __PACKAGE__->filters( name => (
278 trim => 1,
279 with => sub { my ($class, $attrs, $name) = @_; },
280 sub { my ($class, $attrs, $name) = @_; }m
281 ));
282  
283 When you use a Filter class (such as C<trim => { maximum => 25 }>) we resolve the class
284 name C<trim> in the following way. We first camel case the name and then look for a 'Filter' package
285 in the current class namespace. If we don't find a match we check each namespace up the hierarchy and
286 then check the two global namespaces C<Valiant::FilterX> and C<Validate::Filters>. For example if
287 you declare filters as in the example class C<Local::Model::User> we would look for the following:
288  
289 Local::Model::User::Filter::Trim
290 Local::Model:::Filter::Trim
291 Local::Filter::Trim
292 Validator::Trim
293 Valiant::FilterX::Trim
294 Valiant::Filter:::Trim
295  
296 These get checked in the order above and loaded and instantiated once at setup time.
297  
298 B<NOTE:> The namespace C<Valiant::Filter> is reserved for filters that ship with L<Valiant>. The
299 C<Valiant::FilterX> namespace is reserved for additional filters on CPAN that are packaged separately
300 from L<Valiant>. If you wish to share a custom fiter that you wrote the proper namespace to use on
301 CPAN is C<Valiant::FilterX>.
302  
303 You can also prepend your filter name with '+' which will cause L<Valiant> to ignore the namespace
304 resolution and try to load the class directly. For example:
305  
306 __PACKAGE__->filters(name => ('+App::MyFilter' => {}), );
307  
308 Will try to load the class C<App::MyFilter> and use it as a filter directly (or throw an exception if
309 it fails to load).
310  
311 =head2 filters_with
312  
313 C<filters_with> is intended to process filters that are on the class as a whole, or which are very
314 complex and can't easily be assigned to a single attribute. It accepts either a subroutine reference
315 with an optional hash of key value pair options (which are passed to C<$opts>) or a scalar name which
316 should be a stand alone filter class (basically a class that does the C<filters> method although
317 you should consume the L<Validate::Filter> role to enforce the contract).
318  
319 __PACKAGE__->filters_with(sub {
320 my ($self, $class, $attrs)) = @_;
321 ...
322 });
323  
324 __PACKAGE__->filters_with(\&check_object => (arg1=>'foo', arg2=>'bar'));
325  
326 sub filters_with {
327 my ($self, $class, $attrs) = @_;
328 ...
329 }
330  
331 __PACKAGE__->filters_with( 'Custom' => (arg1=>'foo', arg2=>'bar'));
332  
333 If you pass a string that is a filter class we resolve its namespace using the same approach as
334 detailed above for C<filters>. Any arguments are passed to the C<new> method of the found class.
335  
336 =head1 AUTHOR
337
338 John Napiorkowski L<email:jjnapiork@cpan.org>
339
340 =head1 SEE ALSO
341
342 L<Valiant::Filters>
343  
344 =head1 COPYRIGHT & LICENSE
345
346 Copyright 2020, John Napiorkowski L<email:jjnapiork@cpan.org>
347
348 This library is free software; you can redistribute it and/or modify it under
349 the same terms as Perl itself.
350  
351 =cut
352  
« Valiant/JSON/JSONBuilder.pm ↑ Summary Valiant/Translation.pm »