Valiant/Errors.pm

filter: Statementstmt 83.5% 142 / 170 Branchbran 69.5% 32 / 46 Conditioncond 50.0% 16 / 32 MC/DCmcdc 25.0% 5 / 20 Subroutinesub 75.5% 37 / 49 Podpod 62.5% 20 / 32 totaltotal 72.2% 252 / 349 CC 45 SCAR 14.6
CC
45
Cov
77%
added
20.0
add
10.3
as_json
6.0
CRAP 4.3
« Valiant/Validator/Unique.pm ↑ Summary Valiant/Validator/OnlyOf.pm »
1 package Valiant::Errors;
2  
3 47 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 47 ▶use Data::Perl::Collection::Array;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 47 ▶use Valiant::NestedError;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 47 ▶use Valiant::Util 'throw_exception';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 use overload (
9 28 ▶ bool => sub { shift->size ? 1:0 },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
(shift())->size ? : 28 0 28
10 47 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 47 has 'object' => (
13 is => 'ro',
14 required => 1,
15 weak_ref => 1,
16 );
17  
18 has errors => (
19 is => 'ro',
20 init_arg => undef,
21 lazy => 1,
22 required => 1,
23 342 ▶ default => sub { Data::Perl::Collection::Array->new() },
Subroutine __ANON__: called CC=1 SCAR=0.0
24 47 handles => {
25 size => 'count',
26 count => 'count',
27 clear => 'clear',
28 blank => 'is_empty',
29 empty => 'is_empty',
30 }
31 );
32  
33 3 ▶sub i18n_class { 'Valiant::I18N' }
Subroutine i18n_class: called CC=1 SCAR=0.0
Pod undocumented
34  
35 has 'i18n' => (
36 is => 'ro',
37 required => 1,
38 3 ▶ default => sub { Module::Runtime::use_module(shift->i18n_class) },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 47 );
40  
41 445 ▶sub error_class { 'Valiant::Error' }
Subroutine error_class: called CC=1 SCAR=0.0
Pod undocumented
42  
43 # return a flat list of all errors with duplicated removed. To we probably
44 # need to make use the the equals method on Valiant::Error
45 0 ▶sub uniq { die 'todo' }
Subroutine uniq: not called CC=1 SCAR=6.9
Pod undocumented
46  
47 sub any {
48 2 ▶ my ($self, $code) = @_;
Subroutine any: called CC=4 SCAR=14.5
Pod documented
49 2 ▶ $code ||= sub { $_ };
Subroutine __ANON__: not called CC=1 SCAR=2.0
Condition33%1/3
$code ||= sub {
l!l&&r!l&&!r
200
MC/DC0%0/2
$code ||= sub { $_; }
$code sub { $_; }
Truth table33%1/3
A ||= B
A= $codeB= sub { $_; }
ABresult
1X1
011
000
50 2 foreach my $error ($self->errors->all) {
51 10 local $_ = $error;
52 10 ▶ return 1 if $code->($error);
Branch: 1 branch
BranchTrueFalseTotal
if &$code($error) 1 9 10
53 }
54 1 return 0;
55 }
56  
57 sub copy {
58 1 ▶ my ($self, $other) = @_;
Subroutine copy: called CC=1 SCAR=0.0
Pod documented
59 my $errors = $other
60 ->errors
61 ->map(sub {
62 8 ▶ my $class = ref $_;
Subroutine __ANON__: called CC=1 SCAR=0.0
63 8 my $new = $class->new(
64 object => $self->object,
65 attribute => $_->attribute,
66 type => $_->type,
67 i18n => $_->i18n,
68 options => $_->options,
69 );
70 8 return $new;
71 1 });
72 1 $self->errors->clear;
73 1 $self->errors->push($errors->all);
74 }
75  
76 sub import_error {
77 103 ▶ my ($self, $error, $options) = @_;
Subroutine import_error: called CC=2 SCAR=6.9
Pod documented
78 $self->errors->push(
79 my $nested_err = Valiant::NestedError->new(
80 inner_error => $error,
81 object => $error->object,
82 attribute => $error->attribute,
83 103 ▶ %{ $options||+{} },
Branch: 1 branch
BranchTrueFalseTotal
$options or {} 5 98 103
84 )
85 );
86 }
87  
88 sub merge {
89 1 ▶ my ($self, $other) = @_;
Subroutine merge: called CC=2 SCAR=6.9
Pod documented
90 1 foreach my $error ($other->errors->all) {
91 4 $self->import_error($error);
92 }
93 }
94  
95 sub where {
96 320 ▶ my $self = shift;
Subroutine where: called CC=1 SCAR=0.0
Pod documented
97 320 my ($attribute, $type, $options) = $self->_normalize_arguments(@_);
98 return $self->errors->grep(sub {
99 2637 ▶ $_->match($attribute, $type, $options);
Subroutine __ANON__: called CC=1 SCAR=0.0
100 320 })->all;
101 }
102  
103 sub _normalize_arguments {
104 768 ▶ my ($self, $attribute, $type, $options) = @_;
Subroutine _normalize_arguments: called CC=3 SCAR=12.0
105 768 ▶ if(ref($type) && ref($type) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $type and ref $type eq "CODE") 0 768 768
Condition66%2/3
ref $type and ref $type eq "CODE"
!ll&&!rl&&r
4503180
MC/DC0%0/2
ref $type and ref $type eq "CODE"
ref $type ref $type eq "CODE"
Truth table66%2/3
A and B
A= ref $typeB= ref $type eq "CODE"
ABresult
0X0
100
111
106 0 $type = $type->($self->object, $options);
107 }
108 return (
109 768 $attribute,
110 $type,
111 $options,
112 );
113 }
114  
115 # Returns +true+ if the error messages include an error for the given key
116 # +attribute+, +false+ otherwise.
117 sub include {
118 0 ▶ my ($self, $attribute) = @_;
Subroutine include: not called CC=1 SCAR=6.9
Pod documented
119 return scalar($self->any(sub {
120 0 ▶ $_->match($attribute);
Subroutine __ANON__: not called CC=1 SCAR=6.9
121 0 }));
122 }
123 47 *has_key = \&include;
124  
125 # Delete messages for +key+. Returns the deleted messages.
126 sub delete {
127 1 ▶ my $self = shift;
Subroutine delete: called CC=3 SCAR=11.0
Pod documented
128 1 my ($attribute, $type, $options) = $self->_normalize_arguments(@_);
129 1 my @deleted = ();
130 1 my $idx = 0;
131 1 foreach my $error($self->errors->all) {
132 8 ▶ if($error->match($attribute, $type, $options)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error->match($attribute, $type, $options)) { } 4 4 8
133 4 push @deleted, $self->errors->delete($idx);
134 } else {
135 4 $idx++
136 }
137 }
138 1 return @deleted;
139 }
140  
141 sub each {
142 17 ▶ my ($self, $block) = @_;
Subroutine each: called CC=3 SCAR=11.2
Pod documented
143 17 foreach my $error($self->errors->all) {
144 39 ▶ $block->((defined($error->attribute) ? $error->attribute : '*'), $error->message);
Branch: 1 branch
BranchTrueFalseTotal
defined $error->attribute ? : 39 0 39
145 }
146 }
147  
148 sub model_errors {
149 21 ▶ my $self = shift;
Subroutine model_errors: called CC=4 SCAR=13.9
Pod undocumented
150 21 my @errors;
151 21 foreach my $error($self->errors->all) {
152 148 ▶ push @errors, $error if !$error->has_attribute || !defined($error->attribute);
Branch: 1 branch
BranchTrueFalseTotal
unless $error->has_attribute and defined $error->attribute 16 132 148
Condition66%2/3
$error->has_attribute and defined $error->attribute
!ll&&!rl&&r
016132
MC/DC50%1/2
$error->has_attribute and defined $error->attribute
$error->has_attribute defined $error->attribute
Truth table66%2/3
A and B
A= $error->has_attributeB= defined $error->attribute
ABresult
0X0
100
111
153 }
154 21 return @errors;
155 }
156  
157 sub model_messages {
158 21 ▶ my ($self, $full_messages_flag) = @_;
Subroutine model_messages: called CC=2 SCAR=7.1
Pod documented
159 return map {
160 # AFAIK the full_messages_flag does nothing for model errors
161 21 ▶ $full_messages_flag ? $_->full_message : $_->message
Branch: 1 branch
BranchTrueFalseTotal
$full_messages_flag ? : 0 16 16
162 } $self->model_errors;
163 }
164  
165 sub attribute_errors {
166 4 ▶ my $self = shift;
Subroutine attribute_errors: called CC=4 SCAR=13.9
Pod undocumented
167 4 my @errors;
168 4 foreach my $error($self->errors->all) {
169 33 ▶ push @errors, $error if $error->has_attribute and defined($error->attribute);
Branch: 1 branch
BranchTrueFalseTotal
if $error->has_attribute and defined $error->attribute 29 4 33
Condition66%2/3
$error->has_attribute and defined $error->attribute
!ll&&!rl&&r
0429
MC/DC50%1/2
$error->has_attribute and defined $error->attribute
$error->has_attribute defined $error->attribute
Truth table66%2/3
A and B
A= $error->has_attributeB= defined $error->attribute
ABresult
0X0
100
111
170 }
171 4 return @errors;
172 }
173  
174 sub attribute_messages {
175 1 ▶ my ($self) = @_;
Subroutine attribute_messages: called CC=1 SCAR=0.0
Pod documented
176 return map {
177 1 $_->message;
178 } $self->attribute_errors;
179 }
180  
181 sub full_attribute_messages {
182 3 ▶ my ($self) = @_;
Subroutine full_attribute_messages: called CC=1 SCAR=0.0
Pod documented
183 return map {
184 3 $_->full_message;
185 } $self->attribute_errors;
186 }
187  
188  
189 sub group_by_attribute {
190 136 ▶ my $self = shift;
Subroutine group_by_attribute: called CC=4 SCAR=13.9
Pod undocumented
191 136 my %attributes;
192 136 foreach my $error($self->errors->all) {
193 435 ▶ next unless $error->has_attribute;
Branch: 1 branch
BranchTrueFalseTotal
unless $error->has_attribute 0 435 435
194 435 ▶ push @{$attributes{$error->attribute||'*'}}, $error;
Condition100%2/2
$error->attribute || '*'
l!l
41718
MC/DC100%1/1
$error->attribute || '*'
$error->attribute
Truth table100%2/2
A
A= $error->attribute
Aresult
11
00
195 }
196 136 return %attributes;
197 }
198  
199 # Returns a Hash of attributes with their error messages. If +full_messages+
200 # is +true+, it will contain full messages (see +full_message+).
201 sub to_hash {
202 136 ▶ my ($self, $full_messages_flag) = @_;
Subroutine to_hash: called CC=4 SCAR=13.9
Pod documented
203 136 my %hash = ();
204 136 my %grouped = $self->group_by_attribute;
205 136 foreach my $attr (keys %grouped) {
206 $hash{$attr} = [
207 map {
208 435 ▶ $full_messages_flag ? $_->full_message : $_->message
Branch: 1 branch
BranchTrueFalseTotal
$full_messages_flag ? : 339 96 435
209 335 ▶ } @{ $grouped{$attr}||[] }
Branch: 1 branch
BranchTrueFalseTotal
$grouped{$attr} or [] 0 335 335
210 ];
211 }
212 136 return %hash;
213 }
214  
215 sub as_json {
216 0 ▶ my ($self, @args) = @_;
Subroutine as_json: not called CC=2 SCAR=17.9
Pod undocumented
217 0 ▶ return $self->object->errors_as_json($self) if $self->object->can('errors_as_json');
Branch: 1 branch
BranchTrueFalseTotal
if $self->object->can("errors_as_json") 0 0 0
218 0 return $self->as_rfc_7807;
219 }
220  
221 sub as_rfc_7807 {
222 2 ▶ my $self = shift;
Subroutine as_rfc_7807: called CC=3 SCAR=11.0
Pod documented
223 2 my %hash = $self->to_hash(1);
224  
225 2 my %rfc = (fields => {}, general => []);
226 2 foreach my $field (keys %hash) {
227 12 ▶ if ($field eq '*') {
Branch: 1 branch
BranchTrueFalseTotal
if ($field eq '*') { } 1 11 12
228 # General errors
229 1 push @{ $rfc{general} }, @{ $hash{$field} };
230 } else {
231 # Field-specific errors
232 11 $rfc{fields}->{$field} = $hash{$field};
233 }
234 }
235 2 return \%rfc;
236 }
237  
238 0 ▶sub TO_JSON { shift->as_json }
Subroutine TO_JSON: not called CC=1 SCAR=6.9
Pod undocumented
239  
240 # Adds +message+ to the error messages and used validator type to +details+ on +attribute+.
241 # More than one error can be added to the same +attribute+.
242 sub add {
243 445 ▶ my ($self, $attribute, $type, $options) = @_;
Subroutine add: called CC=10 SCAR=23.4
Pod documented
244 445 ▶ unless(defined($type)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type) 1 444 445
245 1 $type = $self->i18n->make_tag('invalid');
246 }
247 445 ▶ $options ||= +{};
Condition100%2/2
$options ||= {}
l!l
34798
MC/DC100%1/1
$options ||= {}
$options
Truth table100%2/2
A
A= $options
Aresult
11
00
248 445 ($attribute, $type, $options) = $self->_normalize_arguments($attribute, $type, $options);
249 445 my $error = $self->build_error($attribute, $type, $options);
250 445 ▶ if(my $exception = $options->{strict}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $exception = $options->{"strict"}) 3 442 445
251 3 my $message = $error->full_message;
252 3 ▶ throw_exception('Strict' => (msg=>$message)) if $exception =~m/^\d+$/ && $exception == 1;
Branch: 1 branch
BranchTrueFalseTotal
if $exception =~ /^\d+$/ and $exception == 1 1 2 3
Condition66%2/3
$exception =~ /^\d+$/ and $exception == 1
!ll&&!rl&&r
201
MC/DC50%1/2
$exception =~ /^\d+$/ and $exception == 1
$exception =~ /^\d+$/ $exception == 1
Truth table66%2/3
A and B
A= $exception =~ /^\d+$/B= $exception == 1
ABresult
0X0
100
111
253 2 ▶ throw_exception('Strict' => (msg=>$exception)) if( (ref(\$exception)||'') eq 'SCALAR');
Branch: 1 branch
BranchTrueFalseTotal
if (ref \$exception || "") eq "SCALAR" 1 1 2
Condition50%1/2
ref \$exception || ''
l!l
20
MC/DC0%0/1
ref \$exception || ''
ref \$exception
Truth table50%1/2
A
A= ref \$exception
Aresult
11
00
254 1 ▶ $exception->($self->object, $message) if( (ref($exception)||'') eq 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
if (ref $exception || "") eq "CODE" 1 0 1
Condition50%1/2
ref $exception || ''
l!l
10
MC/DC0%0/1
ref $exception || ''
ref $exception
Truth table50%1/2
A
A= ref $exception
Aresult
11
00
255 0 $exception->throw($message); # If not 1 then assume its a package name or exception object.
256 }
257
258 442 $self->errors->push($error);
259 442 return $error;
260 }
261  
262 sub build_error {
263 445 ▶ my ($self, $attribute, $type, $options) = @_;
Subroutine build_error: called CC=1 SCAR=0.0
Pod undocumented
264  
265 445 return my $error = $self->error_class
266 ->new(
267 object => $self->object,
268 attribute => $attribute,
269 type => $type,
270 i18n => $self->i18n,
271 options => $options,
272 );
273 }
274  
275 # Returns +true+ if an error on the attribute with the given message is
276 # present, or +false+ otherwise. +message+ is treated the same as for +add+. ~
277 sub added {
278 0 ▶ my ($self, $attribute, $type, $options) = @_;
Subroutine added: not called CC=4 SCAR=30.0
Pod documented
279  
280 ## TODO ok so if the $attribute refers to an object which can->errors maybe we
281 ## need to call $self->$attribute->errors->add(undef, $type, $options) instead
282 ## so that any global errors to a nested object end in in the right place?
283 ## Afterwards we need to associate the nested object errors to $self so that
284 ## we know errors exist (for stuff like to_hash and all_errors, etc.
285  
286 0 ▶ $type ||= $self->i18n->make_tag('invalid');
Condition0%0/3
$type ||= $self->i18n->make_tag("invalid")
l!l&&r!l&&!r
000
MC/DC0%0/2
$type ||= $self->i18n->make_tag("invalid")
$type $self->i18n->make_tag("invalid")
Truth table0%0/3
A ||= B
A= $typeB= $self->i18n->make_tag("invalid")
ABresult
1X1
011
000
287 0 ($attribute, $type, $options) = $self->_normalize_arguments($attribute, $type, $options);
288 0 ▶ if($self->i18n->is_i18n_tag($type)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->i18n->is_i18n_tag($type)) { } 0 0 0
289 return $self->any(sub {
290 0 ▶ $_->strict_match($attribute, $type, $options);
Subroutine __ANON__: not called CC=1 SCAR=6.9
291 0 });
292 } else {
293 return scalar(grep {
294 0 ▶ $_ eq $type;
Branch: 1 branch
BranchTrueFalseTotal
scalar grep({$_ eq $type;} $self->messages_for($attribute)) ? : 0 0 0
295 } $self->messages_for($attribute)) ? 1:0
296 }
297 }
298  
299 # Similar to ->added except we don't care about options
300 sub of_kind {
301 2 ▶ my ($self, $attribute, $type) = @_;
Subroutine of_kind: called CC=4 SCAR=15.2
Pod documented
302 2 ▶ $type ||= $self->i18n->make_tag('invalid');
Condition33%1/3
$type ||= $self->i18n->make_tag("invalid")
l!l&&r!l&&!r
200
MC/DC0%0/2
$type ||= $self->i18n->make_tag("invalid")
$type $self->i18n->make_tag("invalid")
Truth table33%1/3
A ||= B
A= $typeB= $self->i18n->make_tag("invalid")
ABresult
1X1
011
000
303 2 ($attribute, $type) = $self->_normalize_arguments($attribute, $type);
304 2 ▶ if($self->i18n->is_i18n_tag($type)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->i18n->is_i18n_tag($type)) { } 0 2 2
305 return $self->any(sub {
306 0 ▶ $_->strict_match($attribute, $type);
Subroutine __ANON__: not called CC=1 SCAR=6.9
307 0 });
308 } else {
309 return scalar(grep {
310 2 ▶ $_ eq $type;
Branch: 1 branch
BranchTrueFalseTotal
scalar grep({$_ eq $type;} $self->messages_for($attribute)) ? : 1 1 2
311 } $self->messages_for($attribute)) ? 1:0
312 }
313 }
314  
315 1 ▶sub messages { map { $_->message } shift->errors->all }
Subroutine messages: called CC=1 SCAR=0.0
Pod documented
316
317 sub full_messages {
318 4 ▶ my $self = shift;
Subroutine full_messages: called CC=1 SCAR=0.0
Pod documented
319 4 $self->full_messages_collection->all;
320 }
321  
322 sub full_messages_collection {
323 4 ▶ my $self = shift;
Subroutine full_messages_collection: called CC=1 SCAR=0.0
Pod undocumented
324 4 ▶ return $self->errors->map(sub { $_->full_message });
Subroutine __ANON__: called CC=1 SCAR=0.0
325 }
326  
327  
328 sub full_messages_for {
329 52 ▶ my ($self, $attribute) = @_;
Subroutine full_messages_for: called CC=1 SCAR=0.0
Pod documented
330 return map {
331 52 $_->full_message
332 } $self->where($attribute);
333 }
334  
335 sub messages_for {
336 4 ▶ my ($self, $attribute) = @_;
Subroutine messages_for: called CC=1 SCAR=0.0
Pod documented
337 return map {
338 4 $_->message
339 } $self->where($attribute)
340 }
341  
342 sub full_message {
343 0 ▶ my ($self, $attribute, $message) = @_;
Subroutine full_message: not called CC=1 SCAR=6.9
Pod undocumented
344 0 $self->error_class->full_message(
345 $attribute,
346 $message,
347 $self->object,
348 $self->i18n);
349 }
350  
351 sub generate_message {
352 0 ▶ my ($self, $attribute, $type, $options) = @_;
Subroutine generate_message: not called CC=2 SCAR=17.9
Pod undocumented
353 0 ▶ $type ||= $self->i18n->make_tag('invalid');
Condition0%0/3
$type ||= $self->i18n->make_tag("invalid")
l!l&&r!l&&!r
000
MC/DC0%0/2
$type ||= $self->i18n->make_tag("invalid")
$type $self->i18n->make_tag("invalid")
Truth table0%0/3
A ||= B
A= $typeB= $self->i18n->make_tag("invalid")
ABresult
1X1
011
000
354 0 return $self->error_class->generate_message(
355 $attribute,
356 $type,
357 $self->object,
358 $options,
359 $self->i18n);
360 }
361  
362 sub _dump {
363 0 ▶ require Data::Dumper;
Subroutine _dump: not called CC=1 SCAR=6.9
364 0 return Data::Dumper::Dumper( +{shift->to_hash(full_messages=>1)} );
365 }
366  
367 47 1;
368  
369 =head1 NAME
370  
371 Valiant::Errors - A collection of errors associated with an object
372  
373 =head1 SYNOPSIS
374  
375 =head1 DESCRIPTION
376  
377 A collection of errors (each instances of L<Valiant::Error>) associated with attributes
378 or a model. This class provides methods for adding, retrieving and introspecting
379 error, typically via a L<Valiant::Validator> or L<Valiant::Validator::Each> subclass.
380  
381 The goal of this class is to make it as easy as possible to work with and understand
382 errors that have been added to your instance. In general you will never make an instance
383 of this directly since it will be used via the L<Valiant::Validates> role.
384  
385 =head1 ATTRIBUTES
386  
387 This class defined the following attributes
388  
389 =head2 object
390  
391 This is a weak reference to the object which the errors belong to.
392  
393 =head2 errors
394  
395 This is an instance of L<Data::Perl::Collection::Array> which in a collection of
396 L<Valiant::Error> objects added by validators.
397  
398 =head2 i18n
399  
400 The internationalization and translation class. Generally this is an instance of
401 L<Valiant::I18N>. You won't need to supply this as it normally is built automatically.
402  
403 =head1 METHODS
404  
405 The class defines the following methods
406  
407 =head2 count
408  
409 =head2 size
410  
411 The number of errors collected. If there are no errors then the size is 0.
412  
413 =head2 empty
414  
415 =head2 blank
416  
417 Returns true if there are no errors collected.
418  
419 =head2 any(\&code)
420  
421 Accepts a coderef that will receive each error object in the collect and return true
422 if any of the coderef calls return true. Used to determine if the errors collection
423 contains at least one type of error.
424  
425 my $has_invalids = $user1->errors->any(sub {
426 ${\$_->type} eq 'invalid';
427 });
428  
429 =head2 copy
430  
431 Copy an errors collection into the current (replacing any existing). The copies are
432 new instances of L<Valiant::Error>, not references to the original objects.
433  
434 =head2 import_error ($error)
435  
436 Given a single L<Valiant::Error> inport it into the current errors collection
437  
438 =head2 merge ($collectio)
439  
440 Given a L<Valiant::Errors> collection, merge it into the current one.
441  
442 =head2 where ($attribute, $message, \%options)
443  
444 return all the L<Valiant::Error> objects in the current collection which match criteria.
445  
446 =head2 include ($attribute)
447  
448 Returns +true+ if the error messages include an error for the given key
449 +attribute+, +false+ otherwise.
450  
451 =head2 delete ($attribute)
452  
453 Delete messages for +key+. Returns the deleted messages.
454  
455 =head2 each ($coderef)
456  
457 Iterates through each error key, value pair in the error messages hash.
458 Yields the attribute and the error for that attribute. If the attribute
459 has more than one error message, yields once for each error message.
460  
461 $object->errors->each(sub {
462 my ($attribute, $message) = @_;
463 });
464  
465 If the error is a model error then C<$attribute> will be '*'.
466  
467 =head2 model_messages
468  
469 Returns an array of all the errors that are associated with the model (Localized
470 if needed).
471  
472 =head2 attribute_messages
473  
474 Returns an array of all the errors that are associated with attributes (localized if needed).
475  
476 =head2 full_attribute_messages
477  
478 Returns an array of the full messages of all attributes (localized if needed).
479  
480 =head2 to_hash (?$flag)
481  
482 Returns a hash where each key is an attribute (or '*' for the model) and
483 each value is an arrayref of errors. C<?$flag> when true will return
484 the full messages for each error.
485  
486 =head2 add ($attribute|undef, $message, \%opts)
487  
488 Add a new error message to the object. Error can be associated with an attribute
489 or with the object itself. C<$message> can be one of:
490  
491 =over 14
492  
493 =item A string
494  
495 If a string this is the error message recorded.
496  
497 validates name => (
498 format => 'alphabetic',
499 length => [3,20],
500 message => 'Unacceptable Name',
501 );
502  
503 =item A translation tag
504  
505 use Valiant::I18N;
506  
507 validates name => (
508 format => 'alphabetic',
509 length => [3,20],
510 message => _t('bad_name'),
511 );
512  
513 This will look up a translated version of the tag. See L<Valiant::I18N> for more details.
514  
515 =item A scalar reference
516  
517 validates name => (
518 format => 'alphabetic',
519 length => [3,20],
520 message => \'Unacceptable {{attribute}}',
521 );
522  
523 Similar to string but we will expand any placeholder variables which are indicated by the
524 '{{' and '}}' tokens (which are removed from the final string). You can use any placeholder
525 that is a key in the options hash (and you can pass additional values when you add an error).
526 By default the following placeholder expansions are available attribute (the attribute name),
527 value (the current attribute value), model (the human name of the model containing the
528 attribute and object (the actual object instance that has the error).
529  
530 =item A subroutine reference
531  
532 validates name => (
533 format => 'alphabetic',
534 length => [3,20],
535 message => sub {
536 my ($self, $attr, $value, $opts) = @_;
537 return "Unacceptable $attr!";
538 }
539 );
540  
541 Similar to the scalar reference option just more flexible since you can write custom code
542 to build the error message. For example you could return different error messages based on
543 the identity of a person. Also if you return a translation tag instead of a simple string
544 we will attempt to resolve it to a translated string (see L<Valiant::I18N>).
545  
546 =back
547  
548 =head2 added ($attribute|undef, $message, \%opts)
549  
550 Return true if the error has already been created.
551  
552 =head2 of_kind ($attribute|undef, $message)
553  
554 Similar to <added> expect we don't need to match options
555  
556 =head2 messages
557  
558 An array of the error messages. All translation tags will be translated to strings in the
559 expected local langauge.
560  
561 =head2 full_messages
562  
563 An array of the full messages (localized if needed).
564  
565 =head2 messages_for ($attribute)
566  
567 An array of all the messages for the given attribute (localized if needed).
568  
569 =head2 full_messages_for ($attribute)
570  
571 An array of all the full messages for the given attribute (localized if needed).
572  
573 =head2 as_rfc_7807
574  
575 Returns a hashref suitable for contstructing an error response compatible with
576 RFC-7807, an open standard for returning errors formated in JSON from web APIs.
577  
578 Example response:
579  
580 {
581 fields => {
582 attendees => [
583 "Attendees Are Invalid",
584 ],
585 "attendees[0].role" => [
586 "Attendees Role is too short (minimum is 2 characters)",
587 ],
588 "attendees[1].role" => [
589 "Attendees Role is too short (minimum is 2 characters)",
590 ],
591 },
592 general => [
593 "A model error",
594 ],
595 }
596  
597 You can use this to construct the C<errors> field of a compliant response. Here's how
598 A full response might look like encoded in JSON.
599  
600 {
601 "type": "https://example.com/probs/validation-error",
602 "title": "Validation Error",
603 "status": 400,
604 "detail": "There are validation errors in your request.",
605 "errors": {
606 "fields": {
607 "attendees": [
608 "Attendees Are Invalid"
609 ],
610 "attendees[0].role": [
611 "Attendees Role is too short (minimum is 2 characters)"
612 ],
613 "attendees[1].role": [
614 "Attendees Role is too short (minimum is 2 characters)"
615 ]
616 },
617 "general": [
618 "A model error"
619 ]
620 }
621 }
622  
623 =head1 JSONification
624  
625 This class provides a C<TO_JSON> method suitable for use in some of the common
626 JSON serializers. When supported it will delegate the job of turning the object
627 into a hash that can be serialized to JSON to the C<as_rfc_7807> method.
628  
629 If you wish to overide this, you can have your model object provide a method
630 C<errors_as_json> which will recieve the errors object as an argument and then
631 you can format it as you wish. This method should return a hash or array reference
632 that can be passed to one of the standard C<JSON> encoders.
633  
634 =head1 SEE ALSO
635
636 L<Valiant>, L<Valiant::Error>.
637  
638 =head1 AUTHOR
639
640 See L<Valiant>
641
642 =head1 COPYRIGHT & LICENSE
643
644 See L<Valiant>
645  
646 =cut
647  
648 47 1;
« Valiant/Validator/Unique.pm ↑ Summary Valiant/Validator/OnlyOf.pm »