File: Joi.pm

package info (click to toggle)
libjson-validator-perl 5.14%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,160 kB
  • sloc: perl: 3,015; makefile: 14
file content (486 lines) | stat: -rw-r--r-- 10,709 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package JSON::Validator::Joi;
use Mojo::Base -base;
use Exporter 'import';

use List::Util qw(uniq);
use Mojo::JSON qw(false true);
use Mojo::Util;
use Scalar::Util qw(blessed);
use Storable qw(dclone);

our @EXPORT_OK = qw(joi);

# Avoid "Subroutine redefined" warnings
require JSON::Validator::Schema::Draft7;

has enum      => sub { +[] };
has type      => 'object';
has validator => sub { JSON::Validator::Schema::Draft7->new->coerce('booleans,numbers,strings') };

has [qw(format max min multiple_of regex)];

for my $attr (qw(required strict unique)) {
  Mojo::Util::monkey_patch(__PACKAGE__, $attr => sub { $_[0]->{$attr} = $_[1] // 1; $_[0]; });
}

sub alphanum { shift->_type('string')->regex('^\w*$') }
sub boolean  { shift->type('boolean') }

sub compile {
  my $self   = shift;
  my $merged = {};

  for (ref $self->type eq 'ARRAY' ? @{$self->type} : $self->type) {
    my $method   = "_compile_$_";
    my $compiled = $self->$method;
    @$merged{keys %$compiled} = values %$compiled;
  }

  return $merged;
}

sub date_time { shift->_type('string')->format('date-time') }
sub email     { shift->_type('string')->format('email') }

sub extend {
  my ($self, $by) = @_;
  die "Cannot extend joi '@{[$self->type]}' by '@{[$by->type]}'" unless $self->type eq $by->type;

  my $clone = shift->new(dclone($self));

  for my $key (keys %$by) {
    my $ref = ref $by->{$key};
    $clone->{$key} = $by->{$key} unless $ref eq 'ARRAY' or $ref eq 'HASH';
  }

  if ($self->type eq 'array') {
    $clone->{items} = dclone($by->{items}) if $by->{items};
  }
  elsif ($self->type eq 'object') {
    $clone->{required_props} = [uniq @{$clone->{required_props}}, @{$by->{required_props}}]
      if defined $by->{required_props};
    $clone->{properties}{$_} = dclone($by->{properties}{$_}) for keys %{$by->{properties} || {}};
  }

  return $clone;
}

sub array     { shift->type('array') }
sub integer   { shift->type('integer') }
sub iso_date  { shift->date_time }
sub items     { $_[0]->{items} = $_[1]; $_[0] }
sub joi       { __PACKAGE__->new(@_) }
sub length    { shift->min($_[0])->max($_[0]) }
sub lowercase { shift->_type('string')->regex('^\p{Lowercase}*$') }
sub negative  { shift->_type('number')->max(0) }
sub number    { shift->type('number') }
sub object    { shift->type('object') }
sub pattern   { shift->regex(@_) }
sub positive  { shift->number->min(0) }

sub props {
  my $self       = shift->type('object');
  my %properties = ref $_[0] ? %{$_[0]} : @_;

  while (my ($name, $property) = each %properties) {
    push @{$self->{required_props}}, $name if $property->{required};
    $self->{properties}{$name} = $property->compile;
  }

  return $self;
}

sub string    { shift->type('string') }
sub token     { shift->_type('string')->regex('^[a-zA-Z0-9_]+$') }
sub uppercase { shift->_type('string')->regex('^\p{Uppercase}*$') }
sub uri       { shift->_type('string')->format('uri') }

sub validate {
  my ($self, $data) = @_;
  return $self->validator->data($self->compile)->validate($data);
}

sub _compile_array {
  my $self = shift;
  my $json = {type => $self->type};

  $json->{additionalItems} = false        if $self->{strict};
  $json->{maxItems}        = $self->{max} if defined $self->{max};
  $json->{minItems}        = $self->{min} if defined $self->{min};
  $json->{uniqueItems}     = true         if $self->{unique};

  if ($self->{items}) {
    $json->{items} = $self->{items};
    for my $item (ref $json->{items} eq 'ARRAY' ? @{$json->{items}} : $json->{items}) {
      $item = $item->compile if blessed $item and $item->can('compile');
    }
  }

  return $json;
}

sub _compile_boolean { +{type => 'boolean'} }

sub _compile_integer { shift->_compile_number }

sub _compile_null { {type => shift->type} }

sub _compile_number {
  my $self = shift;
  my $json = {type => $self->type};

  $json->{enum}       = $self->{enum}        if defined $self->{enum} and @{$self->{enum}};
  $json->{maximum}    = $self->{max}         if defined $self->{max};
  $json->{minimum}    = $self->{min}         if defined $self->{min};
  $json->{multipleOf} = $self->{multiple_of} if defined $self->{multiple_of};

  return $json;
}

sub _compile_object {
  my $self = shift;
  my $json = {type => $self->type};

  $json->{additionalProperties} = false                   if $self->{strict};
  $json->{maxProperties}        = $self->{max}            if defined $self->{max};
  $json->{minProperties}        = $self->{min}            if defined $self->{min};
  $json->{patternProperties}    = $self->{regex}          if $self->{regex};
  $json->{properties}           = $self->{properties}     if ref $self->{properties} eq 'HASH';
  $json->{required}             = $self->{required_props} if defined $self->{required_props};

  return $json;
}

sub _compile_string {
  my $self = shift;
  my $json = {type => $self->type};

  $json->{enum}      = $self->{enum}   if defined $self->{enum} and @{$self->{enum}};
  $json->{format}    = $self->{format} if defined $self->{format};
  $json->{maxLength} = $self->{max}    if defined $self->{max};
  $json->{minLength} = $self->{min}    if defined $self->{min};
  $json->{pattern}   = $self->{regex}  if defined $self->{regex};

  return $json;
}

sub _type {
  $_[0]->{type} = $_[1] unless $_[0]->{type};
  return $_[0];
}

sub TO_JSON { shift->compile }

1;

=encoding utf8

=head1 NAME

JSON::Validator::Joi - Joi validation sugar for JSON::Validator

=head1 SYNOPSIS

  use JSON::Validator::Joi "joi";

  my @errors = joi->object->props(
    age   => joi->integer->min(0)->max(200),
    email => joi->regex(".@.")->required,
    name  => joi->string->min(1),
  )->validate({
    name  => "Jan Henning",
    age   => 34,
    email => "jhthorsen@cpan.org",
  });

  die "@errors" if @errors;

=head2 EXPORTED FUNCTIONS

=head2 joi

  $joi = joi(%attrs);

Same as:

  JSON::Validator::Joi->new(%attrs);

=head1 DESCRIPTION

L<JSON::Validator::Joi> is an elegant DSL schema-builder. The main purpose is
to build a L<JSON Schema|https://json-schema.org/> for L<JSON::Validator>, but
it can also validate data directly with sane defaults.

=head1 ATTRIBUTES

=head2 enum

  my $joi       = $joi->enum(["foo", "bar"]);
  my $array_ref = $joi->enum;

Defines a list of enum values for L</integer>, L</number> and L</string>.

=head2 format

  my $joi = $joi->format("email");
  my $str = $joi->format;

Used to set the format of the L</string>.
See also L</iso_date>, L</email> and L</uri>.

=head2 max

  my $joi = $joi->max(10);
  my $int = $joi->max;

=over 2

=item * array

Defines the max number of items in the array.

=item * integer, number

Defined the max value.

=item * object

Defines the max number of items in the object.

=item * string

Defines how long the string can be.

=back

=head2 min

  my $joi = $joi->min(10);
  my $int = $joi->min;

=over 2

=item * array

Defines the minimum number of items in the array.

=item * integer, number

Defined the minimum value.

=item * object

Defines the minimum number of items in the object.

=item * string

Defines how short the string can be.

=back

=head2 multiple_of

  my $joi = $joi->multiple_of(3);
  my $int = $joi->multiple_of;

Used by L</integer> and L</number> to define what the number must be a multiple
of.

=head2 regex

  my $joi = $joi->regex("^\w+$");
  my $str = $joi->regex;

Defines a pattern that L</string> will be validated against.

=head2 type

  my $joi = $joi->type("string");
  my $joi = $joi->type([qw(null integer)]);
  my $any = $joi->type;

Sets the required type. This attribute is set by the convenience methods
L</array>, L</integer>, L</object> and L</string>, but can be set manually if
you need to check against a list of type.

=head2 validator

  my $joi = $joi->validator(JSON::Validator::Schema::Draft7->new);
  my $jv  = $joi->validator;

Defaults to a L<JSON::Validator> object. This object is used by L</validate>.

Note: This might change to L<JSON::Validator::Schema::Draft7> or a later
schema in the future.

=head1 METHODS

=head2 TO_JSON

Alias for L</compile>.

=head2 alphanum

  my $joi = $joi->alphanum;

Sets L</regex> to "^\w*$".

=head2 array

  my $joi = $joi->array;

Sets L</type> to "array".

=head2 boolean

  my $joi = $joi->boolean;

Sets L</type> to "boolean".

=head2 compile

  my $hash_ref = $joi->compile;

Will convert this object into a JSON-Schema data structure that
L<JSON::Validator/schema> understands.

=head2 date_time

  my $joi = $joi->date_time;

Sets L</format> to L<date-time|JSON::Validator/date-time>.

=head2 email

  my $joi = $joi->email;

Sets L</format> to L<email|JSON::Validator/email>.

=head2 extend

  my $new_joi = $joi->extend($other_joi_object);

Will extend C<$joi> with the definitions in C<$other_joi_object> and return a
new object.

=head2 iso_date

Alias for L</date_time>.

=head2 integer

  my $joi = $joi->integer;

Sets L</type> to "integer".

=head2 items

  my $joi = $joi->items($joi);
  my $joi = $joi->items([$joi, ...]);

Defines a list of items for the L</array> type.

=head2 length

  my $joi = $joi->length(10);

Sets both L</min> and L</max> to the number provided.

=head2 lowercase

  my $joi = $joi->lowercase;

Will set L</regex> to only match lower case strings.

=head2 negative

  my $joi = $joi->negative;

Sets L</max> to C<0>.

=head2 number

  my $joi = $joi->number;

Sets L</type> to "number".

=head2 object

  my $joi = $joi->object;

Sets L</type> to "object".

=head2 pattern

Alias for L</regex>.

=head2 positive

  my $joi = $joi->positive;

Sets L</min> to C<0>.

=head2 props

  my $joi = $joi->props(name => JSON::Validator::Joi->new->string, ...);

Used to define properties for an L</object> type. Each key is the name of the
parameter and the values must be a L<JSON::Validator::Joi> object.

=head2 required

  my $joi = $joi->required;

Marks the current property as required.

=head2 strict

  my $joi = $joi->strict;

Sets L</array> and L</object> to not allow any more items/keys than what is defined.

=head2 string

  my $joi = $joi->string;

Sets L</type> to "string".

=head2 token

  my $joi = $joi->token;

Sets L</regex> to C<^[a-zA-Z0-9_]+$>.

=head2 validate

  my @errors = $joi->validate($data);

Used to validate C<$data> using L<JSON::Validator/validate>. Returns a list of
L<JSON::Validator::Error|JSON::Validator/ERROR OBJECT> objects on invalid
input.

=head2 unique

  my $joi = $joi->unique;

Used to force the L</array> to only contain unique items.

=head2 uppercase

  my $joi = $joi->uppercase;

Will set L</regex> to only match upper case strings.

=head2 uri

  my $joi = $joi->uri;

Sets L</format> to L<uri|JSON::Validator/uri>.

=head1 SEE ALSO

L<JSON::Validator>

L<https://github.com/hapijs/joi>.

=cut