File Coverage

File:blib/lib/Params/Validate/Strict.pm
Coverage:90.0%

linestmtbrancondsubtimecode
1package Params::Validate::Strict;
2
3
37
37
37
2340814
35
470
use strict;
4
37
37
37
61
22
596
use warnings;
5
6
37
37
37
64
28
256
use Carp ();
7
37
37
37
45
32
444
use Exporter qw(import);        # Required for @EXPORT_OK
8
37
37
37
7391
218548
1317
use Encode qw(decode_utf8);
9
37
37
37
89
346
994
use List::Util 1.33 qw(all any);        # Required for memberof/matches validation
10
37
37
37
5947
131564
1591
use Readonly::Values::Boolean;
11
37
37
37
100
33
1548
use Scalar::Util;
12
13our @ISA = qw(Exporter);
14our @EXPORT_OK = qw(validate_strict compile_schema);
15
16 - 24
=head1 NAME

Params::Validate::Strict - Validates a set of parameters against a schema

=head1 VERSION

Version 0.43

=cut
25
26our $VERSION = '0.43';
27
28# Recursion depth counter - localised on every entry so it unwinds automatically.
29# Protects against mutations (or bugs) that turn the pipe-normalisation guard into
30# an infinite loop through the union-type ARRAY handler.
31our $_depth = 0;
32
33# Type codes used by compiled schemas (see _compile_schema).  Numeric codes
34# keep the per-call dispatch to integer comparisons.
35use constant {
36
37
226594
        _T_STRING => 1,
37        _T_INT => 2,
38        _T_NUM => 3,
39        _T_BOOL => 4,
40        _T_ARRAY => 5,
41        _T_HASH => 6,
42        _T_SCALAR => 7,
43        _T_CODE => 8,
44        _T_OBJECT => 9,
45
37
37
72
32
};
46
47 - 1220
=head1 SYNOPSIS

    my $schema = {
        username => { type => 'string', min => 3, max => 50 },
        age => { type => 'integer', min => 0, max => 150 },
    };

    my $input = {
         username => 'john_doe',
         age => '30',        # Will be coerced to integer
    };

    my $validated_input = validate_strict(schema => $schema, input => $input);

    if(defined($validated_input)) {
        print "Example 1: Validation successful!\n";
        print 'Username: ', $validated_input->{username}, "\n";
        print 'Age: ', $validated_input->{age}, "\n";      # It's an integer now
    } else {
        print "Example 1: Validation failed: $@\n";
    }

Upon first reading this may seem overly complex and full of scope creep in a sledgehammer to crack a nut sort of way,
however two use cases make use of the extensive logic that comes with this code
and I have a couple of other reasons for writing it.

=over 4

=item * Black Box Testing

The schema can be plumbed into L<App::Test::Generator> to automatically create a set of black-box test cases.

=item * WAF

The schema can be plumbed into a WAF,
e.g., L<VWF|https://github.com/nigelhorne/VWF/>,
to protect from random user input.

=item * Improved API Documentation

Even if you don't use this module,
the specification syntax can help with documentation.

=item * I like it

I found it fun to write this,
even if nobody else finds it useful,
though I hope you will.

=back

=head1  METHODS

=head2 validate_strict

Validates a set of parameters against a schema.

This function takes two mandatory arguments:

=over 4

=item * C<schema> || C<members>

A reference to a hash that defines the validation rules for each parameter.
The keys of the hash are the parameter names, and the values are either a string representing the parameter type or a reference to a hash containing more detailed rules.

As an alternative the schema may be supplied as an B<arrayref of parameter hashrefs>,
where every element describes one parameter and carries a mandatory
C<name> key:

  $schema = [
    { name => 'username', type => 'string', min => 3, max => 50 },
    { name => 'age',      type => 'integer', min => 0, max => 150 },
    { name => 'role',     type => 'string', optional => 1, default => 'user' },
  ];

The arrayref form is normalised to the standard hashref form before any further
processing.  It is particularly useful when declaration order matters (e.g.
for positional or mixed calling conventions used by some CPAN modules).  The
C<name> key is consumed during normalisation and does not appear as a
validation rule.

For some sort of compatibility with L<Data::Processor>,
it is possible to wrap the schema within a hash like this:

  $schema = {
    description => 'Describe what this schema does',
    error_msg => 'An error message',
    schema => {
      # ... schema goes here
    }
  }

=item * C<args> || C<input>

A reference to a hash containing the parameters to be validated.
The keys of the hash are the parameter names, and the values are the parameter values.

=back

It takes optional arguments:

=over 4

=item * C<description>

What the schema does,
used in error messages.

=item * C<error_msg>

Overrides the default message when something doesn't validate.

=item * C<unknown_parameter_handler>

This parameter describes what to do when a parameter is given that is not in the schema of valid parameters.
It must be one of C<die>, C<warn>, or C<ignore>.

It defaults to C<die> unless C<carp_on_warn> is given, in which case it defaults to C<warn>.

=item * C<logger>

A logging object that understands messages such as C<error> and C<warn>.

=item * C<custom_types>

A reference to a hash that defines reusable custom types.
Custom types allow you to define validation rules once and reuse them throughout your schema,
making your validation logic more maintainable and readable.

Each custom type is defined as a hash reference containing the same validation rules available for regular parameters
(C<type>, C<min>, C<max>, C<matches>, C<memberof>, C<values>, C<enum>, C<notmemberof>, C<callback>, etc.).

  my $custom_types = {
    email => {
      type => 'string',
      matches => qr/^[^@\s]+\@[^@\s]+\.[^@\s]+$/,
      error_msg => 'Invalid email address format'
    }, phone => {
      type => 'string',
      matches => qr/^\+?[1-9]\d{1,14}$/,
      min => 10,
      max => 15
    }, percentage => {
      type => 'number',
      min => 0,
      max => 100
    }, status => {
      type => 'string',
      memberof => ['draft', 'published', 'archived']
    }
  };

  my $schema = {
    user_email => { type => 'email' },
    contact_number => { type => 'phone', optional => 1 },
    completion => { type => 'percentage' },
    post_status => { type => 'status' }
  };

  my $validated = validate_strict(
    schema => $schema,
    input => $input,
    custom_types => $custom_types
  );

Custom types can be extended or overridden in the schema by specifying additional constraints:

  my $schema = {
    admin_username => {
      type => 'username',  # Uses custom type definition
      min => 5,            # Overrides custom type's min value
      max => 15            # Overrides custom type's max value
    }
  };

Custom types work seamlessly with nested schema, optional parameters, and all other validation features.

=back

The schema can define the following rules for each parameter:

=over 4

=item * C<type>

The data type of the parameter.
Valid types are C<string>, C<integer>, C<number>, C<float>, C<boolean>, C<scalar>, C<scalarref>, C<stringref>, C<hashref>, C<arrayref>, C<object>, C<coderef>, C<regex>, C<handle>, C<arraylike>, C<hashlike>, C<codelike>, C<invocant> and C<void>.
C<scalar> accepts any plain scalar value (string, number, boolean, etc.) but rejects references (arrayrefs, hashrefs, coderefs, objects).
C<scalarref> accepts a reference to a scalar value (e.g. C<\$var>) but rejects plain scalars, arrayrefs, hashrefs, coderefs, and objects.
C<stringref> accepts a reference to a scalar that contains a plain string (e.g. C<\$str>) and rejects plain scalars, references-to-references, arrayrefs, hashrefs, coderefs, and objects.
C<void> asserts that the parameter value is C<undef> (the parameter represents a void return or absent output).
When C<void> is used the schema must contain exactly one parameter.
The C<min>/C<max> constraints apply to the B<length> (in characters) of the referenced string.
All other string rules (C<matches>, C<nomatch>, C<memberof>, etc.) operate on the dereferenced string value.
The validated return value is the dereferenced plain string.
C<regex> accepts a compiled regular expression (C<qr//> object); the value is returned unchanged.
C<handle> accepts a file handle: a glob reference with a defined C<fileno>, an C<IO::Handle> subclass instance, or any value for which C<fileno> returns a defined value.
C<arraylike> accepts an array reference or a blessed object that overloads C<@{}> array dereferencing.
C<hashlike> accepts a hash reference or a blessed object that overloads C<%{}> hash dereferencing.
C<codelike> accepts a code reference or a blessed object that overloads C<&{}> code dereferencing.
C<invocant> accepts either a blessed object instance or a plain string that is a syntactically valid Perl class name (e.g. C<'MyApp::Widget'>).

A type can be an arrayref when a parameter could have different types (e.g. a string or an object).

  $schema = {
    username => [
      { type => 'string', min => 3, max => 50 },       # Name
      { type => 'integer', 'min' => 1 },  # UID that isn't root
    ]
  };

As a shorthand, C<type> itself may be an arrayref of type name strings (a I<union type>),
or a pipe-separated string, when all other constraints are shared between the alternatives:

  $schema = {
    data => { type => ['string', 'arrayref'] },
    id   => { type => 'string|integer', optional => 1 },
  };

This is equivalent to the full array-of-rules form but more concise.
Whitespace around the C<|> is ignored, so C<'string | arrayref'> is the same as C<'string|arrayref'>.
Every other key in the rule hash (C<optional>, C<min>, C<max>, C<matches>, etc.)
is inherited by each candidate type and validated independently against it.
Type names are tried left-to-right; the first match wins and its coercion
(e.g. numeric types) is propagated back to the caller.
If the value fails all candidate types, validation croaks with a message
listing the union members.

=item * C<can>

The parameter must be an object, or with C<type =E<gt> 'invocant'> an object or a class name,
that understands the method C<can>.
C<can> can be a simple scalar string of a method name,
or an arrayref of a list of method names, all of which must be supported by the object.

   $schema = {
     gedcom => { type => object, can => 'get_individual' }
   }

=item * C<isa>

The parameter must be an object of type C<isa>.
Requires C<type =E<gt> 'object'>.

=item * C<does>

The parameter must be a blessed object that satisfies the role via C<-E<gt>DOES>.
Requires C<type =E<gt> 'object'>.

  handler => { type => 'object', does => 'My::Role::Printable' }

=item * C<classcan>

The parameter must be a string holding a syntactically valid Perl class name
whose class understands the given method (or every method in an arrayref).
The check is always a C<-E<gt>can> method call, so an overridden C<can> is respected.
The class must already be loaded.
Symmetric with C<classisa> and C<classdoes>.

  backend => { type => 'string', classcan => ['connect', 'disconnect'] }

=item * C<element_isa>

Requires C<type =E<gt> 'arrayref'>.
Every element must be a blessed object that passes C<-E<gt>isa('Base::Class')>.
An empty arrayref is accepted; add C<min =E<gt> 1> to require at least one element.
Unlike C<element_type =E<gt> 'object'>, this checks the inheritance chain, not just blessedness.

  handlers => { type => 'arrayref', min => 1, element_isa => 'My::Handler' }

=item * C<needs>

A parameter name, or an arrayref of names, that must also be given whenever this parameter is.
A shorthand for one C<dependency> relationship per name (see C<relationships>).

  user => { type => 'string', optional => 1, needs => ['password', 'realm'] }

=item * C<classisa>

The parameter must be a string holding a syntactically valid Perl class name
that passes C<-E<gt>isa('Base::Class')>.
The class must already be loaded (its C<@ISA> must be reachable).
Does not accept blessed object references; use C<isa> for those.

  backend => { type => 'string', classisa => 'My::Backend::Base' }

=item * C<subclass>

Like C<classisa>, but requires a I<strict> subclass: the value must not equal
the base class name itself.

  plugin => { type => 'string', subclass => 'My::Plugin::Base' }

=item * C<classdoes>

Like C<classisa>, but tests C<-E<gt>DOES> (role consumption) instead of C<-E<gt>isa>.

  consumer => { type => 'string', classdoes => 'My::Role::Loggable' }

=item * C<driver>

The parameter must be a valid class name that: (1) can be loaded via C<require>,
and (2) passes C<-E<gt>isa('Base::Class')>.
The module is actually loaded as a side effect of validation.

  store => { type => 'string', driver => 'Cache::Store' }

=item * C<memberof>

The parameter must be a member of the given arrayref.

  status => {
    type => 'string',
    memberof => ['draft', 'published', 'archived']
  }

  priority => {
    type => 'integer',
    memberof => [1, 2, 3, 4, 5]
  }

For string types, the comparison is case-sensitive by default. Use the C<case_sensitive>
flag to control this behavior:

  # Case-sensitive (default) - must be exact match
  code => {
    type => 'string',
    memberof => ['ABC', 'DEF', 'GHI']
    # 'abc' will fail
  }

  # Case-insensitive - any case accepted
  code => {
    type => 'string',
    memberof => ['ABC', 'DEF', 'GHI'],
    case_sensitive => 0
    # 'abc', 'Abc', 'ABC' all pass, original case preserved
  }

For numeric types (C<integer>, C<number>, C<float>), the comparison uses numeric
equality (C<==> operator):

  rating => {
    type => 'number',
    memberof => [0.5, 1.0, 1.5, 2.0]
  }

Note that C<memberof> cannot be combined with C<min> or C<max> constraints as they
serve conflicting purposes - C<memberof> defines an explicit whitelist while C<min>/C<max>
define ranges.

=item * C<enum>

Same as C<memberof>.

=item * C<values>

Same as C<memberof>.

=item * C<notmemberof>

The parameter must not be a member of the given arrayref (blacklist).
This is the inverse of C<memberof>.

  username => {
    type => 'string',
    notmemberof => ['admin', 'root', 'system', 'administrator']
  }

  port => {
    type => 'integer',
    notmemberof => [22, 23, 25, 80, 443]  # Reserved ports
  }

Like C<memberof>, string comparisons are case-sensitive by default but can be controlled
with the C<case_sensitive> flag:

  # Case-sensitive (default)
  username => {
    type => 'string',
    notmemberof => ['Admin', 'Root']
    # 'admin' would pass, 'Admin' would fail
  }

  # Case-insensitive
  username => {
    type => 'string',
    notmemberof => ['Admin', 'Root'],
    case_sensitive => 0
    # 'admin', 'ADMIN', 'Admin' all fail
  }

The blacklist is checked after any C<transform> rules are applied, allowing you to
normalize input before checking:

  username => {
    type => 'string',
    transform => sub { lc($_[0]) },  # Normalize to lowercase
    notmemberof => ['admin', 'root', 'system']
  }

C<notmemberof> can be combined with other validation rules:

  username => {
    type => 'string',
    notmemberof => ['admin', 'root', 'system'],
    min => 3,
    max => 20,
    matches => qr/^[a-z0-9_]+$/
  }

=item * C<case_sensitive>

A boolean value indicating whether string comparisons should be case-sensitive.
This flag affects the C<memberof> and C<notmemberof> validation rules.
The default value is C<1> (case-sensitive).

When set to C<0>, string comparisons are performed case-insensitively, allowing values
with different casing to match. The original case of the input value is preserved in
the validated output.

  # Case-sensitive (default)
  status => {
    type => 'string',
    memberof => ['Draft', 'Published', 'Archived'] # Input 'draft' will fail - must match exact case
  }

  # Case-insensitive
  status => {
    type => 'string',
    memberof => ['Draft', 'Published', 'Archived'],
    case_sensitive => 0 # Input 'draft', 'DRAFT', or 'DrAfT' will all pass
  }

  country_code => {
    type => 'string',
    memberof => ['US', 'UK', 'CA', 'FR'],
    case_sensitive => 0  # Accept 'us', 'US', 'Us', etc.
  }

This flag has no effect on numeric types (C<integer>, C<number>, C<float>) as numbers
do not have case.

=item * C<min>/C<minimum>

The minimum length (for strings in characters not bytes), value (for numbers) or number of keys (for hashrefs).

=item * C<max>

The maximum length (for strings in characters not bytes), value (for numbers) or number of keys (for hashrefs).

=item * C<matches>

A regular expression that the parameter value must match.
Checks all members of arrayrefs.

=item * C<nomatch>

A regular expression that the parameter value must not match.
Checks all members of arrayrefs.

=item * C<bnf>

An arrayref of BNF grammar lines that defines the set of strings the
parameter value must belong to.
The first rule in the grammar is the start rule; the value must match it
exactly (anchored).

Each element is either a rule definition (C<< <name> ::= ... >>) or a
continuation of the previous rule.  Terminals are double-quoted; non-terminals
use angle brackets.  Alternatives are separated by C<|>.

  $schema = {
    na_tel_no => {
      type => 'string',
      bnf  => [
        '<telephone-number> ::= <country-code-opt> <area-code> <separator-opt>',
        '<central-office-code> <separator-opt> <station-code>',
        '<country-code-opt> ::= "" | "+1" | "1"',
        '<separator-opt>    ::= "" | "-" | " " | "."',
        '<area-code>        ::= <digit2-9> <digit0-9> <digit0-9>',
        '<central-office-code> ::= <digit2-9> <digit0-9> <digit0-9>',
        '<station-code>     ::= <digit0-9> <digit0-9> <digit0-9> <digit0-9>',
        '<digit0-9> ::= "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"',
        '<digit2-9> ::= "2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"',
      ],
    },
  };

Implemented by L<Params::Validate::Strict::BNF>.  Recursive grammars are not
supported.

=item * C<position>

For routines and methods that take positional args,
this integer value defines which position the argument will be in.
If this is set for all arguments,
C<validate_strict> will return a reference to an array, rather than a reference to a hash.

=item * C<slurp>

Valid only in positional-argument schemas (those where every parameter has a
C<position> value).  When C<slurp =E<gt> 1> is set, this parameter collects
I<all> remaining positional arguments starting from C<position> into an
arrayref, rather than taking only the single element at that index.

  # sub log_message($level, @messages)
  my $schema = {
    level    => { type => 'string',   position => 0 },
    messages => { type => 'arrayref', position => 1, slurp => 1 },
  };

The slurp parameter is implicitly optional: if there are no arguments at or
beyond C<position>, the value is an empty arrayref.  Combine with C<min =E<gt>
1> to require at least one element:

  messages => { type => 'arrayref', position => 1, slurp => 1, min => 1 }

At most one slurp parameter may be defined per schema, and it must have the
highest C<position> value.  The return value at that position is an arrayref.

=item * C<aliases>

An arrayref of alternative input-key names that are also accepted for this
parameter.  When any alias is found in the input the parameter is stored
under its canonical schema key; if both the canonical name and an alias are
present the canonical name takes precedence.  Aliases are not treated as
unknown parameters regardless of the C<unknown_parameter_handler> setting.

  colour => {
    type    => 'string',
    aliases => ['color'],
    memberof => ['red', 'green', 'blue'],
  }

Only named (hashref) input supports aliases; positional (arrayref) input
ignores them.

=item * C<regex>

Synonym of matches

=item * C<description>

The description of the rule

=item * C<callback>

A code reference to a subroutine that performs custom validation logic.
The subroutine is called with four arguments: the parameter value, the argument list, the schema and the name of the parameter being validated
(the canonical name, even if the value was supplied under an alias).
It should return true if the value is valid, false otherwise.
The name lets one callback be shared between several parameters.

Use this to test more complex examples:

  my $schema = {
    even_number => {
      type => 'integer',
      callback => sub { $_[0] % 2 == 0 }
  };

  # Specify the arguments for a routine which has a second, optional argument, which, if given, must be less than or equal to the first
  my $schema = {
    first => {
      type => 'integer'
    }, second => {
      type => 'integer',
      optional => 1,
      callback => sub {
        my($value, $args) = @_;
        # The 'defined' is needed in case 'second' is evaluated before 'first'
        return (defined($args->{first}) && $value <= $args->{first}) ? 1 : 0
      }
    }
  };

=item * C<optional>

A boolean value indicating whether the parameter is optional.
If true, the parameter is not required.
If false or omitted, the parameter is required.

It can be a reference to a code snippet that will return true or false,
to determine if the parameter is optional or not.
The code will be called with two arguments: the value of the parameter and hash ref of all parameters:

  my $schema = {
    optional_field => {
      type => 'string',
      optional => sub {
        my ($value, $all_params) = @_;
        return $all_params->{make_optional} ? 1 : 0;
      }
    },
    make_optional => { type => 'boolean' }
  };

  my $result = validate_strict(schema => $schema, input => { make_optional => 1 });

If the parameter is not optional, it can be passed an undef value, which will not flag an error.
This is by design.
So this will not say that the required parameter 's' is missing:

    validate_strict(
        schema => { s => { type => 'string' } },
        input  => { s => undef },
    );

=item * C<default>

Populate missing optional parameters with the specified value.
Note that this value is not validated.

  username => {
    type => 'string',
    optional => 1,
    default => 'guest'
  }

=item * C<element_type>

Extends the validation to individual elements of arrays.

  tags => {
    type => 'arrayref',
    element_type => 'number',        # Float means the same
    min => 1,        # this is the length of the array, not the min value for each of the numbers. For that, add a C<schema> rule
    max => 5
  }

=item * C<error_msg>

The custom error message to be used in the event of a validation failure.

  age => {
    type => 'integer',
    min => 18,
    error_msg => 'You must be at least 18 years old'
  }

=item * C<nullable>

Like optional,
though this cannot be a coderef,
only a flag.

=item * C<schema>

You can validate nested hashrefs and arrayrefs using the C<schema> property:

    my $schema = {
        user => {    # 'user' is a hashref
            type => 'hashref',
            schema => {      # Specify what the elements of the hash should be
                name => { type => 'string' },
                age => { type => 'integer', min => 0 },
                hobbies => { # 'hobbies' is an array ref that this user has
                    type => 'arrayref',
                    schema => { type => 'string' }, # Validate each hobby
                    min => 1 # At least one hobby
                }
            }
        }, metadata => {
            type => 'hashref',
            schema => {
                created => { type => 'string' },
                tags => {
                    type => 'arrayref',
                    schema => {
                        type => 'string',
                        matches => qr/^[a-z]+$/      # Or you can say matches => '^[a-z]+$'
                    }
                }
            }
        }
    };

=item * C<validate>

A snippet of code that validates the input.
It's passed the input arguments,
and return a string containing a reason for rejection,
or undef if it's allowed.

    my $schema = {
      user => {
        type => 'string',
        validate => sub {
          if($_[0]->{'password'} eq 'bar') {
            return undef;
          }
          return 'Invalid password, try again';
        }
      }, password => {
         type => 'string'
      }
    };

=item * C<transform>

A code reference to a subroutine that transforms/sanitizes the parameter value before validation.
The subroutine should accept the parameter value as an argument and return the transformed value.
The transformation is applied before any validation rules are checked, allowing you to normalize
or clean data before it is validated.

Common use cases include trimming whitespace, normalizing case, formatting phone numbers,
sanitizing user input, and converting between data formats.

  # Simple string transformations
  username => {
    type => 'string',
    transform => sub { lc(trim($_[0])) },  # lowercase and trim
    matches => qr/^[a-z0-9_]+$/
  }

  email => {
    type => 'string',
    transform => sub { lc(trim($_[0])) },  # normalize email
    matches => qr/^[^@\s]+\@[^@\s]+\.[^@\s]+$/
  }

  # Array transformations
  tags => {
    type => 'arrayref',
    transform => sub { [map { lc($_) } @{$_[0]}] },  # lowercase all elements
    element_type => 'string'
  }

  keywords => {
    type => 'arrayref',
    transform => sub {
      my @arr = map { lc(trim($_)) } @{$_[0]};
      my %seen;
      return [grep { !$seen{$_}++ } @arr];  # remove duplicates
    }
  }

  # Numeric transformations
  quantity => {
    type => 'integer',
    transform => sub { int($_[0] + 0.5) },  # round to nearest integer
    min => 1
  }

  # Sanitization
  slug => {
    type => 'string',
    transform => sub {
      my $str = lc(trim($_[0]));
      $str =~ s/[^\w\s-]//g;  # remove special characters
      $str =~ s/\s+/-/g;      # replace spaces with hyphens
      return $str;
    },
    matches => qr/^[a-z0-9-]+$/
  }

  phone => {
    type => 'string',
    transform => sub {
      my $str = $_[0];
      $str =~ s/\D//g;  # remove all non-digits
      return $str;
    },
    matches => qr/^\d{10}$/
  }

The C<transform> function is applied to the value before any validation checks (C<min>/C<minimum>, C<max>,
C<matches>, C<callback>, etc.), ensuring that validation rules are checked against the cleaned data.

Transformations work with all parameter types including nested structures:

  user => {
    type => 'hashref',
    schema => {
      name => {
        type => 'string',
        transform => sub { trim($_[0]) }
      }, email => {
        type => 'string',
        transform => sub { lc(trim($_[0])) }
      }
    }
  }

Transformations can also be defined in custom types for reusability:

  my $custom_types = {
    email => {
      type => 'string',
      transform => sub { lc(trim($_[0])) },
      matches => qr/^[^@\s]+\@[^@\s]+\.[^@\s]+$/
    }
  };

Note that the transformed value is what gets returned in the validated result and is what
subsequent validation rules will check against. If a transformation might fail, ensure it
handles edge cases appropriately.
It is the responsibility of the transformer to ensure that the type of the returned value is correct,
since that is what will be validated.

Many validators also allow a code ref to be passed so that you can create your own, conditional validation rule, e.g.:

  $schema = {
    age => {
      type => 'integer',
      min => sub {
          my ($value, $all_params) = @_;
          return $all_params->{country} eq 'US' ? 21 : 18;
      }
    }
  }

=item * C<validator>

A synonym of C<validate>, for compatibility with L<Data::Processor>.

=item * C<cross_validation>

A reference to a hash that defines validation rules that depend on more than one parameter.
Cross-field validations are performed after all individual parameter validations have passed,
allowing you to enforce business logic that requires checking relationships between different fields.

Each cross-validation rule is a key-value pair where the key is a descriptive name for the validation
and the value is a code reference that accepts a hash reference of all validated parameters.
The subroutine should return C<undef> if the validation passes, or an error message string if it fails.

  my $schema = {
    password => { type => 'string', min => 8 },
    password_confirm => { type => 'string' }
  };

  my $cross_validation = {
    passwords_match => sub {
      my $params = shift;
      return $params->{password} eq $params->{password_confirm}
        ? undef : "Passwords don't match";
    }
  };

  my $validated = validate_strict(
    schema => $schema,
    input => $input,
    cross_validation => $cross_validation
  );

Common use cases include password confirmation, date range validation, numeric comparisons,
and conditional requirements:

  # Date range validation
  my $cross_validation = {
    date_range_valid => sub {
      my $params = shift;
      return $params->{start_date} le $params->{end_date}
        ? undef : "Start date must be before or equal to end date";
    }
  };

  # Price range validation
  my $cross_validation = {
    price_range_valid => sub {
      my $params = shift;
      return $params->{min_price} <= $params->{max_price}
        ? undef : "Minimum price must be less than or equal to maximum price";
    }
  };

  # Conditional required field
  my $cross_validation = {
    address_required_for_delivery => sub {
      my $params = shift;
      if ($params->{shipping_method} eq 'delivery' && !$params->{delivery_address}) {
        return "Delivery address is required when shipping method is 'delivery'";
      }
      return undef;
    }
  };

Multiple cross-validations can be defined in the same hash, and they are all checked in order.
If any cross-validation fails, the function will C<croak> with the error message returned by the validation:

  my $cross_validation = {
    passwords_match => sub {
      my $params = shift;
      return $params->{password} eq $params->{password_confirm}
        ? undef : "Passwords don't match";
    },
    emails_match => sub {
      my $params = shift;
      return $params->{email} eq $params->{email_confirm}
        ? undef : "Email addresses don't match";
    },
    age_matches_birth_year => sub {
      my $params = shift;
      my $current_year = (localtime)[5] + 1900;
      my $calculated_age = $current_year - $params->{birth_year};
      return abs($calculated_age - $params->{age}) <= 1
        ? undef : "Age doesn't match birth year";
    }
  };

Cross-validations receive the parameters after individual validation and transformation have been applied,
so you can rely on the data being in the correct format and type:

  my $schema = {
    email => {
      type => 'string',
      transform => sub { lc($_[0]) }  # Lowercased before cross-validation
    },
    email_confirm => {
      type => 'string',
      transform => sub { lc($_[0]) }
    }
  };

  my $cross_validation = {
    emails_match => sub {
      my $params = shift;
      # Both emails are already lowercased at this point
      return $params->{email} eq $params->{email_confirm}
        ? undef : "Email addresses don't match";
    }
  };

Cross-validations can access nested structures and optional fields:

  my $cross_validation = {
    guardian_required_for_minors => sub {
      my $params = shift;
      if ($params->{user}{age} < 18 && !$params->{guardian}) {
        return "Guardian information required for users under 18";
      }
      return undef;
    }
  };

All cross-validations must pass for the overall validation to succeed.

=item * metadata

Fields starting with <_> are generated by L<App::Test::Generator::SchemaExtractor>,
and are currently ignored.

=item * C<semantic>

A hint about the semantic meaning of the parameter value.
Supported values: C<unix_timestamp>, C<identifier>, C<class_name>, C<filename>.

  ts     => { type => 'integer', semantic => 'unix_timestamp' }
  func   => { type => 'string',  semantic => 'identifier' }
  module => { type => 'string',  semantic => 'class_name' }
  file   => { type => 'string',  semantic => 'filename' }

When C<semantic> is C<unix_timestamp>, the value must be a non-negative integer no greater than
C<2147483647> (i.e. a valid 32-bit Unix epoch timestamp).
Values outside this range cause the function to C<croak>.

When C<semantic> is C<identifier>, the value must match C</\A[A-Za-z_]\w*\z/>, a single
valid Perl bareword identifier.  Package separators (C<::>) are not permitted; use
C<class_name> for those.

When C<semantic> is C<class_name>, the value must match
C</\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/>, a syntactically valid Perl class name such
as C<'Foo'> or C<'Foo::Bar::Baz'>.  The class does not need to be loaded.

When C<semantic> is C<filename>, the value must be a single path component:
non-empty, not C<.> or C<..>, containing neither C</> nor a NUL byte, and at most 255
bytes long when encoded as UTF-8.  Directory parts are rejected, so it is safe against
path traversal such as C<../../etc/passwd>.  It does not check that the file exists, and
it does not reject characters that are only illegal on some platforms (such as C<:> on Windows).

Unknown semantic values emit a warning but do not cause an error.

=item * C<relationships>

A reference to an array that defines validation rules based on relationships between parameters.
Relationship validations are performed after all individual parameter validations have passed,
but before cross-validations.

Each relationship is a hash reference with a C<type> field and additional fields depending on the type:

=over 4

=item * B<mutually_exclusive>

Parameters that cannot be specified together.

  relationships => [
    {
      type => 'mutually_exclusive',
      params => ['file', 'content'],
      description => 'Cannot specify both file and content'
    }
  ]

=item * B<required_group>

At least one parameter from the group must be specified.

  relationships => [
    {
      type => 'required_group',
      params => ['id', 'name'],
      logic => 'or',
      description => 'Must specify either id or name'
    }
  ]

=item * B<conditional_requirement>

If one parameter is specified, another becomes required.

  relationships => [
    {
      type => 'conditional_requirement',
      if => 'async',
      then_required => 'callback',
      description => 'When async is specified, callback is required'
    }
  ]

=item * B<dependency>

One parameter requires another to be present.

  relationships => [
    {
      type => 'dependency',
      param => 'port',
      requires => 'host',
      description => 'port requires host to be specified'
    }
  ]

=item * B<value_constraint>

Specific value requirements between parameters.

  relationships => [
    {
      type => 'value_constraint',
      if => 'ssl',
      then => 'port',
      operator => '==',
      value => 443,
      description => 'When ssl is specified, port must equal 443'
    }
  ]

=item * B<value_conditional>

Parameter required when another has a specific value.

  relationships => [
    {
      type => 'value_conditional',
      if => 'mode',
      equals => 'secure',
      then_required => 'key',
      description => "When mode equals 'secure', key is required"
    }
  ]

=back

If a parameter is optional and its value is C<undef>,
validation will be skipped for that parameter.

If the validation fails, the function will C<croak> with an error message describing the validation failure.

If the validation is successful, the function will return a reference to a new hash containing the validated and (where applicable) coerced parameters.  Integer and number parameters will be coerced to their respective types.

The C<description> field is optional but recommended for clearer error messages.

=back

=head3 API SPECIFICATION

=head4 Input

  {
      schema                    => { type => ['hashref', 'arrayref'] },   # or members
      input                     => { type => ['hashref', 'arrayref'] },   # or args
      description               => { type => 'string',  optional => 1 },
      custom_types              => { type => 'hashref', optional => 1 },
      unknown_parameter_handler => { type => 'string',  optional => 1,
                                     memberof => ['die', 'warn', 'ignore'] },
      logger                    => { type => 'object',  optional => 1, can => ['error', 'warn'] },
      relationships             => { type => 'arrayref', optional => 1 },
      cross_validation          => { type => 'hashref', optional => 1 },
  }

The arguments may be passed as a list of key/value pairs or as a single hashref.
A hashref C<input> is validated as named parameters; an arrayref C<input> is validated as
positional parameters, in which case every parameter in the schema needs a C<position>.

=head4 Output

  { type => 'hashref' }

A new hashref of the validated and coerced parameters, keyed by canonical parameter name.
It croaks (or calls C<< $logger->error >> and then croaks) on the first validation failure.

=head2 Example Usage

  my $schema = {
    host => { type => 'string' },
    port => { type => 'integer' },
    ssl => { type => 'boolean' },
    file => { type => 'string', optional => 1 },
    content => { type => 'string', optional => 1 }
  };

  my $relationships = [
    {
      type => 'mutually_exclusive',
      params => ['file', 'content']
    }, {
      type => 'required_group',
      params => ['host', 'file']
    },
    {
      type => 'dependency',
      param => 'port',
      requires => 'host'
    },
    {
      type => 'value_constraint',
      if => 'ssl',
      then => 'port',
      operator => '==',
      value => 443
    }
  ];

  my $validated = validate_strict(
    schema => $schema,
    input => $input,
    relationships => $relationships
  );

=head1 MIGRATION FROM LEGACY VALIDATORS

=head2 From L<Params::Validate>

    # Old style
    validate(@_, {
        name => { type => SCALAR },
        age => { type => SCALAR, regex => qr/^\d+$/ }
    });

    # New style
    validate_strict(
        schema => {  # or "members"
            name => 'string',
            age => { type => 'integer', min => 0 }
        },
        args => { @_ }
    );

=head2 From L<Type::Params>

    # Old style
    my ($name, $age) = validate_positional \@_, Str, Int;

    # New style - requires converting to named parameters first
    my %args = (name => $_[0], age => $_[1]);
    my $validated = validate_strict(
        schema => { name => 'string', age => 'integer' },
        args => \%args
    );

=cut
1221
1222sub validate_strict
1223{
1224
48540
6344058
        local $_depth = $_depth + 1;
1225
48540
44215
        Carp::croak('validate_strict: maximum call depth exceeded - possible infinite recursion in union-type schema')
1226                if $_depth > 20;
1227
1228        # $params is only ever read, so a hashref argument need not be copied
1229
48539
54837
        my $params = (ref($_[0]) eq 'HASH') ? $_[0] : { @_ };
1230
1231
48539
49723
        my $schema = $params->{'schema'} || $params->{'members'};
1232
48539
64207
        my $args = $params->{'args'} || $params->{'input'};
1233
48539
33003
        my $logger = $params->{'logger'};
1234
48539
32960
        my $custom_types = $params->{'custom_types'};
1235
48539
34710
        my $unknown_parameter_handler = $params->{'unknown_parameter_handler'};
1236
48539
42350
        if(!defined($unknown_parameter_handler)) {
1237
48293
38355
                if($params->{'carp_on_warn'}) {
1238
2
2
                        $unknown_parameter_handler = 'warn';
1239                } else {
1240
48291
32807
                        $unknown_parameter_handler = 'die';
1241                }
1242        }
1243
1244
48539
42204
        return $args if(!defined($schema));     # No schema, allow all arguments
1245
1246        # Accept arrayref schema: [{ name=>'param', type=>'...', ... }, ...]
1247        # Normalise to the standard named-parameter hashref form before further processing.
1248
48535
44219
        if(ref($schema) eq 'ARRAY') {
1249
17
17
                $schema = _schema_from_arrayref($schema, $logger);
1250        }
1251
1252        # Check if schema and args are references to hashes
1253
48528
40337
        if(ref($schema) ne 'HASH') {
1254
3
4
                _error($logger, 'validate_strict: schema must be a hash reference');
1255        }
1256
1257        # Inspired by Data::Processor
1258
48525
59046
        my $schema_description = $params->{'description'} || 'validate_strict';
1259
48525
33701
        my $error_msg = $params->{'error_msg'};
1260
1261
48525
41369
        if($schema->{'members'} && ($schema->{'description'} || $schema->{'error_msg'})) {
1262
8
8
                $schema_description = $schema->{'description'};
1263
8
10
                $error_msg = $schema->{'error_msg'};
1264
8
7
                $schema = $schema->{'members'};
1265                # The members value may also be in arrayref form
1266
8
9
                if(ref($schema) eq 'ARRAY') {
1267
1
2
                        $schema = _schema_from_arrayref($schema, $logger);
1268                }
1269        }
1270
1271
48525
74438
        if(exists($params->{'args'}) && (!defined($args))) {
1272
2
2
                $args = {};
1273        } elsif((ref($args) ne 'HASH') && (ref($args) ne 'ARRAY')) {
1274
4
10
                _error($logger, $error_msg || "$schema_description: args must be a hash or array reference");
1275        }
1276
1277        # A schema prepared by compile_schema carries pre-computed per-field records
1278        # that let simple fields bypass the generic rule interpreter below.  It is
1279        # honoured only when it describes exactly the schema now in hand and the
1280        # input is a named-argument hash.
1281
48521
32401
        my $compiled = $params->{'_compiled'};
1282
48521
30476
        my $fields;
1283
48521
73280
        if($compiled && ref($args) eq 'HASH' && $schema == $compiled->{'schema'}) {
1284
23153
16889
                $fields = $compiled->{'fields'};
1285        } else {
1286
25368
16872
                $compiled = undef;
1287        }
1288
1289
48521
43606
        if(ref($args) eq 'HASH') {
1290                # Named args: build alias reverse-map first so aliased keys are not
1291                # treated as unknown parameters.  A compiled schema already knows
1292                # whether it has any aliases.
1293
48489
28178
                my %_alias_to_canonical;
1294
48489
57966
                if(!$compiled || $compiled->{'has_aliases'}) {
1295
25386
25386
14319
22325
                        foreach my $canonical (keys %{$schema}) {
1296
27025
17880
                                my $r = $schema->{$canonical};
1297
27025
42175
                                if(ref($r) eq 'HASH' && ref($r->{'aliases'}) eq 'ARRAY') {
1298
106
106
69
187
                                        $_alias_to_canonical{$_} = $canonical for @{$r->{'aliases'}};
1299                                }
1300                        }
1301                }
1302
1303
48489
48489
31689
45630
                foreach my $key (keys %{$args}) {
1304
48623
51046
                        if(!exists($schema->{$key}) && !exists($_alias_to_canonical{$key})) {
1305
3266
2888
                                if($unknown_parameter_handler eq 'die') {
1306
3211
3473
                                        _error($logger, "$schema_description: Unknown parameter '$key'");
1307                                } elsif($unknown_parameter_handler eq 'warn') {
1308
24
43
                                        _warn($logger, "$schema_description: Unknown parameter '$key'");
1309
24
2036
                                        next;
1310                                } elsif($unknown_parameter_handler eq 'ignore') {
1311
17
22
                                        if($logger) {
1312
1
3
                                                $logger->debug(__PACKAGE__ . ": $schema_description: Unknown parameter '$key'");
1313                                        }
1314
17
23
                                        next;
1315                                } else {
1316
14
20
                                        _error($logger, "$schema_description: '$unknown_parameter_handler' unknown_parameter_handler must be one of die, warn, ignore");
1317                                }
1318                        }
1319                }
1320        }
1321
1322        # Find out if this routine takes positional arguments
1323
45296
31175
        my $are_positional_args = -1;
1324        # compile_schema only prepares schemas that are not positional, so a compiled
1325        # schema supplies the answer and the detection loop has nothing to do.
1326
45296
37683
        $are_positional_args = $compiled->{'positional'} if($compiled);
1327
45296
23749
37847
20879
        foreach my $key ($compiled ? () : keys %{$schema}) {
1328
23756
20220
                if(defined(my $rules = $schema->{$key})) {
1329
23754
21175
                        if(ref($rules) eq 'HASH') {
1330
23686
21400
                                if($rules->{'slurp'} && !defined($rules->{'position'})) {
1331
0
0
                                        _error($logger, "::validate_strict: slurp parameter '$key' requires a 'position'");
1332                                }
1333
23686
21256
                                if(!defined($rules->{'position'})) {
1334
23637
19293
                                        if($are_positional_args == 1) {
1335
0
0
                                                _error($logger, "::validate_strict: $key is missing position value");
1336                                        }
1337
23637
13761
                                        $are_positional_args = 0;
1338
23637
18214
                                        last;
1339                                }
1340
49
39
                                $are_positional_args = 1;
1341                        } else {
1342
68
51
                                $are_positional_args = 0;
1343
68
59
                                last;
1344                        }
1345                } else {
1346
2
2
                        $are_positional_args = 0;
1347
2
2
                        last;
1348                }
1349        }
1350
1351
45296
32335
        my %validated_args;
1352        my %invalid_args;
1353
45296
27859
        my $has_needs = 0;      # true if any parameter has a 'needs' rule
1354
45296
45296
27065
38341
        foreach my $key (keys %{$schema}) {
1355                # Fast path: a field that compile_schema fully understood is validated
1356                # here without the generic interpreter.  It must produce exactly the same
1357                # result and error messages as the generic code below; t/compile_schema.t
1358                # checks the two against each other.  Fields it does not understand have no
1359                # record and fall through.
1360
46548
53864
                if($fields && (my $f = $fields->{$key})) {
1361
11307
8207
                        my $value = $args->{$key};
1362
1363
11307
9680
                        if(!exists($args->{$key})) {
1364
523
511
                                if($f->{'opt'}) {
1365
184
256
                                        $validated_args{$key} //= $f->{'default'} if($f->{'has_default'});
1366
184
144
                                        next;
1367                                }
1368
339
361
                                _error($logger, "$schema_description: Required parameter $f->{label} is missing");
1369                        }
1370
1371
10784
7765
                        my $label = $f->{'label'};
1372
10784
6885
                        my $frules = $f->{'rules'};
1373
10784
7022
                        my $t = $f->{'t'};
1374
1375
10784
14528
                        if($t == _T_STRING) {
1376
2280
1872
                                if(ref($value)) {
1377
588
641
                                        _rule_error($logger, $frules, "$schema_description: Parameter $label must be a string");
1378                                }
1379                        } elsif($t == _T_INT) {
1380
2020
1779
                                if(defined($value)) {
1381
1940
3606
                                        if(!Scalar::Util::looks_like_number($value) || ($value - $value) != 0 || $value != int($value)) {
1382
1364
1683
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be an integer");
1383                                        }
1384
576
414
                                        $value = int($value);
1385                                }
1386                        } elsif($t == _T_NUM) {
1387
2392
2042
                                if(defined($value)) {
1388
2300
2383
                                        if(!Scalar::Util::looks_like_number($value)) {
1389
1472
1532
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label must be a number");
1390                                        }
1391
828
727
                                        $value = 0 + $value;
1392                                }
1393                        } elsif($t == _T_BOOL) {
1394
889
691
                                if(defined($value)) {
1395
855
1393
                                        if(defined(my $b = $Readonly::Values::Boolean::booleans{$value})) {
1396
141
417
                                                $value = $b;
1397                                        } else {
1398
714
2380
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be a boolean");
1399                                        }
1400                                }
1401                        } elsif($t == _T_ARRAY) {
1402
1357
1875
                                if(defined($value) && ref($value) ne 'ARRAY') {
1403
1196
1378
                                        _rule_error($logger, $frules, "$schema_description: Parameter $label must be an arrayref, not " . ref($value));
1404                                }
1405                        } elsif($t == _T_HASH) {
1406
676
1032
                                if(defined($value) && ref($value) ne 'HASH') {
1407
598
621
                                        _rule_error($logger, $frules, "$schema_description: Parameter $label must be an hashref");
1408                                }
1409                        } elsif($t == _T_SCALAR) {
1410
442
587
                                if(defined($value) && ref($value)) {
1411
119
140
                                        _rule_error($logger, $frules, "$schema_description: Parameter $label must be a scalar, not a " . ref($value) . ' reference');
1412                                }
1413                        } elsif($t == _T_CODE) {
1414
364
493
                                if(defined($value) && ref($value) ne 'CODE') {
1415
336
388
                                        _rule_error($logger, $frules, "$schema_description: Parameter $label must be a coderef, not a ref to " . ref($value));
1416                                }
1417                        } else {        # _T_OBJECT
1418
364
631
                                if(defined($value) && !Scalar::Util::blessed($value)) {
1419
336
375
                                        _rule_error($logger, $frules, "$schema_description: Parameter $label must be an object");
1420                                }
1421                        }
1422
1423
4061
2678
                        my $chars;      # the character count, computed at most once for min and max
1424
4061
3687
                        if(defined(my $min = $f->{'min'})) {
1425
933
652
                                my $mk = $f->{'mk'};
1426
933
1008
                                if($mk eq 's') {
1427
496
493
                                        if(!defined($value)) {
1428
24
37
                                                if($min > 0 && !$f->{'opt'}) {
1429
18
34
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label is undefined, but must be at least $min character" . ($min == 1 ? '' : 's'));
1430                                                }
1431                                        } elsif(defined(my $len = ($chars = _number_of_characters($value)))) {
1432
472
421
                                                if($len < $min) {
1433
42
52
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label too short, ($len characters), must be at least $min characters");
1434                                                }
1435                                        } else {
1436
0
0
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label can't be decoded");
1437                                        }
1438                                } elsif($mk eq 'a') {
1439
54
48
                                        if(!defined($value)) {
1440
18
30
                                                if($min > 0 && !$f->{'opt'}) {
1441
12
23
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label is undefined, but must have at least $min member" . ($min > 1 ? 's' : ''));
1442                                                }
1443
36
43
                                        } elsif(scalar(@{$value}) < $min) {
1444
14
29
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label must have at least $min member" . (($min > 1) ? 's' : ''));
1445                                        }
1446                                } elsif($mk eq 'h') {
1447
27
26
                                        if(!defined($value)) {
1448
9
13
                                                if($min > 0 && !$f->{'opt'}) {
1449
6
21
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label is undefined, but must contain at least $min keys");
1450                                                }
1451
18
21
                                        } elsif(scalar(keys(%{$value})) < $min) {
1452
7
11
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label must contain at least $min keys");
1453                                        }
1454                                } else {        # 'n': integer, number or float
1455
356
374
                                        if(!defined($value)) {
1456
36
53
                                                if($min > 0 && !$f->{'opt'}) {
1457
24
33
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label is undefined, but must be at least $min");
1458                                                }
1459                                        } elsif(Scalar::Util::looks_like_number($value)) {
1460
320
300
                                                if($value < $min) {
1461
72
166
                                                        if($frules->{'error_msg'}) {
1462
8
9
                                                                _error($logger, $frules->{'error_msg'});
1463                                                        } elsif(($f->{'tname'} eq 'integer') && ($value == 0)) {
1464
13
18
                                                                _error($logger, "$schema_description: Parameter $label ($value) must be a positive number");
1465                                                        } elsif(($f->{'tname'} eq 'integer') && ($value == 1)) {
1466
2
4
                                                                _error($logger, "$schema_description: Parameter $label ($value) must be a positive, non-zero number");
1467                                                        } else {
1468
49
71
                                                                _error($logger, "$schema_description: Parameter $label ($value) must be at least $min");
1469                                                        }
1470                                                }
1471                                        } else {
1472
0
0
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be a number");
1473                                        }
1474                                }
1475                        }
1476
1477
3866
4031
                        if(defined(my $max = $f->{'max'}) && defined($value)) {
1478
462
303
                                my $mk = $f->{'mk'};
1479
462
443
                                if($mk eq 's') {
1480
281
324
                                        if(defined(my $len = $chars // _number_of_characters($value))) {
1481
281
261
                                                if($len > $max) {
1482
111
128
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label too long, ($len characters), must be no longer than $max");
1483                                                }
1484                                        } else {
1485
0
0
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label can't be decoded");
1486                                        }
1487                                } elsif($mk eq 'a') {
1488
16
16
12
18
                                        if(scalar(@{$value}) > $max) {
1489
10
15
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label must contain no more than $max items");
1490                                        }
1491                                } elsif($mk eq 'h') {
1492
8
8
6
10
                                        if(scalar(keys(%{$value})) > $max) {
1493
0
0
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label must contain no more than $max keys");
1494                                        }
1495                                } else {        # 'n': integer, number or float
1496
157
147
                                        if(Scalar::Util::looks_like_number($value)) {
1497
157
133
                                                if($value > $max) {
1498
105
188
                                                        if($frules->{'error_msg'}) {
1499
0
0
                                                                _error($logger, $frules->{'error_msg'});
1500                                                        } elsif(($f->{'tname'} eq 'integer') && ($value == 0)) {
1501
0
0
                                                                _error($logger, "$schema_description: Parameter $label ($value) must be a negative number");
1502                                                        } elsif(($f->{'tname'} eq 'integer') && ($value == -1)) {
1503
0
0
                                                                _error($logger, "$schema_description: Parameter $label ($value) must be a negative, non-zero number");
1504                                                        } else {
1505
105
125
                                                                _error($logger, "$schema_description: Parameter $label ($value) must be no more than $max");
1506                                                        }
1507                                                }
1508                                        } else {
1509
0
0
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be a number");
1510                                        }
1511                                }
1512                        }
1513
1514
3640
3044
                        if(defined($value)) {
1515
3286
3112
                                if(my $re = $f->{'re'}) {
1516                                        # As in the generic 'matches' handler, a failed match is raised
1517                                        # inside an eval and then re-raised wrapped, so the messages agree.
1518
440
286
                                        eval {
1519
440
792
                                                if($value !~ $re) {
1520
332
507
                                                        _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must match pattern '$re'");
1521                                                }
1522
108
99
                                                1;
1523                                        };
1524
440
32901
                                        if($@) {
1525
332
472
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label regex '$f->{match_src}' error: $@");
1526                                        }
1527                                }
1528
2954
2681
                                if(my $list = $f->{'list'}) {
1529
725
819
                                        unless(_value_in_list($value, $list, $f->{'type'}, $frules->{'case_sensitive'})) {
1530
589
589
580
753
                                                _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be one of ", join(', ', @{$list}));
1531                                        }
1532                                }
1533                        }
1534
1535
2719
2236
                        $validated_args{$key} = $value;
1536
2719
2433
                        next;
1537                }
1538
1539
35241
23617
                my $rules = $schema->{$key};
1540
1541                # For named-arg schemas: resolve which input key provides this parameter.
1542                # If the canonical name is absent, try each alias in order.
1543
35241
21506
                my $lookup_key = $key;
1544
35241
69531
                if($are_positional_args != 1 && ref($rules) eq 'HASH'
1545                   && ref($rules->{'aliases'}) eq 'ARRAY'
1546                   && !exists($args->{$key})) {
1547
38
38
23
39
                        for my $alias (@{$rules->{'aliases'}}) {
1548
62
58
                                if(exists($args->{$alias})) {
1549
23
13
                                        $lookup_key = $alias;
1550
23
18
                                        last;
1551                                }
1552                        }
1553                }
1554
1555
35241
21560
                my $value;
1556
35241
23976
                if($are_positional_args == 1) {
1557
48
63
                        if(ref($args) ne 'ARRAY') {
1558
0
0
                                _error($logger, "::validate_strict: position $rules->{position} given for '$key', but args isn't an array");
1559                        }
1560
48
85
                        if(ref($rules) eq 'HASH' && $rules->{'slurp'}) {
1561
4
4
                                my $pos = $rules->{'position'};
1562
4
4
5
4
                                $value = [@{$args}[$pos .. $#$args]];
1563                        } else {
1564
44
67
                                $value = $args->[$rules->{'position'}];
1565                        }
1566                } else {
1567
35193
23907
                        $value = $args->{$lookup_key};
1568                }
1569
1570
35240
26176
                if(!defined($rules)) {  # Allow anything
1571
76
54
                        $validated_args{$key} = $value;
1572
76
59
                        next;
1573                }
1574
1575                # If rules are a simple type string
1576
35164
29769
                if(ref($rules) eq '') {
1577
163
141
                        $rules = { type => $rules };
1578                }
1579
1580
35164
44859
                $has_needs = 1 if(ref($rules) eq 'HASH' && defined($rules->{'needs'}));
1581
1582
35164
20412
                my $is_optional = 0;
1583
1584
35164
21976
                my $rule_description = $schema_description;     # Can be overridden in each element
1585
35164
23334
                my $param_label = "'$key'";
1586
1587
35164
27648
                if(ref($rules) eq 'HASH') {
1588
35144
27214
                        if(exists($rules->{'description'})) {
1589
1899
1504
                                $param_label = "'$key' ($rules->{description})";
1590                        }
1591                        # For stringref: validate and dereference before transform so that
1592                        # transform (and all subsequent rule handlers) see the plain string.
1593                        # Preserve the original ref so optional => CODE receives what the caller passed.
1594
35144
22015
                        my $pre_deref_value = $value;
1595
35144
71338
                        my $is_stringref_type = defined($value) && defined($rules->{'type'}) && !ref($rules->{'type'}) && lc($rules->{'type'}) eq 'stringref';
1596
35144
27399
                        if($is_stringref_type) {
1597
116
110
                                if(ref($value) ne 'SCALAR') {
1598
42
48
                                        my $got = ref($value) ? 'a ' . ref($value) . ' reference' : 'a plain scalar';
1599
42
55
                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a string reference, not $got");
1600                                }
1601
74
74
53
65
                                $value = ${$value};
1602                        }
1603
35102
33087
                        if($rules->{'transform'} && defined($value)) {
1604
1024
938
                                if(ref($rules->{'transform'}) eq 'CODE') {
1605
1021
1021
643
1086
                                        $value = &{$rules->{'transform'}}($value);
1606                                } else {
1607
3
4
                                        _error($logger, "$rule_description: transforms must be a code ref");
1608                                }
1609                        }
1610
35099
68778
                        if(exists($rules->{optional})) {
1611
5626
5034
                                if(ref($rules->{'optional'}) eq 'CODE') {
1612                                        # For stringref the coderef receives the original SCALAR ref (what
1613                                        # the caller supplied), not the internally-dereferenced plain string.
1614                                        # For all other types the post-transform value is passed, as before.
1615
991
836
                                        my $opt_arg = $is_stringref_type ? $pre_deref_value : $value;
1616
991
991
657
1025
                                        $is_optional = &{$rules->{optional}}($opt_arg, $args);
1617                                } else {
1618
4635
3811
                                        $is_optional = $rules->{'optional'};
1619                                }
1620                        } elsif($rules->{nullable}) {
1621
1195
933
                                $is_optional = $rules->{'nullable'};
1622                        } elsif(defined($rules->{'type'}) && !ref($rules->{'type'}) && lc($rules->{'type'}) eq 'void') {
1623
17
14
                                $is_optional = 1;
1624                        } elsif($rules->{'slurp'}) {
1625
4
4
                                $is_optional = 1;
1626                        }
1627                }
1628
1629                # Handle optional parameters
1630
35119
64126
                if((ref($rules) eq 'HASH') && $is_optional) {
1631
5856
3626
                        my $missing;
1632
5856
4679
                        if($are_positional_args == 1) {
1633                                # A slurp parameter is never missing: at worst it yields an empty arrayref.
1634
10
11
                                $missing = $rules->{'slurp'} ? 0 : !defined($args->[$rules->{position}]);
1635                        } else {
1636
5846
4173
                                $missing = !exists($args->{$lookup_key});
1637                        }
1638
5856
5040
                        if($missing) {
1639
580
478
                                if($are_positional_args == 1) {
1640
5
5
3
8
                                        if(scalar(@{$args}) < $rules->{'position'}) {
1641                                                # arg array is too short, so it must be missing
1642
1
2
                                                _error($logger, "$rule_description: Required parameter $param_label is missing");
1643
0
0
                                                _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
1644                                        }
1645                                }
1646
579
552
                                if(exists($rules->{'default'})) {
1647                                        # Populate missing optional parameters with the specified output values
1648
92
232
                                        $validated_args{$key} //= $rules->{'default'};
1649
92
91
                                        next;   # default wins; do not fall through to the schema branch
1650                                }
1651
1652
487
413
                                if($rules->{'schema'}) {
1653
70
77
                                        $value = _apply_nested_defaults({}, $rules->{'schema'});
1654
70
70
54
95
                                        next unless scalar(%{$value});
1655                                        # The nested schema has a default value
1656                                } else {
1657
417
402
                                        next;   # optional and missing
1658                                }
1659                        }
1660                } elsif((ref($args) eq 'HASH') && !exists($args->{$lookup_key})) {
1661                        # The parameter is required
1662                        # Use exists rather than defined, so that an undefined value can be passed, but the key is there
1663
1044
1099
                        _error($logger, "$rule_description: Required parameter $param_label is missing");
1664                }
1665
1666                # Normalise union type shorthand: { type => ['string', 'integer'], ... }
1667                # or pipe-separated string { type => 'string|integer' }
1668                # into the array-of-rules form that the ARRAY handler below already supports.
1669                # Each candidate type inherits all other constraints from the parent rule
1670                # (min, max, matches, optional, etc.) so they are each fully validated.
1671                # Must run after optional/transform handling above but before rule dispatch below.
1672
33497
80378
                if(ref($rules) eq 'HASH' && !ref($rules->{'type'}) && defined($rules->{'type'}) && index($rules->{'type'}, '|') >= 0) {
1673
80
256
                        $rules = { %$rules, type => [ split /\s*\|\s*/, $rules->{'type'} ] };
1674                }
1675
33497
42088
                if(ref($rules) eq 'HASH' && ref($rules->{'type'}) eq 'ARRAY') {
1676
224
224
133
243
                        my %base = %{$rules};
1677
224
224
167
254
                        my @type_list = @{delete $base{'type'}};
1678
224
217
                        if(!@type_list) {
1679
2
3
                                _error($logger, "$rule_description: Parameter $param_label: union type list must not be empty");
1680                        }
1681                        # Expand into one full rule hash per candidate type
1682
222
443
171
512
                        $rules = [ map { { %base, type => $_ } } @type_list ];
1683                }
1684
1685                # Validate based on rules
1686
33495
25493
                if(ref($rules) eq 'HASH') {
1687
33253
49818
                        if(defined(my $min = $rules->{'min'} // $rules->{'minimum'}) && defined(my $max = $rules->{'max'})) {
1688
2498
2245
                                if($min > $max) {
1689
943
991
                                        _error($logger, "validate_strict($key): min must be <= max ($min > $max)");
1690                                }
1691                        }
1692
1693                        # memberof and its synonym enum cannot be combined with min or max
1694
32310
49362
                        if($rules->{'memberof'} || $rules->{'enum'} || $rules->{'values'}) {
1695
4346
6438
                                if(defined(my $min = $rules->{'min'} // $rules->{'minimum'})) {
1696
944
1014
                                        _error($logger, "validate_strict($key): min ($min) makes no sense with memberof/enum/values");
1697                                }
1698
3402
3482
                                if(defined(my $max = $rules->{'max'})) {
1699
5
9
                                        _error($logger, "validate_strict($key): max ($max) makes no sense with memberof/enum/values");
1700                                }
1701                        }
1702
1703
31361
69683
30136
60038
                        foreach my $rule_name ('type', grep { $_ ne 'type' } keys %$rules) {
1704
44717
31395
                                my $rule_value = $rules->{$rule_name};
1705
1706
44717
40133
                                if((ref($rule_value) eq 'CODE')
1707                                        && ($rule_name ne 'validate')
1708                                        && ($rule_name ne 'callback')
1709                                        && ($rule_name ne 'validator')
1710                                        && ($rule_name ne 'transform')  # already applied before this loop
1711                                        && ($rule_name ne 'optional')) {        # already applied before this loop
1712
16
16
14
19
                                        $rule_value = &{$rule_value}($value, $args);
1713                                }
1714
1715                                # Better OOP, the routine has been given an object rather than a scalar
1716
44717
37204
                                if(ref($rule_value) && Scalar::Util::blessed($rule_value) && $rule_value->can('as_string')) {
1717
2
2
                                        $rule_value = $rule_value->as_string();
1718                                }
1719
1720
44717
76510
                                if($rule_name eq 'type') {
1721
31361
21145
                                        my $type = lc($rule_value);
1722
1723
31361
107437
                                        if(($type eq 'string') || ($type eq 'str')) {
1724
5596
4193
                                                if(ref($value)) {
1725
1176
1229
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a string");
1726                                                }
1727
4420
4422
                                                unless((ref($value) eq '') || (defined($value) && length($value))) {    # Allow undef for optional strings
1728
0
0
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a string");
1729                                                }
1730                                        } elsif(($type eq 'integer') || ($type eq 'int')) {
1731
5097
4063
                                                if(!defined($value)) {
1732
185
168
                                                        next;   # Skip if number is undefined
1733                                                }
1734
4912
8915
                                                if(!Scalar::Util::looks_like_number($value) || ($value - $value) != 0 || $value != int($value)) {
1735
3281
4417
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be an integer");
1736                                                }
1737
1631
1420
                                                $value = int($value); # Coerce to integer
1738                                        } elsif(($type eq 'number') || ($type eq 'float') || ($type eq 'num') || ($type eq 'double')) {
1739
6439
5300
                                                if(!defined($value)) {
1740
246
214
                                                        next;   # Skip if number is undefined
1741                                                }
1742
6193
7130
                                                if(!Scalar::Util::looks_like_number($value)) {
1743
3909
4082
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a number");
1744                                                }
1745                                                # $value = eval $value; # Coerce to number (be careful with eval)
1746
2284
2713
                                                $value = 0 + $value;    # Numeric coercion
1747                                        } elsif($type eq 'arrayref') {
1748
3235
2771
                                                if(!defined($value)) {
1749
119
114
                                                        next;   # Skip if arrayref is undefined
1750                                                }
1751
3116
2898
                                                if(ref($value) ne 'ARRAY') {
1752
2698
3156
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an arrayref, not " . ref($value));
1753                                                }
1754                                        } elsif($type eq 'hashref') {
1755
1616
1401
                                                if(!defined($value)) {
1756
61
62
                                                        next;   # Skip if hashref is undefined
1757                                                }
1758
1555
1585
                                                if(ref($value) ne 'HASH') {
1759
1343
1664
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an hashref");
1760                                                }
1761                                        } elsif($type eq 'scalar') {
1762
1860
1663
                                                if(!defined($value)) {
1763
70
66
                                                        next;   # Skip if undefined
1764                                                }
1765
1790
1749
                                                if(ref($value)) {
1766
502
630
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a scalar, not a " . ref($value) . ' reference');
1767                                                }
1768                                        } elsif($type eq 'scalarref') {
1769
71
66
                                                if(!defined($value)) {
1770
2
3
                                                        next;   # Skip if undefined
1771                                                }
1772
69
76
                                                if(ref($value) ne 'SCALAR') {
1773
41
45
                                                        my $got = ref($value) ? 'a ' . ref($value) . ' reference' : 'a plain scalar';
1774
41
57
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a scalar reference, not $got");
1775                                                }
1776                                        } elsif($type eq 'stringref') {
1777
76
85
                                                if(!defined($value)) {
1778
2
4
                                                        next;   # Skip if undefined
1779                                                }
1780                                                # The early-deref block validated the SCALAR ref and set $value to the
1781                                                # plain string.  If transform subsequently returned a reference, reject it.
1782
74
89
                                                if(ref($value)) {
1783
2
5
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label stringref transform must return a plain string, not a " . ref($value) . ' reference');
1784                                                }
1785                                        } elsif($type eq 'void') {
1786
16
16
13
18
                                                if(scalar(keys %{$schema}) != 1) {
1787
2
4
                                                        _error($logger, "$rule_description: type 'void' requires exactly one parameter in the schema");
1788                                                }
1789
14
17
                                                if(defined($value)) {
1790
11
14
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be undef (void type accepts no value)");
1791                                                }
1792                                        } elsif(($type eq 'boolean') || ($type eq 'bool')) {
1793
3557
3018
                                                if(!defined($value)) {
1794
136
120
                                                        next;   # Skip if bool is undefined
1795                                                }
1796
3421
5650
                                                if(defined(my $b = $Readonly::Values::Boolean::booleans{$value})) {
1797
600
2197
                                                        $value = $b;
1798                                                } else {
1799
2821
9621
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be a boolean");
1800                                                }
1801                                        } elsif($type eq 'coderef') {
1802
1830
1480
                                                if(!defined($value)) {
1803
71
66
                                                        next;   # Skip if code is undefined
1804                                                }
1805
1759
1619
                                                if(ref($value) ne 'CODE') {
1806
1685
2046
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a coderef, not a ref to " . ref($value));
1807                                                }
1808                                        } elsif($type eq 'regex') {
1809
3
4
                                                if(!defined($value)) {
1810
1
2
                                                        next;
1811                                                }
1812
2
3
                                                if(ref($value) ne 'Regexp') {
1813
1
3
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a compiled regex (qr//)" .
1814                                                                (ref($value) ? ", not a " . ref($value) . " reference" : ", not a plain scalar"));
1815                                                }
1816                                        } elsif($type eq 'handle') {
1817
3
4
                                                if(!defined($value)) {
1818
1
1
                                                        next;
1819                                                }
1820
2
2
                                                my $is_handle = 0;
1821
2
7
                                                if(ref($value) eq 'GLOB' && defined(fileno($value))) {
1822
1
1
                                                        $is_handle = 1;
1823                                                } elsif(Scalar::Util::blessed($value) && $value->isa('IO::Handle')) {
1824
0
0
                                                        $is_handle = 1;
1825                                                } else {
1826
1
1
1
3
                                                        $is_handle = defined(eval { fileno($value) });
1827                                                }
1828
2
4
                                                unless($is_handle) {
1829
1
2
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a file handle");
1830                                                }
1831                                        } elsif($type eq 'arraylike') {
1832
2
3
                                                if(!defined($value)) {
1833
0
0
                                                        next;
1834                                                }
1835
2
20
                                                unless(ref($value) eq 'ARRAY' || (Scalar::Util::blessed($value) && overload::Method($value, '@{}'))) {
1836
1
2
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an array reference or array-like object");
1837                                                }
1838                                        } elsif($type eq 'hashlike') {
1839
2
2
                                                if(!defined($value)) {
1840
0
0
                                                        next;
1841                                                }
1842
2
5
                                                unless(ref($value) eq 'HASH' || (Scalar::Util::blessed($value) && overload::Method($value, '%{}'))) {
1843
1
2
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a hash reference or hash-like object");
1844                                                }
1845                                        } elsif($type eq 'codelike') {
1846
2
4
                                                if(!defined($value)) {
1847
0
0
                                                        next;
1848                                                }
1849
2
4
                                                unless(ref($value) eq 'CODE' || (Scalar::Util::blessed($value) && overload::Method($value, '&{}'))) {
1850
1
3
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a code reference or code-like object");
1851                                                }
1852                                        } elsif($type eq 'invocant') {
1853
8
9
                                                if(!defined($value)) {
1854
0
0
                                                        next;
1855                                                }
1856
8
31
                                                unless(Scalar::Util::blessed($value) || (!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/)) {
1857
1
3
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a blessed object or a class name");
1858                                                }
1859                                        } elsif($type eq 'object') {
1860
1882
1516
                                                if(!defined($value)) {
1861
71
65
                                                        next;   # Skip if object is undefined
1862                                                }
1863
1811
2027
                                                if(!Scalar::Util::blessed($value)) {
1864
1686
1706
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an object");
1865                                                }
1866                                        } elsif(my $custom_type = $custom_types->{$type}) {
1867
63
78
                                                if($custom_type->{'transform'}) {
1868                                                        # The custom type has a transform embedded within it
1869
9
10
                                                        if(ref($custom_type->{'transform'}) eq 'CODE') {
1870
8
8
7
10
                                                                $value = &{$custom_type->{'transform'}}($value);
1871                                                        } else {
1872
1
2
                                                                _error($logger, "$rule_description: transforms must be a code ref");
1873                                                        }
1874                                                }
1875
62
405
                                                validate_strict({ input => { $key => $value }, schema => { $key => $custom_type }, custom_types => $custom_types });
1876                                        } else {
1877
3
8
                                                _error($logger, "$rule_description: Unknown type '$type'");
1878                                        }
1879                                } elsif(($rule_name eq 'min') || ($rule_name eq 'minimum')) {
1880
3031
2823
                                        if(!defined($rules->{'type'})) {
1881
0
0
                                                _error($logger, "$rule_description: Don't know type of $param_label to determine its minimum value $rule_value");
1882                                        }
1883
3031
2179
                                        my $type = lc($rules->{'type'});
1884
3031
4934
                                        if(exists($custom_types->{$type}->{'min'}) || exists($custom_types->{$type}->{minimum})) {
1885
3
3
                                                $rule_value = $custom_types->{$type}->{'min'} // $custom_types->{$type}->{minimum};
1886
3
3
                                                $type = $custom_types->{$type}->{'type'};
1887                                        }
1888
3031
7759
                                        if(($type eq 'string') || ($type eq 'str') || ($type eq 'stringref')) {
1889
951
1620
                                                if($rule_value < 0) {
1890
117
122
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label has meaningless minimum value that is less than zero");
1891                                                }
1892
834
2314
                                                if(!defined($value)) {
1893
39
74
                                                        if($rule_value > 0 && !$is_optional) {
1894
19
46
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must be at least $rule_value character" . ($rule_value == 1 ? '' : 's'));
1895
0
0
                                                                $invalid_args{$key} = 1;
1896                                                        }
1897
20
60
                                                        next;
1898                                                }
1899
795
699
                                                if(defined(my $len = _number_of_characters($value))) {
1900
795
1067
                                                        if($len < $rule_value) {
1901
80
169
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label too short, ($len characters), must be at least $rule_value characters");
1902
0
0
                                                                $invalid_args{$key} = 1;
1903                                                        }
1904                                                } else {
1905
0
0
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label can't be decoded");
1906
0
0
                                                        $invalid_args{$key} = 1;
1907                                                }
1908                                        } elsif($type eq 'arrayref') {
1909
182
187
                                                if(!defined($value)) {
1910
27
71
                                                        if($rule_value > 0 && !$is_optional) {
1911
13
30
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must have at least $rule_value member" . ($rule_value > 1 ? 's' : ''));
1912
0
0
                                                                $invalid_args{$key} = 1;
1913                                                        }
1914
14
76
                                                        next;
1915                                                }
1916
155
155
113
290
                                                if(scalar(@{$value}) < $rule_value) {
1917
27
72
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label must have at least $rule_value member" . (($rule_value > 1) ? 's' : ''));
1918
0
0
                                                $invalid_args{$key} = 1;
1919                                        }
1920                                        } elsif($type eq 'hashref') {
1921
55
69
                                                if(!defined($value)) {
1922
14
36
                                                        if($rule_value > 0 && !$is_optional) {
1923
7
14
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must contain at least $rule_value keys");
1924
0
0
                                                                $invalid_args{$key} = 1;
1925                                                        }
1926
7
37
                                                        next;
1927                                                }
1928
41
41
42
97
                                                if(scalar(keys(%{$value})) < $rule_value) {
1929
15
32
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must contain at least $rule_value keys");
1930
0
0
                                                        $invalid_args{$key} = 1;
1931                                                }
1932                                        } elsif(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) {
1933
619
502
                                                if(!defined($value)) {
1934
53
139
                                                        if($rule_value > 0 && !$is_optional) {
1935
25
42
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must be at least $rule_value");
1936
0
0
                                                                $invalid_args{$key} = 1;
1937                                                        }
1938
28
150
                                                        next;
1939                                                }
1940
566
557
                                                if(Scalar::Util::looks_like_number($value)) {
1941
566
1073
                                                        if($value < $rule_value) {
1942
126
387
                                                                if($rules->{'error_msg'}) {
1943
15
21
                                                                        _error($logger, $rules->{'error_msg'});
1944                                                                } elsif(($type eq 'integer') && ($value == 0)) {
1945
15
25
                                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be a positive number");
1946                                                                } elsif(($type eq 'integer') && ($value == 1)) {
1947
2
5
                                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be a positive, non-zero number");
1948                                                                } else {
1949
94
188
                                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be at least $rule_value");
1950                                                                }
1951
0
0
                                                                $invalid_args{$key} = 1;
1952
0
0
                                                                next;
1953                                                        }
1954                                                } else {
1955
0
0
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be a number");
1956
0
0
                                                        _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
1957                                                }
1958                                        } else {
1959
1224
2133
                                                _error($logger, "$rule_description: Parameter $param_label of type '$type' has meaningless min value $rule_value");
1960                                        }
1961                                } elsif($rule_name eq 'max') {
1962
1219
1260
                                        if(!defined($rules->{'type'})) {
1963
0
0
                                                _error($logger, "$rule_description: Don't know type of $param_label to determine its maximum value $rule_value");
1964                                        }
1965
1219
887
                                        my $type = lc($rules->{'type'});
1966
1219
1380
                                        if(exists($custom_types->{$type}->{'max'})) {
1967
4
4
                                                $rule_value = $custom_types->{$type}->{'max'};
1968
4
4
                                                $type = $custom_types->{$type}->{'type'};
1969                                        }
1970
1219
3268
                                        if(($type eq 'string') || ($type eq 'str') || ($type eq 'stringref')) {
1971
403
365
                                                if(!defined($value)) {
1972
13
13
                                                        next;   # Skip if string is undefined
1973                                                }
1974
390
395
                                                if(defined(my $len = _number_of_characters($value))) {
1975
390
404
                                                        if($len > $rule_value) {
1976
141
216
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label too long, ($len characters), must be no longer than $rule_value");
1977
0
0
                                                                $invalid_args{$key} = 1;
1978                                                        }
1979                                                } else {
1980
0
0
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label can't be decoded");
1981
0
0
                                                        $invalid_args{$key} = 1;
1982                                                }
1983                                        } elsif($type eq 'arrayref') {
1984
47
45
                                                if(!defined($value)) {
1985
8
5
                                                        next;   # Skip if string is undefined
1986                                                }
1987
39
39
23
58
                                                if(scalar(@{$value}) > $rule_value) {
1988
19
30
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must contain no more than $rule_value items");
1989
0
0
                                                        $invalid_args{$key} = 1;
1990                                                }
1991                                        } elsif($type eq 'hashref') {
1992
27
25
                                                if(!defined($value)) {
1993
3
3
                                                        next;   # Skip if hash is undefined
1994                                                }
1995
24
24
16
42
                                                if(scalar(keys(%{$value})) > $rule_value) {
1996
8
17
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label must contain no more than $rule_value keys");
1997
0
0
                                                        $invalid_args{$key} = 1;
1998                                                }
1999                                        } elsif(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) {
2000
252
223
                                                if(!defined($value)) {
2001
17
15
                                                        next;   # Skip if hash is undefined
2002                                                }
2003
235
260
                                                if(Scalar::Util::looks_like_number($value)) {
2004
235
253
                                                        if($value > $rule_value) {
2005
122
279
                                                                if($rules->{'error_msg'}) {
2006
0
0
                                                                        _error($logger, $rules->{'error_msg'});
2007                                                                } elsif(($type eq 'integer') && ($value == 0)) {
2008
0
0
                                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be a negative number");
2009                                                                } elsif(($type eq 'integer') && ($value == -1)) {
2010
0
0
                                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be a negative, non-zero number");
2011                                                                } else {
2012
122
168
                                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be no more than $rule_value");
2013                                                                }
2014
0
0
                                                                $invalid_args{$key} = 1;
2015
0
0
                                                                next;
2016                                                        }
2017                                                } else {
2018
0
0
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be a number");
2019
0
0
                                                        _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
2020                                                }
2021                                        } else {
2022
490
544
                                                _error($logger, "$rule_description: Parameter $param_label of type '$type' has meaningless max value $rule_value");
2023                                        }
2024                                } elsif(($rule_name eq 'matches') || ($rule_name eq 'regex')) {
2025
1006
891
                                        if(!defined($value)) {
2026
106
97
                                                next;   # Skip if string is undefined
2027                                        }
2028
900
625
                                        eval {
2029
900
2574
                                                my $re = (ref($rule_value) eq 'Regexp') ? $rule_value : qr/\Q$rule_value\E/;
2030
900
2647
                                                if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
2031                                                        # all{} short-circuits on first failure and allocates no temp array
2032
37
39
37
64
87
61
                                                        unless(all { $_ =~ $re } @{$value}) {
2033
14
14
38
36
                                                                _rule_error($logger, $rules, "$rule_description: All members of parameter $param_label [", join(', ', @{$value}), "] must match pattern '$rule_value'");
2034                                                        }
2035                                                } elsif($value !~ $re) {
2036
672
1198
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must match pattern '$re'");
2037                                                }
2038
214
194
                                                1;
2039                                        };
2040
900
73838
                                        if($@) {
2041
686
1108
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label regex '$rule_value' error: $@");
2042
0
0
                                                $invalid_args{$key} = 1;
2043                                        }
2044                                } elsif($rule_name eq 'nomatch') {
2045
352
316
                                        if(!defined($value)) {
2046
36
34
                                                next;   # Skip if string is undefined
2047                                        }
2048                                        # Compile string patterns with \Q...\E so metacharacters are
2049                                        # treated as literals, matching the behaviour of 'matches'.
2050
316
513
                                        my $re = (ref($rule_value) eq 'Regexp') ? $rule_value : qr/\Q$rule_value\E/;
2051
316
226
                                        eval {
2052
316
793
                                                if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
2053                                                        # any{} short-circuits on first match and allocates no temp array
2054
13
29
13
20
41
23
                                                        if(any { $_ =~ $re } @{$value}) {
2055
2
2
10
8
                                                                _rule_error($logger, $rules, "$rule_description: No member of parameter $param_label [", join(', ', @{$value}), "] must match pattern '$rule_value'");
2056                                                        }
2057                                                } elsif($value =~ $re) {
2058
10
33
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must not match pattern '$rule_value'");
2059
0
0
                                                        $invalid_args{$key} = 1;
2060                                                }
2061
304
248
                                                1;
2062                                        };
2063
316
3400
                                        if($@) {
2064
12
32
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label regex '$rule_value' error: $@");
2065
0
0
                                                $invalid_args{$key} = 1;
2066                                        }
2067                                } elsif($rule_name eq 'bnf') {
2068
26
25
                                        if(!defined($value)) {
2069
3
4
                                                next;   # Skip if value is undefined
2070                                        }
2071
23
22
                                        if(ref($rule_value) ne 'ARRAY') {
2072
3
4
                                                _error($logger, "$rule_description: Parameter $param_label 'bnf' rule must be an arrayref of grammar lines");
2073                                        }
2074
20
206
                                        require Params::Validate::Strict::BNF;
2075
20
26
                                        my $matcher = Params::Validate::Strict::BNF::bnf_to_matcher($rule_value);
2076
16
18
                                        unless($matcher->($value)) {
2077
8
14
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) does not match the BNF grammar");
2078
0
0
                                                $invalid_args{$key} = 1;
2079                                        }
2080                                } elsif(($rule_name eq 'memberof') || ($rule_name eq 'enum') || ($rule_name eq 'values')) {
2081
1261
1112
                                        if(!defined($value)) {
2082
126
119
                                                next;   # Skip if string is undefined
2083                                        }
2084
1135
1011
                                        if(ref($rule_value) eq 'ARRAY') {
2085
843
1208
                                                unless(_value_in_list($value, $rule_value, $rules->{'type'} // '', $rules->{'case_sensitive'})) {
2086
632
632
724
1019
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be one of ", join(', ', @{$rule_value}));
2087
0
0
                                                        $invalid_args{$key} = 1;
2088                                                }
2089                                        } else {
2090
292
325
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label rule ($rule_value) must be an array reference");
2091                                        }
2092                                } elsif($rule_name eq 'notmemberof') {
2093
376
337
                                        if(!defined($value)) {
2094
36
33
                                                next;   # Skip if string is undefined
2095                                        }
2096
340
297
                                        if(ref($rule_value) eq 'ARRAY') {
2097
339
533
                                                if(_value_in_list($value, $rule_value, $rules->{'type'} // '', $rules->{'case_sensitive'})) {
2098
41
41
53
85
                                                        _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must not be one of ", join(', ', @{$rule_value}));
2099
0
0
                                                        $invalid_args{$key} = 1;
2100                                                }
2101                                        } else {
2102
1
2
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label rule ($rule_value) must be an array reference");
2103                                        }
2104                                } elsif($rule_name eq 'isa') {
2105
23
28
                                        if(!defined($value)) {
2106
0
0
                                                next;   # Skip if object not given
2107                                        }
2108
23
45
                                        if($rules->{'type'} eq 'object') {
2109
20
60
                                                if(!$value->isa($rule_value)) {
2110
6
25
                                                        _error($logger, "$rule_description: Parameter $param_label must be a '$rule_value' object got a " . (ref($value) ? ref($value) : $value) . ' object instead');
2111
0
0
                                                        $invalid_args{$key} = 1;
2112                                                }
2113                                        } else {
2114
3
6
                                                _error($logger, "$rule_description: Parameter $param_label has meaningless isa value $rule_value");
2115                                        }
2116                                } elsif($rule_name eq 'can') {
2117
43
39
                                        if(!defined($value)) {
2118
0
0
                                                next;   # Skip if object not given
2119                                        }
2120
43
75
                                        if(($rules->{'type'} eq 'object') || ($rules->{'type'} eq 'invocant')) {
2121
39
64
                                                if(ref($rule_value) eq 'ARRAY') {
2122                                                        # List of methods
2123
16
16
12
20
                                                        foreach my $method(@{$rule_value}) {
2124
31
67
                                                                if(!$value->can($method)) {
2125
7
14
                                                                        _error($logger, "$rule_description: Parameter $param_label must be an object that understands the $method method");
2126
0
0
                                                                        $invalid_args{$key} = 1;
2127                                                                }
2128                                                        }
2129                                                } elsif(!ref($rule_value)) {
2130
22
101
                                                        if(!$value->can($rule_value)) {
2131
10
45
                                                                _error($logger, "$rule_description: Parameter $param_label must be an object that understands the $rule_value method");
2132
0
0
                                                                $invalid_args{$key} = 1;
2133                                                        }
2134                                                } else {
2135
1
2
                                                        _error($logger, "$rule_description: 'can' rule for Parameter $param_label must be either a scalar or an arrayref");
2136                                                }
2137                                        } else {
2138
4
9
                                                _error($logger, "$rule_description: Parameter $param_label has meaningless can value '$rule_value' for parameter type $rules->{type}");
2139                                        }
2140                                } elsif($rule_name eq 'classcan') {
2141
6
6
                                        if(!defined($value)) {
2142
0
0
                                                next;
2143                                        }
2144
6
8
                                        if(ref($rule_value) && ref($rule_value) ne 'ARRAY') {
2145
1
1
                                                _error($logger, "$rule_description: 'classcan' rule for Parameter $param_label must be either a scalar or an arrayref");
2146                                        }
2147
5
16
                                        unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) {
2148
1
0
                                                $invalid_args{$key} = 1;
2149
1
2
                                                _error($logger, "$rule_description: Parameter $param_label must be a valid class name");
2150
0
0
                                                _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
2151                                        }
2152
4
2
3
2
                                        foreach my $method (ref($rule_value) ? @{$rule_value} : ($rule_value)) {
2153                                                # Always a method call, so an overridden can() is respected
2154
6
14
                                                unless($value->can($method)) {
2155
2
7
                                                        _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that understands the $method method");
2156
0
0
                                                        $invalid_args{$key} = 1;
2157                                                }
2158                                        }
2159                                } elsif($rule_name eq 'does') {
2160
3
2
                                        if(!defined($value)) {
2161
0
0
                                                next;   # Skip if object not given
2162                                        }
2163
3
4
                                        if($rules->{'type'} eq 'object') {
2164
2
13
                                                unless(Scalar::Util::blessed($value) && $value->DOES($rule_value)) {
2165
1
2
                                                        _error($logger, "$rule_description: Parameter $param_label must be an object that does '$rule_value'");
2166
0
0
                                                        $invalid_args{$key} = 1;
2167                                                }
2168                                        } else {
2169
1
3
                                                _error($logger, "$rule_description: Parameter $param_label has meaningless does value '$rule_value' for parameter type $rules->{type}");
2170                                        }
2171                                } elsif($rule_name eq 'classisa') {
2172
3
3
                                        if(!defined($value)) {
2173
1
1
                                                next;
2174                                        }
2175
2
20
                                        unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ && $value->isa($rule_value)) {
2176
1
2
                                                _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that isa '$rule_value'");
2177
0
0
                                                $invalid_args{$key} = 1;
2178                                        }
2179                                } elsif($rule_name eq 'subclass') {
2180
2
2
                                        if(!defined($value)) {
2181
0
0
                                                next;
2182                                        }
2183
2
14
                                        unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
2184                                                && $value ne $rule_value && $value->isa($rule_value)) {
2185
1
2
                                                _error($logger, "$rule_description: Parameter $param_label ($value) must be a strict subclass of '$rule_value'");
2186
0
0
                                                $invalid_args{$key} = 1;
2187                                        }
2188                                } elsif($rule_name eq 'classdoes') {
2189
2
2
                                        if(!defined($value)) {
2190
0
0
                                                next;
2191                                        }
2192
2
43
                                        unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ && $value->DOES($rule_value)) {
2193
1
4
                                                _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that does '$rule_value'");
2194
0
0
                                                $invalid_args{$key} = 1;
2195                                        }
2196                                } elsif($rule_name eq 'driver') {
2197
3
4
                                        if(!defined($value)) {
2198
0
0
                                                next;
2199                                        }
2200
3
12
                                        unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) {
2201
1
2
                                                $invalid_args{$key} = 1;
2202
1
2
                                                _error($logger, "$rule_description: Parameter $param_label must be a valid class name");
2203
0
0
                                                _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
2204                                        }
2205
2
5
                                        (my $file = $value) =~ s{::}{/}g;
2206
2
2
                                        $file .= '.pm';
2207
2
2
2
4
                                        eval { require $file };
2208
2
3
                                        if($@) {
2209
0
0
                                                $invalid_args{$key} = 1;
2210
0
0
                                                _error($logger, "$rule_description: Parameter $param_label ($value) could not be loaded: $@");
2211
0
0
                                                _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
2212                                        }
2213
2
7
                                        unless($value->isa($rule_value)) {
2214
1
3
                                                _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that isa '$rule_value'");
2215
0
0
                                                $invalid_args{$key} = 1;
2216                                        }
2217                                } elsif($rule_name eq 'element_type') {
2218
46
71
                                        if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
2219
43
33
                                                my $type = $rule_value;
2220
43
37
                                                my $custom_type = $custom_types->{$rule_value};
2221
43
46
                                                if($custom_type && $custom_type->{'type'}) {
2222
4
4
                                                        $type = $custom_type->{'type'};
2223                                                }
2224
43
43
29
47
                                                foreach my $member(@{$value}) {
2225
104
88
                                                        if($custom_type && $custom_type->{'transform'}) {
2226                                                                # The custom type has a transform embedded within it
2227
5
8
                                                                if(ref($custom_type->{'transform'}) eq 'CODE') {
2228
4
4
4
4
                                                                        $member = &{$custom_type->{'transform'}}($member);
2229                                                                } else {
2230
1
2
                                                                        _error($logger, "$rule_description: transforms must be a code ref");
2231                                                                }
2232                                                        }
2233
103
147
                                                        if(($type eq 'string') || ($type eq 'Str')) {
2234
44
47
                                                                if(ref($member)) {
2235
2
5
                                                                        _rule_error($logger, $rules, "$param_label can only contain strings");
2236
0
0
                                                                        $invalid_args{$key} = 1;
2237                                                                }
2238                                                        } elsif($type eq 'integer') {
2239
44
86
                                                                if(ref($member) || ($member =~ /\D/)) {
2240
6
15
                                                                        _rule_error($logger, $rules, "$param_label can only contain integers (found $member)");
2241
0
0
                                                                        $invalid_args{$key} = 1;
2242                                                                }
2243                                                        } elsif(($type eq 'number') || ($rule_value eq 'float')) {
2244
14
45
                                                                if(ref($member) || ($member !~ /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/)) {
2245
2
4
                                                                        _rule_error($logger, $rules, "$param_label can only contain numbers (found $member)");
2246
0
0
                                                                        $invalid_args{$key} = 1;
2247                                                                }
2248                                                        } elsif($type eq 'object') {
2249
0
0
                                                                if(!Scalar::Util::blessed($member)) {
2250
0
0
                                                                        _rule_error($logger, $rules, "$param_label can only contain objects (found $member)");
2251
0
0
                                                                        $invalid_args{$key} = 1;
2252                                                                }
2253                                                        } else {
2254
1
1
                                                                _error($logger, "BUG: Add $type to element_type list");
2255                                                        }
2256                                                }
2257                                        } else {
2258
3
5
                                                _error($logger, "$rule_description: Parameter $param_label has meaningless element_type value $rule_value");
2259                                        }
2260                                } elsif($rule_name eq 'element_isa') {
2261
5
7
                                        if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
2262
4
4
3
3
                                                foreach my $member (@{$value}) {
2263
5
16
                                                        unless(Scalar::Util::blessed($member) && $member->isa($rule_value)) {
2264
2
9
                                                                $invalid_args{$key} = 1;
2265
2
3
                                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label can only contain '$rule_value' objects");
2266
0
0
                                                                _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
2267                                                        }
2268                                                }
2269                                        } else {
2270
1
1
                                                _error($logger, "$rule_description: Parameter $param_label has meaningless element_isa value $rule_value");
2271                                        }
2272                                } elsif($rule_name eq 'needs') {
2273                                        # Desugared into dependency relationships before validation finishes
2274                                } elsif($rule_name eq 'optional') {
2275                                        # Already handled at the beginning of the loop
2276                                } elsif($rule_name eq 'nullable') {
2277                                        # Already handled at the beginning of the loop (same as optional)
2278                                } elsif($rule_name eq 'default') {
2279                                        # Handled earlier
2280                                } elsif($rule_name eq 'error_msg') {
2281                                        # Handled inline
2282                                } elsif($rule_name eq 'transform') {
2283                                        # Handled before the loop
2284                                } elsif($rule_name eq 'case_sensitive') {
2285                                        # Handled inline
2286                                } elsif($rule_name eq 'description') {
2287                                        # A la, Data::Processor
2288                                } elsif($rule_name =~ /^_/) {
2289                                        # Ignore internal/metadata fields from schema extraction
2290                                } elsif($rule_name eq 'semantic') {
2291
36
48
                                        if($rule_value eq 'unix_timestamp') {
2292
9
19
                                                if($value < 0 || $value > 2147483647) {
2293
4
12
                                                        _error($logger, "Invalid Unix timestamp: $value");
2294                                                }
2295                                        } elsif($rule_value eq 'identifier') {
2296
3
9
                                                if(defined($value) && $value !~ /\A[A-Za-z_]\w*\z/) {
2297
2
3
                                                        _error($logger, "Invalid Perl identifier: $value");
2298                                                }
2299                                        } elsif($rule_value eq 'class_name') {
2300
3
11
                                                if(defined($value) && $value !~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) {
2301
1
3
                                                        _error($logger, "Invalid Perl class name: $value");
2302                                                }
2303                                        } elsif($rule_value eq 'filename') {
2304
19
13
                                                if(defined($value)) {
2305                                                        # A single path component, at most 255 bytes when encoded as UTF-8
2306
18
13
                                                        my $bytes = $value;
2307
18
21
                                                        utf8::encode($bytes);
2308
18
41
                                                        if(($value eq '') || ($value eq '.') || ($value eq '..')
2309                                                           || ($value =~ m{[/\0]}) || (length($bytes) > 255)) {
2310
10
12
                                                                _error($logger, "Invalid filename: $value");
2311                                                        }
2312                                                }
2313                                        } else {
2314
2
5
                                                _warn($logger, "semantic type $rule_value is not yet supported");
2315                                        }
2316                                } elsif($rule_name eq 'schema') {
2317                                        # Nested schema Run the given schema against each element of the array
2318
90
179
                                        if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
2319
18
22
                                                if(ref($value) eq 'ARRAY') {
2320
18
18
14
19
                                                        foreach my $member(@{$value}) {
2321                                                                # Distinguish two schema forms:
2322                                                                # (a) Rule hash   - has a top-level 'type' key, e.g. { type=>'string', matches=>qr/.../ }
2323                                                                #     => validate each element against that rule directly.
2324                                                                # (b) Field-schema hash - keys are field names whose values are rule hashes,
2325                                                                #     e.g. { name=>{type=>'string'}, age=>{type=>'integer'} }
2326                                                                #     => validate each hashref element against the field schema directly.
2327
29
52
                                                                my $is_field_schema = (ref($rule_value) eq 'HASH') && !exists($rule_value->{'type'});
2328
29
31
                                                                my %inner = (custom_types => $custom_types);
2329
29
24
                                                                if($is_field_schema) {
2330
7
7
                                                                        $inner{input}  = $member;
2331
7
5
                                                                        $inner{schema} = $rule_value;
2332                                                                } else {
2333
22
23
                                                                        $inner{input}  = { $key => $member };
2334
22
24
                                                                        $inner{schema} = { $key => $rule_value };
2335                                                                }
2336
29
69
                                                                if(!validate_strict(\%inner)) {
2337
0
0
                                                                        $invalid_args{$key} = 1;
2338                                                                }
2339                                                        }
2340                                                } elsif(defined($value)) {      # Allow undef for optional values
2341
0
0
                                                        _error($logger, "$rule_description: nested schema: Parameter '$value' must be an arrayref");
2342                                                }
2343                                        } elsif($rules->{'type'} eq 'hashref') {
2344
71
63
                                                if(ref($rule_value) eq 'HASH') {
2345                                                        # Apply nested defaults before validation
2346
71
73
                                                        my $nested_with_defaults = _apply_nested_defaults($value, $rule_value);
2347
71
71
42
80
                                                        if(scalar keys(%{$nested_with_defaults})) {
2348
69
403
                                                                if(my $new_args = validate_strict({ input => $nested_with_defaults, schema => $rule_value, custom_types => $custom_types })) {
2349
45
73
                                                                        $value = $new_args;
2350                                                                } else {
2351
0
0
                                                                        $invalid_args{$key} = 1;
2352                                                                }
2353                                                        }
2354                                                } else {
2355
0
0
                                                        _error($logger, "$rule_description: nested schema: Parameter '$value' must be an hashref");
2356                                                }
2357                                        } else {
2358
1
3
                                                _error($logger, "$rule_description: Parameter $param_label: 'schema' only supports arrayref and hashref, not $rules->{type}");
2359                                        }
2360                                } elsif(($rule_name eq 'validate') || ($rule_name eq 'validator')) {
2361
15
24
                                        if(ref($rule_value) eq 'CODE') {
2362
13
13
10
18
                                                if(my $error = &{$rule_value}($args)) {
2363
5
20
                                                        _error($logger, "$rule_description: $param_label not valid: $error");
2364
0
0
                                                        $invalid_args{$key} = 1;
2365                                                }
2366                                        } else {
2367                                                # _error($logger, "$rule_description: Parameter $param_label: 'validate' only supports coderef, not $value");
2368
2
4
                                                _error($logger, "$rule_description: Parameter $param_label: 'validate' only supports coderef, not " . ref($rule_value) // $rule_value);
2369                                        }
2370                                } elsif ($rule_name eq 'callback') {
2371                                        # Custom validation code
2372
755
774
                                        unless (defined &$rule_value) {
2373
1
2
                                                _error($logger, "$rule_description: callback for $param_label must be a code reference");
2374                                        }
2375
754
865
                                        my $res = $rule_value->($value, $args, $schema, $key);
2376
752
1217
                                        unless ($res) {
2377
356
471
                                                _rule_error($logger, $rules, "$rule_description: Parameter $param_label failed custom validation");
2378
0
0
                                                $invalid_args{$key} = 1;
2379                                        }
2380                                } elsif($rule_name eq 'position') {
2381
38
40
                                        if($rule_value < 0) {
2382                                                # A negative number always contains a non-digit ('-'), so the
2383                                                # /\D/ check below (and the positional detection) catch it first.
2384
0
0
                                                _unreachable($logger);
2385                                        }
2386
38
70
                                        if($rule_value =~ /\D/) {
2387
1
3
                                                _error($logger, "$rule_description: Parameter $param_label: 'position' must be a positive integer");
2388                                        }
2389                                } elsif($rule_name eq 'slurp') {
2390
3
9
                                        if($rule_value && $are_positional_args != 1) {
2391
0
0
                                                _error($logger, "$rule_description: Parameter $param_label: 'slurp' is only valid in positional-argument schemas (all parameters need a 'position')");
2392                                        }
2393                                        # Pre-processed: value was already collected as arrayref of remaining positional args
2394                                } elsif($rule_name eq 'aliases') {
2395                                        # Pre-processed: alternative input-key names resolved during value fetch
2396                                } else {
2397
328
368
                                        _error($logger, "$rule_description: Unknown rule '$rule_name'");
2398                                }
2399                        }
2400                } elsif(ref($rules) eq 'ARRAY') {
2401
240
240
158
194
                        if(scalar(@{$rules})) {
2402                                # An argument can be one of several different types.
2403                                # This path handles both explicit array-of-rules schemas and the
2404                                # normalised form of union type shorthand (type => ['a', 'b', ...]).
2405
238
146
                                my $rc = 0;
2406
238
172
                                my @types;
2407
238
238
147
194
                                foreach my $rule(@{$rules}) {
2408
326
320
                                        if(ref($rule) ne 'HASH') {
2409
1
2
                                                _error($logger, "$rule_description: Parameter $param_label rules must be a hash reference");
2410                                        }
2411
325
330
                                        if(!defined($rule->{'type'})) {
2412
0
0
                                                _error($logger, "$rule_description: Parameter $param_label is missing a type in an alternative");
2413                                        }
2414
325
256
                                        push @types, $rule->{'type'};
2415
325
191
                                        my $result;
2416
325
223
                                        eval {
2417
325
760
                                                $result = validate_strict({ input => { $key => $value }, schema => { $key => $rule }, logger => undef, custom_types => $custom_types });
2418                                        };
2419
325
21517
                                        if(!$@) {
2420                                                # Capture coercion performed by the successful sub-validation
2421                                                # (e.g. integer/number coercion) so the outer scope sees it.
2422
204
203
                                                $value = $result->{$key} if(defined($result));
2423
204
132
                                                $rc = 1;
2424
204
173
                                                last;
2425                                        }
2426                                }
2427
237
257
                                if(!$rc) {
2428
33
74
                                        _error($logger, "$rule_description: Parameter $param_label must be one of " . join(', ', @types));
2429
0
0
                                        $invalid_args{$key} = 1;
2430                                }
2431                        } else {
2432
2
4
                                _error($logger, "$rule_description: Parameter $param_label schema is empty arrayref");
2433                        }
2434                } elsif(ref($rules)) {
2435
2
3
                        _error($logger, 'rules must be a hash reference or string');
2436                }
2437
2438
7461
11050
                $validated_args{$key} = $value;
2439        }
2440
2441        # Validate parameter relationships
2442
9765
59
10290
62
        my @relationships = ref($params->{'relationships'}) eq 'ARRAY' ? @{$params->{'relationships'}} : ();
2443
2444        # Desugar per-parameter 'needs' into dependency relationships
2445        # (the sort, which keeps the relationship order stable, is only needed when
2446        # some parameter actually has a 'needs' rule)
2447
9765
369
8336
415
        foreach my $name ($has_needs ? sort(keys %{$schema}) : ()) {
2448
688
451
                my $rules = $schema->{$name};
2449
688
855
                next unless(ref($rules) eq 'HASH' && defined($rules->{'needs'}));
2450
369
246
                my $needs = $rules->{'needs'};
2451
369
511
                if(ref($needs) && ref($needs) ne 'ARRAY') {
2452
1
1
                        _error($logger, "$schema_description: 'needs' for parameter '$name' must be a string or an arrayref");
2453                }
2454
368
366
335
275
                foreach my $required (ref($needs) ? @{$needs} : ($needs)) {
2455
372
747
                        push @relationships, { type => 'dependency', param => $name, requires => $required };
2456                }
2457        }
2458
2459
9764
7937
        if(@relationships) {
2460
425
442
                _validate_relationships(\%validated_args, \@relationships, $logger, $schema_description);
2461        }
2462
2463
9441
7982
        if(my $cross_validation = $params->{'cross_validation'}) {
2464
57
57
52
55
                foreach my $validator_name(keys %{$cross_validation}) {
2465
65
60
                        my $validator = $cross_validation->{$validator_name};
2466
65
117
                        if((!ref($validator)) || (ref($validator) ne 'CODE')) {
2467
2
5
                                _error($logger, "$schema_description: cross_validation $validator is not a code snippet");
2468
0
0
                                _unreachable($logger);  # Defensive: _error always croaks, so this is never reached.
2469                        }
2470
63
63
50
67
                        if(my $error = &{$validator}(\%validated_args, $validator)) {
2471
26
92
                                _error($logger, $error);
2472                                # We have no idea which parameters are still valid, so let's invalidate them all
2473
0
0
                                return;
2474                        }
2475                }
2476        }
2477
2478
9412
7014
        foreach my $key(keys %invalid_args) {
2479
0
0
                delete $validated_args{$key};
2480        }
2481
2482
9412
7177
        if($are_positional_args == 1) {
2483
24
18
                my @rc;
2484
24
24
20
23
                foreach my $key (keys %{$schema}) {
2485                        # Use exists() rather than if(my $value = ...) so that falsy but
2486                        # valid coerced values (integer 0, empty string, undef from an
2487                        # absent optional) are not silently dropped from the return array.
2488
40
41
                        if(exists $validated_args{$key}) {
2489
38
34
                                my $value = delete $validated_args{$key};
2490
38
51
                                my $position = $schema->{$key}->{'position'};
2491
38
35
                                if(defined($rc[$position])) {
2492
2
4
                                        _error($logger, "$schema_description: $key: position $position appears twice");
2493                                }
2494
36
38
                                $rc[$position] = $value;
2495                        }
2496                }
2497
22
55
                return \@rc;
2498        }
2499
9388
15322
        return \%validated_args;
2500}
2501
2502 - 2579
=head2 compile_schema

  my $validator = compile_schema(\%schema);
  my $result    = $validator->(\%input);

  # with optional keyword args
  my $validator = compile_schema(\%schema,
      description            => 'User registration',
      custom_types           => \%types,
      unknown_parameter_handler => 'warn',
  );

Pre-captures a schema (and any optional keyword arguments accepted by
C<validate_strict>) into a reusable validator closure.  Calling the returned
coderef is equivalent to:

  validate_strict(schema => \%schema, input => \%input, %opts);

but the schema is analysed once, when C<compile_schema> is called, rather than
on every call - useful when the same schema is applied repeatedly in a hot
path.  The result, the errors raised, the warnings and the logger calls are
exactly those of C<validate_strict>; only the speed differs.

Fields that use a built-in type (C<string>, C<integer>, C<number>, C<boolean>,
C<arrayref>, C<hashref>, C<scalar>, C<coderef>, C<object> and their synonyms)
with any of the rules C<min>, C<max>, C<optional>, C<nullable>, C<default>,
C<description>, C<error_msg>, C<matches>, C<memberof> (also C<enum> and
C<values>) and C<case_sensitive> are validated by a fast path.  Any other
field - one that uses C<callback>, C<transform>, union types, C<aliases>,
C<needs>, nested C<schema>, custom types, the class and element rules, and so
on - is validated by the general code, as before, so using such a rule never
changes behaviour; it just does not get faster.  Positional schemas (those with
C<position>) are not precompiled.  On a typical five-field schema a compiled
validator runs about three times faster than calling C<validate_strict>
directly.

B<The schema must not be modified after it has been compiled>, since what was
learnt about it is kept.  Compile a new validator instead.

=head3 Arguments

=over 4

=item * C<\%schema> (required)

The validation schema as a hashref or arrayref, identical to the C<schema>
argument of C<validate_strict>.

=item * C<%opts> (optional)

Any keyword arguments accepted by C<validate_strict> other than C<schema>
and C<input>: C<description>, C<custom_types>,
C<unknown_parameter_handler>, C<logger>, C<relationships>,
C<cross_validation>, etc.

=back

=head3 Returns

A code reference C<sub ($input) -E<gt> \%validated>.

=head3 API SPECIFICATION

=head4 Input

  {
      schema => { type => ['hashref', 'arrayref'] },
      opts   => { type => 'hashref', optional => 1 },   # passed as trailing key/value pairs
  }

=head4 Output

  { type => 'coderef' }

The returned coderef has the signature C<sub ($input) -E<gt> \%validated>,
and croaks in the same way as C<validate_strict>.

=cut
2580
2581sub compile_schema
2582{
2583
852
140354
        my ($schema, %opts) = @_;
2584
852
1085
        unless(ref($schema) eq 'HASH' || ref($schema) eq 'ARRAY') {
2585
3
13
                Carp::croak('compile_schema: schema must be a hash or array reference');
2586        }
2587
2588        # Options that would override the schema or input are left to
2589        # validate_strict to resolve, exactly as before, with nothing precompiled.
2590
849
3396
708
2771
        if(grep { exists($opts{$_}) } qw(schema input args _compiled)) {
2591                return sub {
2592
1
4
                        my $input = shift;
2593
1
2
                        return validate_strict(schema => $schema, input => $input, %opts);
2594
1
4
                };
2595        }
2596
2597        # An arrayref schema is normalised once here rather than on every call.  Any
2598        # error it would raise is left to surface at call time, as before.
2599
848
774
        if(ref($schema) eq 'ARRAY') {
2600
2
2
2
4
                my $normalised = eval { _schema_from_arrayref($schema, undef) };
2601
2
236
                $schema = $normalised if($normalised);
2602        }
2603
2604
848
1087
        my $compiled = _compile_schema($schema, $opts{'custom_types'});
2605
848
1193
        my %params = (schema => $schema, %opts);
2606
848
1008
        $params{'_compiled'} = $compiled if($compiled);
2607
2608        return sub {
2609                # Setting input in place avoids copying the option hash on every call.
2610                # local restores it on exit, so re-entrant and recursive use is safe.
2611
23156
2499787
                local $params{'input'} = shift;
2612
23156
20796
                return validate_strict(\%params);
2613
848
1445
        };
2614}
2615
2616# _compile_schema($schema, $custom_types)
2617#
2618# Pre-compute everything about a named-parameter schema that does not depend on
2619# the input, for use by compile_schema.  Returns undef when the schema is not
2620# suitable (positional, wrapped in 'members', and so on), in which case
2621# validate_strict simply interprets it as usual.
2622#
2623# For each field whose rules are *fully* understood - a plain built-in type and
2624# a small set of common rules - a record is stored in {fields}; validate_strict
2625# validates such fields without the generic rule interpreter.  Anything unusual
2626# (callbacks, transforms, unions, aliases, nested schemas, custom types, bad
2627# constraint values, ...) is left out and so takes the generic path, which keeps
2628# a single implementation of the complicated rules and of every error path.
2629sub _compile_schema
2630{
2631
923
84384
        my ($schema, $custom_types) = @_;
2632
2633
923
926
        return unless(ref($schema) eq 'HASH');
2634
921
885
        return if(exists($schema->{'members'}));     # 'members' may denote a wrapper
2635
2636
920
3772
        my %type_info = (
2637                string => [_T_STRING, 's'], str => [_T_STRING, 's'],
2638                integer => [_T_INT, 'n'], int => [_T_INT, undef],
2639                number => [_T_NUM, 'n'], float => [_T_NUM, 'n'],
2640                num => [_T_NUM, undef], double => [_T_NUM, undef],
2641                boolean => [_T_BOOL, undef], bool => [_T_BOOL, undef],
2642                arrayref => [_T_ARRAY, 'a'], hashref => [_T_HASH, 'h'],
2643                scalar => [_T_SCALAR, undef], coderef => [_T_CODE, undef],
2644                object => [_T_OBJECT, undef],
2645        );
2646        # Types whose values are plain scalars, so that 'matches' behaves simply
2647
920
10120
808
7672
        my %scalar_like = map { $_ => 1 } qw(string str integer int number float num double boolean bool scalar);
2648
920
11960
1123
8577
        my %allowed = map { $_ => 1 } qw(type min max optional nullable default description error_msg
2649                matches memberof enum values case_sensitive);
2650
2651
920
1004
        my $has_aliases = 0;
2652
920
559
        my $has_needs = 0;
2653
920
541
        my %fields;
2654
2655
920
920
585
847
        foreach my $key (keys %{$schema}) {
2656
994
682
                my $rules = $schema->{$key};
2657
994
774
                next unless(defined($rules));
2658
2659
988
871
                if(ref($rules) eq 'HASH') {
2660                        # Positional schemas are not compiled, and a slurp rule is an error
2661                        # when there is no position; leave both to the generic code.
2662
957
1322
                        return if(exists($rules->{'position'}) || exists($rules->{'slurp'}));
2663
955
895
                        $has_aliases = 1 if(ref($rules->{'aliases'}) eq 'ARRAY');
2664
955
793
                        $has_needs = 1 if(defined($rules->{'needs'}));
2665                } elsif(ref($rules) eq '') {
2666
31
29
                        $rules = { type => $rules }; # as the generic code does
2667                } else {
2668
0
0
                        next;
2669                }
2670
2671
986
1072
                my $f = _compile_field($key, $rules, \%type_info, \%scalar_like, \%allowed, $custom_types);
2672
986
1234
                $fields{$key} = $f if($f);
2673        }
2674
2675        return {
2676                schema => $schema,
2677                fields => \%fields,
2678                has_aliases => $has_aliases,
2679                has_needs => $has_needs,
2680
918
918
810
3884
                positional => (%{$schema} ? 0 : -1),
2681        };
2682}
2683
2684# _compile_field($key, \%rules, ...)
2685#
2686# Return the record for one field, or undef if its rules are not entirely within
2687# what the fast path in validate_strict reproduces.  When in any doubt, undef.
2688sub _compile_field
2689{
2690
986
1053
        my ($key, $rules, $type_info, $scalar_like, $allowed, $custom_types) = @_;
2691
2692
986
2217
986
585
2092
946
        return if(grep { !$allowed->{$_} } keys %{$rules});
2693
2694        # Every value must be a plain scalar, apart from the two that may be refs
2695
817
817
611
786
        foreach my $name (keys %{$rules}) {
2696
1850
1392
                next if($name eq 'default');
2697
1807
1072
                my $v = $rules->{$name};
2698
1807
1526
                if(ref($v)) {
2699
210
290
                        next if($name eq 'matches' && ref($v) eq 'Regexp');
2700
161
353
                        next if(($name eq 'memberof' || $name eq 'enum' || $name eq 'values') && ref($v) eq 'ARRAY');
2701
45
54
                        return;
2702                }
2703        }
2704
2705
772
682
        my $type = $rules->{'type'};
2706
772
928
        return unless(defined($type) && !ref($type));
2707
770
860
        my $info = $type_info->{lc($type)} or return;
2708
758
711
        return if(ref($custom_types) eq 'HASH' && exists($custom_types->{lc($type)}));
2709
2710
756
506
        my $label = "'$key'";
2711
756
611
        if(exists($rules->{'description'})) {
2712
56
53
                return unless(defined($rules->{'description'}));
2713
55
45
                $label = "'$key' ($rules->{description})";
2714        }
2715
2716        my %f = (
2717                rules => $rules,
2718                type => $type,
2719                tname => lc($type),
2720                t => $info->[0],
2721                mk => $info->[1],
2722                label => $label,
2723                opt => 0,
2724                has_default => exists($rules->{'default'}) ? 1 : 0,
2725
755
1978
                default => $rules->{'default'},
2726        );
2727
2728        # optional wins over nullable if both are present, as in validate_strict
2729
755
746
        if(exists($rules->{'optional'})) {
2730
150
163
                $f{'opt'} = $rules->{'optional'} ? 1 : 0;
2731        } elsif($rules->{'nullable'}) {
2732
37
51
                $f{'opt'} = 1;
2733        }
2734
2735
755
553
        foreach my $bound (qw(min max)) {
2736
1378
1302
                next unless(exists($rules->{$bound}));
2737
382
261
                my $v = $rules->{$bound};
2738
382
836
                return unless(defined($v) && $info->[1] && Scalar::Util::looks_like_number($v));
2739
229
311
                return if($bound eq 'min' && $info->[1] eq 's' && $v < 0);        # meaningless; generic code reports it
2740
225
275
                $f{$bound} = $v;
2741        }
2742
598
686
        return if(defined($f{'min'}) && defined($f{'max'}) && $f{'min'} > $f{'max'});
2743
2744
587
501
        if(exists($rules->{'matches'})) {
2745
68
106
                return unless($scalar_like->{lc($type)});
2746
52
44
                my $m = $rules->{'matches'};
2747
52
43
                return unless(defined($m));
2748
52
89
                $f{'re'} = (ref($m) eq 'Regexp') ? $m : qr/\Q$m\E/;
2749
52
67
                $f{'match_src'} = $m;
2750        }
2751
2752
571
1713
455
1482
        my @list_names = grep { exists($rules->{$_}) } qw(memberof enum values);
2753
571
539
        if(@list_names) {
2754                # exactly one, and not combined with min/max (which is an error)
2755
126
224
                return if(@list_names > 1 || exists($rules->{'min'}) || exists($rules->{'max'}));
2756
113
151
                return unless(ref($rules->{$list_names[0]}) eq 'ARRAY');
2757
94
94
                $f{'list'} = $rules->{$list_names[0]};
2758        } elsif(exists($rules->{'case_sensitive'})) {
2759
19
33
                return; # meaningless without a list; leave it to the generic code
2760        }
2761
2762
520
601
        return \%f;
2763}
2764
2765# _schema_from_arrayref($arrayref, $logger)
2766#
2767# Normalise an arrayref schema:
2768#   [ { name => 'param', type => 'string', ... }, ... ]
2769# to the standard named-parameter hashref form:
2770#   { param => { type => 'string', ... }, ... }
2771#
2772# The 'name' key is consumed during conversion and does not become a rule.
2773# Croaks if any element is not a hashref, is missing 'name', or if a name
2774# appears more than once.
2775sub _schema_from_arrayref
2776{
2777
20
20
        my ($arrayref, $logger) = @_;
2778
2779
20
18
        my %schema;
2780
20
20
14
22
        foreach my $spec (@{$arrayref}) {
2781
27
33
                _error($logger, "validate_strict: each arrayref schema element must be a hashref")
2782                        unless ref($spec) eq 'HASH';
2783                _error($logger, "validate_strict: arrayref schema element must have a 'name' key")
2784
25
27
                        unless exists($spec->{'name'});
2785
21
21
17
28
                my %rule = %{$spec};
2786
21
24
                my $name = delete $rule{'name'};
2787                _error($logger, "validate_strict: duplicate parameter '$name' in arrayref schema")
2788
21
25
                        if exists($schema{$name});
2789
19
25
                $schema{$name} = \%rule;
2790        }
2791
12
14
        return \%schema;
2792}
2793
2794# Return number of visible characters not number of bytes
2795# Ensure string is decoded into Perl characters
2796sub _number_of_characters
2797{
2798
1827
73539
        my $value = $_[0];
2799
2800
1827
1442
        return if(!defined($value));
2801
2802
1826
2355
        if($value !~ /[^[:ascii:]]/) {
2803
1684
1746
                return length($value);
2804        }
2805        # Decode only if it's not already a Perl character string
2806
142
231
        $value = decode_utf8($value) unless utf8::is_utf8($value);
2807
2808        # Count grapheme clusters (visible characters).
2809        # \X matches one extended grapheme cluster; Perl's Unicode tables are kept
2810        # current with each release, correctly handling ZWJ sequences and emoji
2811        # modifier sequences that Unicode::GCString 2013.10 could not.
2812
142
582
        return scalar(() = $value =~ /\X/g);
2813}
2814
2815sub _apply_nested_defaults {
2816
155
5517
        my ($input, $schema) = @_;
2817
155
163
        my %result = %$input;
2818
2819
155
148
        foreach my $key (keys %$schema) {
2820
237
172
                my $rules = $schema->{$key};
2821
2822
237
343
                if (ref $rules eq 'HASH' && exists $rules->{default} && !exists $result{$key}) {
2823
11
21
                        $result{$key} //= $rules->{default};
2824                }
2825
2826                # Recursively handle nested schema
2827
237
353
                if((ref $rules eq 'HASH') && $rules->{schema} && (ref $result{$key} eq 'HASH')) {
2828
10
14
                        $result{$key} = _apply_nested_defaults($result{$key}, $rules->{schema});
2829                }
2830        }
2831
2832
155
149
        return \%result;
2833}
2834
2835sub _validate_relationships {
2836
425
389
        my ($validated_args, $relationships, $logger, $description) = @_;
2837
2838
425
421
        return unless ref($relationships) eq 'ARRAY';
2839
2840
425
339
        foreach my $rel (@$relationships) {
2841
429
406
                my $type = $rel->{type} or next;
2842
2843
429
540
                if ($type eq 'mutually_exclusive') {
2844
10
12
                        _validate_mutually_exclusive($validated_args, $rel, $logger, $description);
2845                } elsif ($type eq 'required_group') {
2846
7
22
                        _validate_required_group($validated_args, $rel, $logger, $description);
2847                } elsif ($type eq 'conditional_requirement') {
2848
9
18
                        _validate_conditional_requirement($validated_args, $rel, $logger, $description);
2849                } elsif ($type eq 'dependency') {
2850
378
346
                        _validate_dependency($validated_args, $rel, $logger, $description);
2851                } elsif ($type eq 'value_constraint') {
2852
17
21
                        _validate_value_constraint($validated_args, $rel, $logger, $description);
2853                } elsif ($type eq 'value_conditional') {
2854
7
11
                        _validate_value_conditional($validated_args, $rel, $logger, $description);
2855                } else {
2856
1
2
                        _error($logger, "Unknown relationship type $type");
2857                }
2858        }
2859}
2860
2861sub _validate_mutually_exclusive {
2862
14
5477
        my ($args, $rel, $logger, $description) = @_;
2863
2864
14
14
15
28
        my @params = @{$rel->{params} || []};
2865
14
22
        return unless @params >= 2;
2866
2867
14
28
15
24
        my @present = grep { _param_defined($args, $_) } @params;
2868
2869
14
25
        if (@present > 1) {
2870
7
18
                my $msg = $rel->{description} || 'Cannot specify both ' . join(' and ', @present);
2871
7
13
                _error($logger, "$description: $msg");
2872        }
2873}
2874
2875sub _validate_required_group {
2876
9
2347
        my ($args, $rel, $logger, $description) = @_;
2877
2878
9
9
10
21
        my @params = @{$rel->{params} || []};
2879
9
13
        return unless @params >= 2;
2880
2881
8
16
8
15
        my @present = grep { _param_defined($args, $_) } @params;
2882
2883
8
16
        if (@present == 0) {
2884                my $msg = $rel->{description} ||
2885
4
11
                        'Must specify at least one of: ' . join(', ', @params);
2886
4
7
                _error($logger, "$description: $msg");
2887        }
2888}
2889
2890sub _validate_conditional_requirement {
2891
13
4490
        my ($args, $rel, $logger, $description) = @_;
2892
2893
13
20
        my $if_param = $rel->{if} or return;
2894
12
16
        my $then_param = $rel->{then_required} or return;
2895
2896        # If the condition parameter is present and defined
2897
11
11
        if (_param_defined($args, $if_param)) {
2898                # Check if it's truthy (for booleans and general values)
2899
9
14
                if ($args->{$if_param}) {
2900                        # Then the required parameter must also be present
2901
7
8
                        unless (_param_defined($args, $then_param)) {
2902
3
7
                                my $msg = $rel->{description} || "When $if_param is specified, $then_param is required";
2903
3
6
                                _error($logger, "$description: $msg");
2904                        }
2905                }
2906        }
2907}
2908
2909sub _validate_dependency {
2910
381
3734
        my ($args, $rel, $logger, $description) = @_;
2911
2912
381
332
        my $param = $rel->{param} or return;
2913
380
303
        my $requires = $rel->{requires} or return;
2914
2915        # If param is present, requires must also be present
2916
380
347
        if (_param_defined($args, $param)) {
2917
315
248
                unless (_param_defined($args, $requires)) {
2918
300
363
                        my $msg = $rel->{description} || "$param requires $requires to be specified";
2919
300
290
                        _error($logger, "$description: $msg");
2920                }
2921        }
2922}
2923
2924sub _validate_value_constraint {
2925
32
7402
        my ($args, $rel, $logger, $description) = @_;
2926
2927
32
40
        my $if_param = $rel->{if} or return;
2928
32
34
        my $then_param = $rel->{then} or return;
2929
32
31
        my $operator = $rel->{operator} or return;
2930
32
22
        my $value = $rel->{value};
2931
32
34
        return unless defined $value;
2932
2933        # If the condition parameter is present and truthy
2934
32
37
        if (_param_defined($args, $if_param) && $args->{$if_param}) {
2935                # Check if the then parameter exists
2936
29
24
                if (_param_defined($args, $then_param)) {
2937
29
33
                        my $actual = $args->{$then_param};
2938
29
21
                        my $valid = 0;
2939
2940
29
47
                        if ($operator eq '==') {
2941
8
21
                                $valid = ($actual == $value);
2942                        } elsif ($operator eq '!=') {
2943
4
3
                                $valid = ($actual != $value);
2944                        } elsif ($operator eq '<') {
2945
4
4
                                $valid = ($actual < $value);
2946                        } elsif ($operator eq '<=') {
2947
4
4
                                $valid = ($actual <= $value);
2948                        } elsif ($operator eq '>') {
2949
4
4
                                $valid = ($actual > $value);
2950                        } elsif ($operator eq '>=') {
2951
4
3
                                $valid = ($actual >= $value);
2952                        }
2953
2954
29
58
                        unless ($valid) {
2955
17
46
                                my $msg = $rel->{description} || "When $if_param is specified, $then_param must be $operator $value (got $actual)";
2956
17
25
                                _error($logger, "$description: $msg");
2957                        }
2958                }
2959        }
2960}
2961
2962sub _validate_value_conditional {
2963
11
4737
        my ($args, $rel, $logger, $description) = @_;
2964
2965
11
18
        my $if_param = $rel->{if} or return;
2966
11
11
        my $equals = $rel->{equals};
2967
11
34
        my $then_param = $rel->{then_required} or return;
2968
11
13
        return unless defined $equals;
2969
2970        # If the parameter has the specific value
2971
11
10
        if (_param_defined($args, $if_param)) {
2972
9
21
                if ($args->{$if_param} eq $equals) {
2973                        # Then the required parameter must be present
2974
6
5
                        unless (_param_defined($args, $then_param)) {
2975                                my $msg = $rel->{description} ||
2976
4
11
                                        "When $if_param equals '$equals', $then_param is required";
2977
4
10
                                _error($logger, "$description: $msg");
2978                        }
2979                }
2980        }
2981}
2982
2983# Emit either the rule's custom error_msg or the supplied default message.
2984# Accepts a list for @default_parts so callers can pass join() fragments
2985# without pre-allocating a concatenated string.
2986sub _rule_error
2987{
2988
30632
30522
        my ($logger, $rules, @default_parts) = @_;
2989
30632
51341
        _error($logger, $rules->{'error_msg'} || join('', @default_parts));
2990}
2991
2992# Package-level cache: maps "refaddr(list):mode" -> [weak_list_ref, lookup_hash].
2993# Each entry holds a WEAK reference to the original list arrayref alongside the
2994# compiled lookup hash.  When the list goes out of scope and is freed, the weak
2995# reference becomes undef; the next access detects the stale entry and rebuilds,
2996# preventing false cache hits after address reuse.
2997my %_pvs_memberof_cache;
2998
2999# Return true if $value is present in $list, respecting numeric vs string
3000# comparison and the case_sensitive flag.  Used by both memberof and notmemberof.
3001# On the first call for a given ($list, mode) pair the lookup hash is built
3002# (O(k)); subsequent calls with the same live list object are O(1).
3003sub _value_in_list
3004{
3005
1907
2266
        my ($value, $list, $type, $case_sensitive) = @_;
3006
1907
3141
        my $is_numeric = ($type eq 'integer') || ($type eq 'number') || ($type eq 'float');
3007
1907
2563
        my $is_icase   = !$is_numeric && defined($case_sensitive) && !$case_sensitive;
3008
3009        # Key combines address and comparison mode so the same list object can be
3010        # cached under multiple modes without collision.
3011
1907
2628
        my $ckey = Scalar::Util::refaddr($list) . ($is_numeric ? 'n' : $is_icase ? 'i' : 's');
3012
1907
1508
        my $entry = $_pvs_memberof_cache{$ckey};
3013
3014        # Stale check: if the weak ref is dead the list was freed and its address
3015        # may have been reused by a different list - discard the cached hash.
3016
1907
2522
        if(defined($entry) && !defined($entry->[0])) {
3017
0
0
                delete $_pvs_memberof_cache{$ckey};
3018
0
0
                $entry = undef;
3019        }
3020
3021
1907
1459
        unless(defined $entry) {
3022
338
204
                my $lookup;
3023
338
303
                if($is_numeric) {
3024                        # Normalise to numeric value so "1" and "1.0" hash identically.
3025
58
154
58
44
503
53
                        $lookup = { map { ($_ + 0) => 1 } @{$list} };
3026                } elsif($is_icase) {
3027
44
92
44
31
115
47
                        $lookup = { map { lc($_) => 1 } @{$list} };
3028                } else {
3029
236
594
236
145
612
203
                        $lookup = { map { $_ => 1 } @{$list} };
3030                }
3031                # Store [weak_ref_to_list, lookup_hash] - weak ref does not prevent GC.
3032
338
434
                my $weak = $list;
3033
338
421
                Scalar::Util::weaken($weak);
3034
338
436
                $_pvs_memberof_cache{$ckey} = [$weak, $lookup];
3035
338
315
                $entry = $_pvs_memberof_cache{$ckey};
3036        }
3037
3038
1907
1351
        my $lookup = $entry->[1];
3039        return $is_numeric ? exists($lookup->{$value + 0})
3040             : $is_icase   ? exists($lookup->{lc($value)})
3041
1907
3470
             :               exists($lookup->{$value});
3042}
3043
3044# Return true when $args->{$param} is both present (exists) and defined.
3045sub _param_defined
3046{
3047
835
595
        my ($args, $param) = @_;
3048
835
1251
        return exists($args->{$param}) && defined($args->{$param});
3049}
3050
3051# Called from code paths that path analysis shows can never run.  If one ever
3052# does, fail loudly rather than carry on with undefined behaviour.
3053sub _unreachable
3054{
3055
2
2008
        my $logger = shift;
3056
2
2
        my @call_details = caller(0);
3057
2
31
        my $message = 'BUG: this code should not be reachable.  Please report it to the maintainer';
3058
3059
2
4
        if($logger) {
3060
1
2
                $logger->error(__PACKAGE__, ' line ', $call_details[2], ": $message");
3061        }
3062
2
11
        Carp::croak(__PACKAGE__, ' line ', $call_details[2], ": $message");
3063}
3064
3065# Helper to log error or croak
3066sub _error
3067{
3068
40092
30999
        my $logger = shift;
3069
40092
32627
        my $message = join('', @_);
3070        # Strip ASCII control characters to prevent log-injection / CRLF attacks
3071        # when user-supplied values appear in the message.
3072
40092
36327
        $message =~ s/[[:cntrl:]]/ /g;
3073
3074
40092
40098
        my @call_details = caller(0);
3075
40092
259346
        if($logger) {
3076
59
103
                $logger->error(__PACKAGE__, ' line ', $call_details[2], ": $message");
3077        }
3078
40092
142622
        Carp::croak(__PACKAGE__, ' line ', $call_details[2], ": $message");
3079}
3080
3081# Helper to log warning or carp
3082sub _warn
3083{
3084
28
3570
        my $logger = shift;
3085
28
33
        my $message = join('', @_);
3086        # Strip ASCII control characters to prevent log-injection / CRLF attacks.
3087
28
52
        $message =~ s/[[:cntrl:]]/ /g;
3088
3089
28
30
        if($logger) {
3090
7
18
                $logger->warn(__PACKAGE__, ": $message");
3091        } else {
3092
21
89
                Carp::carp(__PACKAGE__, ": $message");
3093        }
3094}
3095
3096 - 3329
=head1 AUTHOR

Nigel Horne, C<< <njh at nigelhorne.com> >>

=encoding utf-8

=head1 FORMAL SPECIFICATION

    [PARAM_NAME, VALUE, TYPE_NAME, CONSTRAINT_VALUE]

    ValidationRule ::= SimpleType | ComplexRule | UnionType

    SimpleType ::= string | integer | number | float | boolean | scalar
               | scalarref | stringref | arrayref | hashref | coderef
               | object | void | regex | handle
               | arraylike | hashlike | codelike | invocant

    UnionType ::= seq SimpleType    -- at least two members; written as type => ['a', 'b']

    ComplexRule == [
        type: SimpleType | UnionType;
        min: ℕ₁;
        max: ℕ₁;
        optional: 𝔹;
        matches: REGEX;
        regex: REGEX;
        nomatch: REGEX;
        memberof: seq VALUE;
        enum: seq VALUE;
        values: seq VALUE;
        notmemberof: seq VALUE;
        callback: FUNCTION;
        isa: TYPE_NAME;
        does: ROLE_NAME;
        can: METHOD_NAME | seq METHOD_NAME;
        classisa: TYPE_NAME;
        subclass: TYPE_NAME;
        classdoes: ROLE_NAME;
        classcan: METHOD_NAME | seq METHOD_NAME;
        element_isa: TYPE_NAME;
        needs: PARAM_NAME | seq PARAM_NAME;
        driver: TYPE_NAME;
        semantic: 'unix_timestamp' | 'identifier' | 'class_name' | 'filename';
        aliases: seq PARAM_NAME;
        slurp: 𝔹;
        position: â„•â‚€;
        default: VALUE;
        transform: FUNCTION;
        error_msg: STRING
    ]

    Schema == PARAM_NAME ⇸ ValidationRule

    Arguments == PARAM_NAME ⇸ VALUE

    ValidatedResult == PARAM_NAME ⇸ VALUE

    âˆ€ rule: ComplexRule •
      rule.min ≤ rule.max ∧
      Â¬((rule.memberof ∨ rule.enum ∨ rule.values) ∧ rule.min) ∧
      Â¬((rule.memberof ∨ rule.enum ∨ rule.values) ∧ rule.max) ∧
      Â¬(rule.notmemberof ∧ rule.min) ∧
      Â¬(rule.notmemberof ∧ rule.max)

    âˆ€ schema: Schema; args: Arguments •
      dom(validate_strict(schema, args)) ⊆ dom(schema) ∪ dom(args)

    validate_strict: Schema × Arguments → ValidatedResult

    âˆ€ schema: Schema; args: Arguments •
      let result == validate_strict(schema, args) •
        (∀ name: dom(schema) ∩ dom(args) •
          name ∈ dom(result) ⇒
          type_matches(result(name), schema(name))) ∧
        (∀ name: dom(schema) •
          Â¬optional(schema(name)) ⇒ name ∈ dom(args))

    type_matches: VALUE × ValidationRule → 𝔹

=head1 EXAMPLE

    use Params::Get;
    use Params::Validate::Strict;

    sub where_am_i
    {
        my $params = Params::Validate::Strict::validate_strict({
            args => Params::Get::get_params(undef, \@_),
            description => 'Print a string of latitude and longitude',
            error_msg => 'Latitude is a number between +/- 90, longitude is a number between +/- 180',
            members => {
                'latitude' => {
                    type => 'number',
                    min => -90,
                    max => 90
                }, 'longitude' => {
                    type => 'number',
                    min => -180,
                    max => 180
                }
            }
        });

        print 'You are at ', $params->{'latitude'}, ', ', $params->{'longitude'}, "\n";
    }

    where_am_i({ latitude => 3.14, longitude => -155 });

=head1 BUGS

Known limitations:

=over 4

=item * C<semantic =E<gt> 'filename'> checks for a single path component only.
It does not reject characters that are illegal only on some platforms,
such as C<:> or C<\> on Windows, and does not check that the file exists.

=item * C<classisa>, C<subclass>, C<classdoes> and C<classcan> require the class to be loaded already;
use C<driver> to load it first.

=item * Grammars passed to C<bnf> are cached for the life of the process and never evicted.

=back

Please report any other bugs as described in L</SUPPORT>.

=head1 SECURITY

=head2 Taint mode

This module does B<not> untaint its return values.
When running under Perl's taint mode (C<-T>), any value that was derived from
tainted external input (C<$ENV{}>, C<STDIN>, etc.) will remain tainted in the
validated result, even if the module accepted it.
Callers that require untainted values must perform their own regex capture after
validation, for example:

    my $validated = validate_strict(%args);
    my ($safe_name) = ($validated->{name} =~ /\A([\w\s]+)\z/);

=head2 User-supplied regex patterns

The C<matches> rule accepts pre-compiled C<qr//> objects supplied by the caller.
A pathologically constructed pattern (e.g. C<qr/(a+)+b/>) can cause catastrophic
backtracking and peg a CPU core when matched against a hostile input value.
Use possessive quantifiers (C<++>) or atomic groups (C<< (?>...) >>) in any
C<matches> pattern that will be applied to untrusted data.

=head2 Error message content

Error and warning messages produced by this module may include the parameter
value supplied by the caller.
The module strips ASCII control characters (including CR and LF) from all
messages before passing them to the logger or croaking, to prevent log-injection
and HTTP response-splitting attacks.
Callers should nevertheless apply their own output encoding before including any
validated value in an HTTP response, HTML page, or structured log entry.

=head1 SEE ALSO

=over 4

=item * L<Test Dashboard|https://nigelhorne.github.io/Params-Validate-Strict/coverage/>

=item * L<Data::Processor>

=item * L<Params::Get>

=item * L<Params::Smart>

This is where the ideas for C<aliases>, C<slurp> and C<compile_schema> came from.

=item * L<Params::Util>

This is where the ideas for C<regex>, C<handle>, C<arraylike>, C<hashlike>, C<codelike>, C<invocant> came from.

=item * L<Params::SomeUtil>

A maintained fork of L<Params::Util> 1.07 with bug fixes.  The same type-predicate ideas apply.

=item * L<Params::Validate>

=item * L<Return::Set>

=item * L<App::Test::Generator>

=back

=head1 SUPPORT

This module is provided as-is without any warranty.

Please report any bugs or feature requests to C<bug-params-validate-strict at rt.cpan.org>,
or through the web interface at
L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Params-Validate-Strict>.
I will be notified, and then you'll
automatically be notified of progress on your bug as I make changes.

You can find documentation for this module with the perldoc command.

    perldoc Params::Validate::Strict

You can also look for information at:

=over 4

=item * MetaCPAN

L<https://metacpan.org/dist/Params-Validate-Strict>

=item * RT: CPAN's request tracker

L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Params-Validate-Strict>

=item * CPAN Testers' Matrix

L<http://matrix.cpantesters.org/?dist=Params-Validate-Strict>

=item * CPAN Testers Dependencies

L<http://deps.cpantesters.org/?module=Params::Validate::Strict>

=back

=head1 LICENSE AND COPYRIGHT

Copyright 2025-2026 Nigel Horne.

This program is released under the following licence: GPL2.
If you use it,
please let me know.

=cut
3330
33311;
3332