Source

p5-json-schema / lib / JSON / Schema / Helper.pm

Full commit
  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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package JSON::Schema::Helper;

### 
# JSONSchema Validator - Validates JavaScript objects using JSON Schemas 
#	(http://www.json.com/json-schema-proposal/)
#
# Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
# Licensed under the MIT (MIT-LICENSE.txt) license.
#To use the validator call JSONSchema.validate with an instance object and an optional schema object.
#If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), 
#that schema will be used to validate and the schema parameter is not necessary (if both exist, 
#both validations will occur). 
#The validate method will return an array of validation errors. If there are no errors, then an 
#empty list will be returned. A validation error will have two properties: 
#"property" which indicates which property had the error
#"message" which indicates what the error was
##

use 5.008;
use common::sense;
use constant FALSE => 0;
use constant TRUE  => 1;

use JSON::Hyper;
use JSON::Schema::Null;
use POSIX qw[modf];
use Scalar::Util qw[blessed];

our $VERSION = '0.001_01';

sub new
{
	my ($class, %args) = @_;
	$args{'hyper'}  ||= JSON::Hyper->new;
	$args{'errors'} ||= [];
	return bless \%args, $class;
}

sub validate
{
	my ($self, $instance, $schema) = @_;
	## Summary:
	##  	To use the validator call JSONSchema.validate with an instance object and an optional schema object.
	## 		If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), 
	## 		that schema will be used to validate and the schema parameter is not necessary (if both exist, 
	## 		both validations will occur). 
	## 		The validate method will return an object with two properties:
	## 			valid: A boolean indicating if the instance is valid by the schema
	## 			errors: An array of validation errors. If there are no errors, then an 
	## 					empty list will be returned. A validation error will have two properties: 
	## 						property: which indicates which property had the error
	## 						message: which indicates what the error was
	##
	return $self->_validate($instance, $schema, FALSE);
}

sub checkPropertyChange
{
	my ($self, $value, $schema, $property) = @_;
	## Summary:
	## 		The checkPropertyChange method will check to see if an value can legally be in property with the given schema
	## 		This is slightly different than the validate method in that it will fail if the schema is readonly and it will
	## 		not check for self-validation, it is assumed that the passed in value is already internally valid.  
	## 		The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for 
	## 		information.
	##
	return $self->_validate($value, $schema, $property||'property');	
}

sub _validate
{
	my ($self, $instance, $schema, $_changing) = @_;
	
	$self->{errors} = [];
	
	if ($schema)
	{
		$self->checkProp($instance, $schema, '', $_changing || '', $_changing);
	}
	if(!$_changing and defined $instance and ref $instance eq 'HASH' and defined $instance->{'$schema'})
	{
		$self->checkProp($instance, $instance->{'$schema'}, '', '', $_changing);
	}
	
	return { valid=>(@{$self->{errors}} ? FALSE : TRUE), errors=> $self->{errors} };
}

sub checkType
{
	my ($self, $type, $value, $path, $_changing, $schema) = @_;
	
	my @E;
	my $addError = sub
	{
		my ($message) = @_;
		my $e = { property=>$path, message=>$message };
		foreach (qw(title description))
		{
			$e->{$_} = $schema->{$_}
				if defined $schema->{$_};
		}
		push @E, $e;
	};
	
	if ($type)
	{
#		if (ref $type ne 'HASH'
#		and $type ne 'any'
#		and ($type eq 'null' ? $self->jsIsNull($value) : $self->jsMatchType($type, $value))
#		and !(ref $value eq 'ARRAY' and $type eq 'array')
#		and !($type eq 'integer' and $value % 1 == 0))
		if (!$self->jsMatchType($type, $value))
		{
			$addError->($self->jsGuessType($value)." value found, but a $type is required");
			return @E;
		}
		if (ref $type eq 'ARRAY')
		{
			my @unionErrors;
			TYPE: foreach my $t (@$type)
			{
				@unionErrors = @{ $self->checkType($t, $value, $path, $_changing, $schema) };
				last unless @unionErrors;
			}
			return @unionErrors if @unionErrors;
		}
		elsif (ref $type eq 'HASH')
		{
			local $self->{errors} = [];
			$self->checkProp($value, $type, $path, undef, $_changing);
			return @{ $self->{errors} };
		}
	}
	return;
}

# validate a value against a property definition
sub checkProp
{
	my ($self, $value, $schema, $path, $i, $_changing) = @_;
	my $l;
	$path .= $path ? ".${i}" : "\$${i}";
	
	my $addError = sub
	{
		my ($message) = @_;
		my $e = { property=>$path, message=>$message };
		foreach (qw(title description))
		{
			$e->{$_} = $schema->{$_}
				if defined $schema->{$_};
		}
		push @{$self->{errors}}, $e;
	};
	
	if (ref $schema ne 'HASH' and ($path or ref $schema ne 'CODE'))
	{
		if (ref $schema eq 'CODE')
		{
			# ~TOBYINK: I don't think this makes any sense in Perl
			$addError->("is not an instance of the class/constructor " . $schema);
		}
		elsif ($schema)
		{
			$addError->("Invalid schema/property definition " . $schema);
		}
		return undef;
	}
	
	$self->{'hyper'}->process_includes($schema, $self->{'base'});
	
	if ($_changing and $schema->{'readonly'})
	{
		$addError->("is a readonly field, it can not be changed");
	}
	if ($schema->{'extends'})
	{
		$self->checkProp($value, $schema->{'extends'}, $path, $i, $_changing);
	}
	
	# validate a value against a type definition
	if (!defined $value)
	{
		$addError->("is missing and it is not optional")
			unless $schema->{'optional'};
	}
	else
	{
		push @{$self->{errors}}, $self->checkType($schema->{'type'}, $value, $path, $_changing, $schema);
		if (defined $schema->{'disallow'}
		and !$self->checkType($schema->{'disallow'}, $value, $path, $_changing))
		{
			$addError->(" disallowed value was matched");
		}
		if (!$self->jsIsNull($value))
		{
			if (ref $value eq 'ARRAY')
			{
				my $items = $schema->{items};
				if (ref $items eq 'ARRAY')
				{ # check each item in $schema->{items} vs corresponding array value
					for (my $i=0; $i < @$items; $i++)
					{
						my $x = defined $value->[$i] ? $value->[$i] : JSON::Schema::Null->new; 
						push @{$self->{errors}}, $self->checkProp($x, $items->[$i], $path, $i, $_changing);
					}
				}
				elsif (ref $items eq 'HASH')
				{ # check single $schema->{items} hash vs all values in array
					for (my $i=0; $i < @$value; $i++)
					{
						my $x = defined $value->[$i] ? $value->[$i] : JSON::Schema::Null->new; 
						push @{$self->{errors}}, $self->checkProp($x, $items, $path, $i, $_changing);
					}
				}
				if ($schema->{'minItems'}
				and scalar @$value < $schema->{'minItems'})
				{
					addError->("There must be a minimum of " . $schema->{'minItems'} . " in the array");
				}
				if ($schema->{'maxItems'}
				and scalar @$value > $schema->{'maxItems'})
				{
					addError->("There must be a maximum of " . $schema->{'maxItems'} . " in the array");
				}
			}
			elsif ($schema->{'properties'})
			{
				push @{$self->{errors}}, $self->checkObj($value, $schema->{'properties'}, $path, $schema->{'additionalProperties'}, $_changing);
			}
			if ($schema->{'pattern'} and $self->jsMatchType('string', $value))
			{
				my $x = $schema->{'pattern'};
				$addError->("does not match the regex pattern $x")
					unless $value =~ /$x/;
			}
			if ($schema->{'maxLength'} and $self->jsMatchType('string', $value)
			and strlen($value) > $schema->{'maxLength'})
			{
				$addError->("may only be " . $schema->{'maxLength'} . " characters long");
			}
			if ($schema->{'minLength'} and $self->jsMatchType('string', $value)
			and strlen($value) < $schema->{'minLength'})
			{
				$addError->("must be at least " . $schema->{'minLength'} . " characters long");
			}
			if (defined $schema->{'minimum'} and not $self->jsMatchType('number', $value))
			{
				if (defined $schema->{'minimumCanEqual'} and not $schema->{'minimumCanEqual'})
				{
					$addError->("must be greater than minimum value '" . $schema->{'minimum'}) . "'"
						if $value lt $schema->{'minimum'};
				}
				else
				{
					$addError->("must be greater than or equal to minimum value '" . $schema->{'minimum'}) . "'"
						if $value le $schema->{'minimum'};
				}
			}
			elsif (defined $schema->{'minimum'})
			{
				if (defined $schema->{'minimumCanEqual'} and not $schema->{'minimumCanEqual'})
				{
					$addError->("must be greater than minimum value " . $schema->{'minimum'})
						unless $value > $schema->{'minimum'};
				}
				else
				{
					$addError->("must be greater than or equal to minimum value " . $schema->{'minimum'})
						unless $value >= $schema->{'minimum'};
				}
			}
			if (defined $schema->{'maximum'} and not $self->jsMatchType('number', $value))
			{
				if (defined $schema->{'maximumCanEqual'} and not $schema->{'maximumCanEqual'})
				{
					$addError->("must be less than or equal to maximum value '" . $schema->{'maximum'}) . "'"
						if $value gt $schema->{'maximum'};
				}
				else
				{
					$addError->("must be less than or equal to maximum value '" . $schema->{'maximum'}) . "'"
						if $value ge $schema->{'maximum'};
				}
			}
			elsif (defined $schema->{'maximum'})
			{
				if (defined $schema->{'maximumCanEqual'} and not $schema->{'maximumCanEqual'})
				{
					$addError->("must be less than maximum value " . $schema->{'maximum'})
						unless $value < $schema->{'maximum'};
				}
				else
				{
					$addError->("must be less than or equal to maximum value " . $schema->{'maximum'})
						unless $value <= $schema->{'maximum'};
				}
			}
			if ($schema->{'enum'})
			{
				$addError->("does not have a value in the enumeration {" . (join ",", @{ $schema->{'enum'} }) . '}')
					unless grep { $value eq $_ } @{ $schema->{'enum'} };
			}
			if ($schema->{'divisibleBy'} and $self->jsMatchType('number', $value))
			{
				my ($frac,$int) = modf($value / $schema->{'divisibleBy'});
				$addError->("must be divisible by " . $schema->{'divisibleBy'})
					if $frac;
			}
			elsif ($schema->{'maxDecimal'} and $self->jsMatchType('number', $value)) # ~TOBYINK: back-compat
			{
				my $regexp = "\\.[0-9]{" . ($schema->{'maxDecimal'} + 1) . ",}";
				$addError->("may only have " . $schema->{'maxDecimal'} . " digits of decimal places")
					if $value =~ /$regexp/;
			}
		} # END: if (!$self->jsIsNull()) { ... }
	} # END: if (!$defined $value) {} else {...}
	return;
}; # END: sub checkProp


sub checkObj
{
	my ($self, $instance, $objTypeDef, $path, $additionalProp, $_changing) = @_;
	my @errors;
	
	my $addError = sub
	{
		my ($message) = @_;
		my $e = { property=>$path, message=>$message };
		push @{$self->{errors}}, $e;
	};
	
	$self->{'hyper'}->process_includes($objTypeDef, $self->{'base'});
	
	if (ref $objTypeDef eq 'HASH')
	{
		if (ref $instance ne 'HASH')
		{
			$addError->("an object is required");
		}
		
		foreach my $i (keys %$objTypeDef)
		{
			unless ($i =~ /^__/)
			{
				my $value   = defined $instance->{$i} ? $instance->{$i} : exists $instance->{$i} ? JSON::Schema::Null->new : undef;
				my $propDef = $objTypeDef->{$i};
				$self->checkProp($value, $propDef, $path, $i, $_changing);
			}
		}
	} # END: if (ref $objTypeDef eq 'HASH')
	foreach my $i (keys %$instance)
	{
		if ($i !~ /^__/
		and defined $objTypeDef
		and not defined $objTypeDef->{$i}
		and not defined $additionalProp)
		{
			$addError->("The property $i is not defined in the schema and the schema does not allow additional properties");
		}
		my $requires = $objTypeDef && $objTypeDef->{$i} && $objTypeDef->{$i}->{'requires'};
		if (defined $requires and not defined $instance->{$requires})
		{
			$addError->("the presence of the property $i requires that $requires also be present");
		}
		my $value = defined $instance->{$i} ? $instance->{$i} : exists $instance->{$i} ? JSON::Schema::Null->new : undef;
		if (defined $objTypeDef
		and ref $objTypeDef eq 'HASH'
		and !defined $objTypeDef->{$i})
		{
			$self->checkProp($value, $additionalProp, $path, $i, $_changing); 
		}
		if(!$_changing and defined $value and ref $value eq 'HASH' and defined $value->{'$schema'})
		{
			push @errors, $self->checkProp($value, $value->{'$schema'}, $path, $i, $_changing);
		}
	}
	return @errors;
}

sub jsIsNull
{
	my ($self, $value) = @_;
	
	return TRUE if blessed($value) && $value->isa('JSON::Schema::Null');
	
	return FALSE;
}

sub jsMatchType
{
	my ($self, $type, $value) = @_;
	
	if (lc $type eq 'string')
	{
		return (ref $value) ? FALSE : TRUE;
	}

	if (lc $type eq 'number')
	{
		return ($value =~ /^\-?[0-9]*(\.[0-9]*)?$/ and length $value) ? TRUE : FALSE;
	}
	
	if (lc $type eq 'integer')
	{
		return ($value =~ /^\-?[0-9]+$/) ? TRUE : FALSE;
	}
	
	if (lc $type eq 'boolean')
	{
		return TRUE if (ref $value eq 'SCALAR' and $$value==0 || $$value==1);
		return TRUE if ($value eq TRUE);
		return TRUE if ($value eq FALSE);
		return TRUE if (ref $value eq 'JSON::PP::Boolean');
		return TRUE if (ref $value eq 'JSON::XS::Boolean');
		return FALSE;
	}

	if (lc $type eq 'object')
	{
		return (ref $value eq 'HASH') ? TRUE : FALSE;
	}
	
	if (lc $type eq 'array')
	{
		return (ref $value eq 'ARRAY') ? TRUE : FALSE;
	}

	if (lc $type eq 'null')
	{
		return $self->jsIsNull($value);
	}
	
	if (lc $type eq 'any')
	{
		return TRUE;
	}
	
	if (lc $type eq 'none')
	{
		return FALSE;
	}
	
	if (blessed($value) and $value->isa($type))
	{
		return TRUE;
	}
	elsif (ref($value) and ref($value) eq $type)
	{
		return TRUE;
	}
	
	return FALSE;
}

sub jsGuessType
{
	my ($self, $value) = @_;
	
	return 'object'
		if ref $value eq 'HASH';

	return 'array'
		if ref $value eq 'ARRAY';

	return 'boolean'
		if (ref $value eq 'SCALAR' and $$value==0 and $$value==1);
	
	return 'null'
		if $self->jsIsNull($value);
		
	return ref $value
		if ref $value;

	return 'integer'
		if $value =~ /^\-?[0-9]+$/;
	
	return 'number'
		if $value =~ /^\-?[0-9]*(\.[0-9]*)?$/;
	
	return 'string';
}

1;

__END__

=head1 NAME

JSON::Schema::Helper - helper class for JSON::Schema

=head1 SEE ALSO

L<JSON::Schema>.

=head1 AUTHOR

Toby Inkster E<lt>tobyink@cpan.orgE<gt>.

=head1 COPYRIGHT AND LICENCE

Copyright 2007-2009 Kris Zyp.

Copyright 2010-2011 Toby Inkster.

This module is tri-licensed. It is available under the X11 (a.k.a. MIT)
licence; you can also redistribute it and/or modify it under the same
terms as Perl itself.

=head2 a.k.a. "The MIT Licence"

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

=cut