lib/Schema/Validator.pm

filter: Statementstmt 84.7% 72 / 85 Branchbran 61.7% 21 / 34 Conditioncond 55.5% 5 / 9 MC/DCmcdc 33.3% 2 / 6 Subroutinesub 100% 8 / 8 Podpod 100% 2 / 2 totaltotal 76.3% 110 / 144 CC 22 SCAR 32.6
CC
22
Cov
77%
load_dynamic_vocabulary
34.0
BEGIN
1.0
BEGIN
1.0
CRAP 26.0
« blib/lib/Schema/Validator.pm ↑ Summary
1 package Schema::Validator;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use JSON::MaybeXS qw(decode_json encode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Encode qw(decode);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 1 ▶use base 'Exporter'; # Use Exporter as the base class
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 our @EXPORT_OK = qw(is_valid_datetime load_dynamic_vocabulary);
12  
13 1 our $VERSION = '0.02';
14  
15 1 our %dynamic_properties; # Global variable to store property definitions
16 1 our %dynamic_schema; # Global variable to store class definitions
17  
18 =head1 NAME
19  
20 Schema::Validator - Tools for validating and loading Schema.org vocabulary definitions
21  
22 =head1 VERSION
23  
24 Version 0.02
25  
26 =head1 SYNOPSIS
27  
28 =head2 FROM THE COMMAND LINE
29  
30 bin/validate-schema --file index.html
31  
32 =head2 FROM PERL
33  
34 use Schema::Validator qw(is_valid_datetime load_dynamic_vocabulary);
35  
36 # Validate datetime strings
37 if (is_valid_datetime('2024-11-14')) {
38 print "Valid date\n";
39 }
40  
41 if (is_valid_datetime('2024-11-14T15:30:00')) {
42 print "Valid datetime\n";
43 }
44  
45 # Load Schema.org vocabulary
46 my %schema = load_dynamic_vocabulary();
47  
48 # Access loaded schema definitions
49 print 'Classes: ', scalar(keys %Schema::Validator::dynamic_schema), "\n";
50 print 'Properties: ', scalar(keys %Schema::Validator::dynamic_properties), "\n";
51  
52 =head1 DESCRIPTION
53  
54 Schema::Validator provides utilities for working with Schema.org structured data vocabularies.
55 It includes functions for validating datetime formats and dynamically loading Schema.org class
56 and property definitions from the official Schema.org JSON-LD vocabulary file.
57  
58 =head2 Command Line Schema.org Validator
59  
60 This repository contains a Schema.org validator that scans HTML files for embedded JSON-LD (`application/ld+json` blocks) and validates them against a local schema definition.
61 It can optionally output diagnostics in SARIF format for GitHub Code Scanning integration.
62  
63 The Validator is a versatile tool designed to help you validate structured data embedded in your HTML files.
64 At its core, the script parses HTML to extract
65  
66 <script type="application/ld+json">
67  
68 blocks and validates the included JSON-LD against a set of built-in schema rules-verifying properties such as required fields,
69 proper date formats (e.g., for startdate), enumerated values, and cross-field consistency
70 (like ensuring a MusicEvent's performer is either a Person or a PerformingGroup).
71 For basic usage, simply run
72  
73 bin/validate-schema --file sample/sample.html
74  
75 to receive interactive console feedback about any missing or invalid properties.
76 The file can be a URL.
77  
78 =head3 Integration with GitHub Actions
79  
80 To integrate with GitHub Code Scanning and CI/CD pipelines, you can activate SARIF output by adding the C<--github> flag,
81 which aggregates diagnostics into a schema_validation.sarif file.
82  
83 =head3 Dynamic Mode
84  
85 If you want your validations to be driven by the most current standards, the C<--dynamic> flag instructs the tool to download and cache the latest Schema.org vocabulary (currently loading over 900 classes) so that dynamic validations can be performed against live schema definitions.
86 may combine these flags as needed-using C<--file> with either or both of C<--github> and C<--dynamic> to tailor the tool for local testing,
87 automated code analysis,
88 or an in-depth schema audit.
89 The module caches the downloaded vocabulary to minimize network requests and improve performance.
90  
91 =head1 PACKAGE VARIABLES
92  
93 =head2 %dynamic_schema
94  
95 %Schema::Validator::dynamic_schema
96  
97 Global hash containing Schema.org class definitions, keyed by class label (e.g., 'Person',
98 'Organization', 'Event'). Each value is a complete class definition from the Schema.org
99 vocabulary.
100  
101 This variable is populated by calling C<load_dynamic_vocabulary()>.
102  
103 =head2 %dynamic_properties
104  
105 %Schema::Validator::dynamic_properties
106  
107 Global hash containing Schema.org property definitions, keyed by property label (e.g., 'name',
108 'email', 'address'). Each value is a complete property definition from the Schema.org vocabulary.
109  
110 This variable is populated by calling C<load_dynamic_vocabulary()>.
111  
112 =head1 DEPENDENCIES
113  
114 This module requires the following Perl modules:
115  
116 =over 4
117  
118 =item * L<JSON::MaybeXS> - JSON encoding/decoding
119  
120 =item * L<LWP::UserAgent> - HTTP client for downloading vocabulary
121  
122 =item * L<Encode> - Character encoding utilities
123  
124 =back
125  
126 =head1 FILES
127  
128 =head2 schemaorg_dynamic_vocabulary.jsonld
129  
130 Cache file created in the current working directory. Contains the downloaded Schema.org
131 vocabulary in JSON-LD format. Automatically refreshed when older than 24 hours.
132  
133 =head1 ERROR HANDLING
134  
135 The module uses warnings rather than fatal errors for most failure conditions:
136  
137 =over 4
138  
139 =item * Failed HTTP requests emit a warning and return empty results
140  
141 =item * JSON parse errors emit a warning and return empty results
142  
143 =item * File I/O errors emit warnings but attempt to continue operation
144  
145 =back
146  
147 This allows the calling code to continue execution even if vocabulary loading fails.
148  
149 =head1 EXAMPLES
150  
151 =head2 Basic Usage
152  
153 use Schema::Validator qw(is_valid_datetime load_dynamic_vocabulary);
154  
155 # Validate user input
156 my $date_input = '2024-11-14';
157 unless (is_valid_datetime($date_input)) {
158 die "Invalid date format\n";
159 }
160  
161 # Load Schema.org vocabulary
162 load_dynamic_vocabulary();
163  
164 # Check if a specific class exists
165 if (exists $Schema::Validator::dynamic_schema{'Product'}) {
166 print "Product class is defined in Schema.org\n";
167 }
168  
169 =head2 Working with Loaded Vocabulary
170  
171 use Schema::Validator qw(load_dynamic_vocabulary);
172 use Data::Dumper;
173  
174 # Load vocabulary
175 my %classes = load_dynamic_vocabulary();
176  
177 # Examine a specific class
178 if (my $person = $Schema::Validator::dynamic_schema{'Person'}) {
179 print "Person class definition:\n";
180 print Dumper($person);
181 }
182  
183 # List all available properties
184 my @props = keys %Schema::Validator::dynamic_properties;
185 print "Available properties: ", join(', ', sort @props), "\n";
186  
187 =head2 is_valid_datetime
188  
189 my $is_valid = is_valid_datetime($string);
190  
191 Validates whether a string matches valid datetime formats.
192  
193 B<Parameters:>
194  
195 =over 4
196  
197 =item * C<$string> - The string to validate
198  
199 =back
200  
201 B<Returns:> Boolean (1 for valid, 0 for invalid)
202  
203 B<Accepted formats:>
204  
205 =over 4
206  
207 =item * C<YYYY-MM-DD> - Date only (e.g., "2024-11-14")
208  
209 =item * C<YYYY-MM-DDTHH:MM> - Date with time (e.g., "2024-11-14T15:30")
210  
211 =item * C<YYYY-MM-DD HH:MM> - Date with time, space separator (e.g., "2024-11-14 15:30")
212  
213 =item * C<YYYY-MM-DDTHH:MM:SS> - Date with time including seconds (e.g., "2024-11-14T15:30:45")
214  
215 =item * C<YYYY-MM-DD HH:MM:SS> - Date with time including seconds, space separator
216  
217 =back
218  
219 B<Example:>
220  
221 if (is_valid_datetime('2024-11-14T15:30:00')) {
222 print "Valid ISO 8601 datetime\n";
223 }
224  
225 =cut
226  
227 # Validates that a string is in YYYY-MM-DD or YYYY-MM-DDTHH:MM(:SS)? format.
228 sub is_valid_datetime {
229 3 ▶ my $val = shift;
Subroutine is_valid_datetime: called CC=1 SCAR=0.0
Pod documented
230 3 return $val =~ /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?)?$/;
231 }
232  
233 =head2 load_dynamic_vocabulary
234  
235 my %classes = load_dynamic_vocabulary();
236  
237 Downloads and parses the Schema.org vocabulary from the official source, extracting class
238 and property definitions. The vocabulary is cached locally for 24 hours to reduce network
239 overhead.
240  
241 B<Parameters:> None
242  
243 B<Returns:> Hash mapping class labels to their complete Schema.org definitions
244  
245 B<Side effects:>
246  
247 =over 4
248  
249 =item * Populates C<%Schema::Validator::dynamic_schema> with class definitions
250  
251 =item * Populates C<%Schema::Validator::dynamic_properties> with property definitions
252  
253 =item * Creates/updates cache file C<schemaorg_dynamic_vocabulary.jsonld> in the current directory
254  
255 =item * Emits warnings on download, parse, or file I/O errors
256  
257 =back
258  
259 B<Cache behavior:>
260  
261 The function maintains a local cache file (C<schemaorg_dynamic_vocabulary.jsonld>) that
262 expires after 24 hours. If the cache is valid, the vocabulary is loaded from the cache
263 rather than downloading from Schema.org.
264  
265 B<Example:>
266  
267 my %schema_classes = load_dynamic_vocabulary();
268  
269 # Access specific class definition
270 if (exists $Schema::Validator::dynamic_schema{'Person'}) {
271 my $person_def = $Schema::Validator::dynamic_schema{'Person'};
272 print "Person class loaded\n";
273 }
274  
275 # Access property definitions
276 if (exists $Schema::Validator::dynamic_properties{'name'}) {
277 my $name_prop = $Schema::Validator::dynamic_properties{'name'};
278 print "Name property loaded\n";
279 }
280  
281 =cut
282  
283 # Loads the dynamic Schema.org vocabulary from Schema.org and returns a hash mapping class labels to their definitions.
284 sub load_dynamic_vocabulary {
285 1 ▶ my $cache_file = 'schemaorg_dynamic_vocabulary.jsonld';
Subroutine load_dynamic_vocabulary: called CC=22 SCAR=35.3
Pod documented
286 1 my $cache_duration = 86400; # Cache expires in 1 day (86400 seconds)
287 1 my $content;
288 1 my $use_cache = 0;
289  
290 1 ▶ if (-e $cache_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-e $cache_file) 0 1 1
291 0 my $mtime = (stat($cache_file))[9];
292 0 ▶ if ( time - $mtime < $cache_duration ) {
Branch: 1 branch
BranchTrueFalseTotal
if (time - $mtime < $cache_duration) 0 0 0
293 0 $use_cache = 1;
294 }
295 }
296  
297 1 ▶ if ($use_cache) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_cache) { } 0 1 1
298 # Read from the cache file
299 0 ▶ open my $cfh, '<', $cache_file or warn "Could not open cache file $cache_file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $cfh, "<", $cache_file or warn "Could not open cache file ${cache_file}: $!" 0 0 0
300 {
301 0 local $/; # Slurp mode
302 0 $content = <$cfh>;
303 }
304 0 close $cfh;
305 } else {
306 # Download the vocabulary from Schema.org
307 1 my $url = 'https://schema.org/version/latest/schemaorg-current-https.jsonld';
308 1 my $ua = LWP::UserAgent->new( timeout => 30 );
309 1 my $res = $ua->get($url);
310 1 ▶ unless ($res->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 0 1 1
311 0 warn "Failed to fetch dynamic vocabulary from $url: " . $res->status_line;
312 0 return ();
313 }
314 1 $content = $res->decoded_content;
315 # Write the downloaded content to the cache file.
316 1 ▶ open my $cfh, '>', $cache_file or warn "Could not write to cache file $cache_file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $cfh, ">", $cache_file or warn "Could not write to cache file ${cache_file}: $!" 0 1 1
317 1 print $cfh $content;
318 1 close $cfh;
319 }
320  
321 1 my $data = eval { decode_json($content) };
322 1 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 1 1
323 0 warn "Failed to parse dynamic vocabulary JSON: $@";
324 0 return ();
325 }
326  
327 1 my %class_vocab;
328 my %prop_vocab;
329  
330 1 ▶ if (exists $data->{'@graph'} && ref($data->{'@graph'}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $data->{'@graph'} and ref $data->{'@graph'} eq 'ARRAY') { } 1 0 1
Condition33%1/3
exists $data->{"\@graph"} and ref $data->{"\@graph"} eq "ARRAY"
!ll&&!rl&&r
001
MC/DC0%0/2
exists $data->{"\@graph"} and ref $data->{"\@graph"} eq "ARRAY"
exists $data->{"\@graph"} ref $data->{"\@graph"} eq "ARRAY"
Truth table33%1/3
A and B
A= exists $data->{"\@graph"}B= ref $data->{"\@graph"} eq "ARRAY"
ABresult
0X0
100
111
331 1 for my $item (@{ $data->{'@graph'} }) {
332 3219 ▶ next unless exists $item->{'@type'};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $item->{"\@type"} 0 3219 3219
333 3219 my $item_type = $item->{'@type'};
334  
335 # Check for class definitions
336 3219 my $is_class = 0;
337 3219 ▶ if (ref($item_type) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item_type eq 'ARRAY') { } 8 3211 3219
338 8 $is_class = grep { $_ eq 'rdfs:Class' } @$item_type;
339 } else {
340 3211 $is_class = ($item_type eq 'rdfs:Class');
341 }
342 3219 ▶ if ($is_class) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_class) 1010 2209 3219
343 1010 ▶ my $label = $item->{'rdfs:label'} // $item->{'http://www.w3.org/2000/01/rdf-schema#label'};
Condition66%2/3
$item->{"rdfs:label"} // $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
l!l&&r!l&&!r
933077
MC/DC50%1/2
$item->{"rdfs:label"} // $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
$item->{"rdfs:label"} $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
Truth table66%2/3
A // B
A= $item->{"rdfs:label"}B= $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
ABresult
1X1
011
000
344 1010 ▶ next unless $label;
Branch: 1 branch
BranchTrueFalseTotal
unless $label 77 933 1010
345 933 ▶ $label = (ref($label) eq 'ARRAY') ? $label->[0] : $label;
Branch: 1 branch
BranchTrueFalseTotal
ref $label eq 'ARRAY' ? : 0 933 933
346 933 $class_vocab{$label} = $item;
347 }
348  
349 # Check for property definitions (e.g. items with @type 'rdf:Property')
350 3142 my $is_prop = 0;
351 3142 ▶ if (ref($item_type) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item_type eq 'ARRAY') { } 8 3134 3142
352 8 $is_prop = grep { $_ eq 'rdf:Property' } @$item_type;
353 } else {
354 3134 $is_prop = ($item_type eq 'rdf:Property');
355 }
356 3142 ▶ if ($is_prop) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_prop) 1676 1466 3142
357 1676 ▶ my $label = $item->{'rdfs:label'} // $item->{'http://www.w3.org/2000/01/rdf-schema#label'};
Condition66%2/3
$item->{"rdfs:label"} // $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
l!l&&r!l&&!r
15210155
MC/DC50%1/2
$item->{"rdfs:label"} // $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
$item->{"rdfs:label"} $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
Truth table66%2/3
A // B
A= $item->{"rdfs:label"}B= $item->{"http://www.w3.org/2000/01/rdf-schema#label"}
ABresult
1X1
011
000
358 1676 ▶ next unless $label;
Branch: 1 branch
BranchTrueFalseTotal
unless $label 155 1521 1676
359 1521 ▶ $label = (ref($label) eq 'ARRAY') ? $label->[0] : $label;
Branch: 1 branch
BranchTrueFalseTotal
ref $label eq 'ARRAY' ? : 0 1521 1521
360 1521 $prop_vocab{$label} = $item;
361 }
362 }
363 } else {
364 0 warn "No '\@graph' key found in the vocabulary JSON.";
365 }
366  
367 # Assign the populated hashes to the global variables.
368 1 %dynamic_schema = %class_vocab;
369 1 %dynamic_properties = %prop_vocab;
370  
371 1 warn 'Dynamic vocabulary loaded: ', scalar(keys %dynamic_schema),
372 ' classes and ', scalar(keys %dynamic_properties), ' properties found.';
373  
374 1 return %dynamic_schema;
375 }
376  
377 =head1 AUTHOR
378  
379 Nigel Horne, C<< <njh at nigelhorne.com> >>
380  
381 =head1 BUGS
382  
383 =over 4
384  
385 =item * Cache file is stored in the current working directory, which may cause issues with
386 file permissions or multiple concurrent processes
387  
388 =item * No timezone support in datetime validation
389  
390 =item * Cache invalidation is time-based only; no checksums or version checking
391  
392 =item * Network failures during vocabulary download return empty results rather than using
393 stale cache
394  
395 =back
396  
397 =head1 SEE ALSO
398  
399 =over 4
400  
401 =item * L<https://schema.org/> - Schema.org structured data vocabulary
402  
403 =item * L<JSON::MaybeXS> - JSON encoding/decoding
404  
405 =item * L<LWP::UserAgent> - HTTP client library
406  
407 =back
408  
409 =head1 REPOSITORY
410  
411 L<https://github.com/nigelhorne/schema-validator>
412  
413 =head1 SUPPORT
414  
415 This module is provided as-is without any warranty.
416  
417 =head1 LICENCE AND COPYRIGHT
418  
419 Copyright 2025 Nigel Horne.
420  
421 Usage is subject to licence terms.
422  
423 The licence terms of this software are as follows:
424  
425 =over 4
426  
427 =item * Personal single user, single computer use: GPL2
428  
429 =item * All other users (including Commercial, Charity, Educational, Government)
430 must apply in writing for a licence for use from Nigel Horne at the
431 above e-mail.
432  
433 =back
434  
435 =cut
436  
437 1 1;
« blib/lib/Schema/Validator.pm ↑ Summary