blib/lib/Schema/Validator.pm untested

filter: Statementstmt 0.0% 0 / 85 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 13 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 138 CC 16 SCAR 52.5
CC
16
Cov
0%
load_dynamic_vocabulary
272.0
is_valid_datetime
2.0
BEGIN
2.0
CRAP 189.8
1 package Schema::Validator;
2  
3 use strict;
4 use warnings;
5  
6 use JSON::MaybeXS qw(decode_json encode_json);
7 use LWP::UserAgent;
8 use Encode qw(decode);
9  
10 use base 'Exporter'; # Use Exporter as the base class
11 our @EXPORT_OK = qw(is_valid_datetime load_dynamic_vocabulary);
12  
13 our $VERSION = '0.02';
14  
15 our %dynamic_properties; # Global variable to store property definitions
16 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 my $val = shift;
230 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 my $cache_file = 'schemaorg_dynamic_vocabulary.jsonld';
286 my $cache_duration = 86400; # Cache expires in 1 day (86400 seconds)
287 my $content;
288 my $use_cache = 0;
289  
290 if (-e $cache_file) {
291 my $mtime = (stat($cache_file))[9];
292 if ( time - $mtime < $cache_duration ) {
293 $use_cache = 1;
294 }
295 }
296  
297 if ($use_cache) {
298 # Read from the cache file
299 open my $cfh, '<', $cache_file or warn "Could not open cache file $cache_file: $!";
300 {
301 local $/; # Slurp mode
302 $content = <$cfh>;
303 }
304 close $cfh;
305 } else {
306 # Download the vocabulary from Schema.org
307 my $url = 'https://schema.org/version/latest/schemaorg-current-https.jsonld';
308 my $ua = LWP::UserAgent->new( timeout => 30 );
309 my $res = $ua->get($url);
310 unless ($res->is_success) {
311 warn "Failed to fetch dynamic vocabulary from $url: " . $res->status_line;
312 return ();
313 }
314 $content = $res->decoded_content;
315 # Write the downloaded content to the cache file.
316 open my $cfh, '>', $cache_file or warn "Could not write to cache file $cache_file: $!";
317 print $cfh $content;
318 close $cfh;
319 }
320  
321 my $data = eval { decode_json($content) };
322 if ($@) {
323 warn "Failed to parse dynamic vocabulary JSON: $@";
324 return ();
325 }
326  
327 my %class_vocab;
328 my %prop_vocab;
329  
330 if (exists $data->{'@graph'} && ref($data->{'@graph'}) eq 'ARRAY') {
331 for my $item (@{ $data->{'@graph'} }) {
332 next unless exists $item->{'@type'};
333 my $item_type = $item->{'@type'};
334  
335 # Check for class definitions
336 my $is_class = 0;
337 if (ref($item_type) eq 'ARRAY') {
338 $is_class = grep { $_ eq 'rdfs:Class' } @$item_type;
339 } else {
340 $is_class = ($item_type eq 'rdfs:Class');
341 }
342 if ($is_class) {
343 my $label = $item->{'rdfs:label'} // $item->{'http://www.w3.org/2000/01/rdf-schema#label'};
344 next unless $label;
345 $label = (ref($label) eq 'ARRAY') ? $label->[0] : $label;
346 $class_vocab{$label} = $item;
347 }
348  
349 # Check for property definitions (e.g. items with @type 'rdf:Property')
350 my $is_prop = 0;
351 if (ref($item_type) eq 'ARRAY') {
352 $is_prop = grep { $_ eq 'rdf:Property' } @$item_type;
353 } else {
354 $is_prop = ($item_type eq 'rdf:Property');
355 }
356 if ($is_prop) {
357 my $label = $item->{'rdfs:label'} // $item->{'http://www.w3.org/2000/01/rdf-schema#label'};
358 next unless $label;
359 $label = (ref($label) eq 'ARRAY') ? $label->[0] : $label;
360 $prop_vocab{$label} = $item;
361 }
362 }
363 } else {
364 warn "No '\@graph' key found in the vocabulary JSON.";
365 }
366  
367 # Assign the populated hashes to the global variables.
368 %dynamic_schema = %class_vocab;
369 %dynamic_properties = %prop_vocab;
370  
371 warn 'Dynamic vocabulary loaded: ', scalar(keys %dynamic_schema),
372 ' classes and ', scalar(keys %dynamic_properties), ' properties found.';
373  
374 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;