package Params::Validate::Strict;

# FIXME: {max} doesn't play ball with non-ascii strings
# TODO: better use of the description parameter in error messages
# FIXME: ensure paramaters such as min => 1 length constraint applies to all values. In this case, undef should not pass through without a croak.
# TODO: As well as type => [ 'string', 'arrayref' ], allow type => 'string|arrayref'

use strict;
use warnings;

use Carp;
use Exporter qw(import);	# Required for @EXPORT_OK
use Encode qw(decode_utf8);
use List::Util 1.33 qw(any);	# Required for memberof validation
use Params::Get 0.13;
use Readonly::Values::Boolean;
use Scalar::Util;
use Unicode::GCString;

our @ISA = qw(Exporter);
our @EXPORT_OK = qw(validate_strict);

=head1 NAME

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

=head1 VERSION

Version 0.37

=cut

our $VERSION = '0.37';

=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 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 find 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> 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.

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>)
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.
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 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>.

=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<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<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 should accept the parameter value, the argument list and the schema as arguments and return true if the value is valid, false otherwise.

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;
    }
  };

=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.
Currently only C<unix_timestamp> is supported.

  ts => { type => 'integer', semantic => 'unix_timestamp' }

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>.

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

=item * schematic

TODO: gives an idea of what the field will be, e.g. C<filename>.

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

=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

=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

sub validate_strict
{
	my $params = Params::Get::get_params(undef, \@_);

	my $schema = $params->{'schema'} || $params->{'members'};
	my $args = $params->{'args'} || $params->{'input'};
	my $logger = $params->{'logger'};
	my $custom_types = $params->{'custom_types'};
	my $unknown_parameter_handler = $params->{'unknown_parameter_handler'};
	if(!defined($unknown_parameter_handler)) {
		if($params->{'carp_on_warn'}) {
			$unknown_parameter_handler = 'warn';
		} else {
			$unknown_parameter_handler = 'die';
		}
	}

	return $args if(!defined($schema));	# No schema, allow all arguments

	# Accept arrayref schema: [{ name=>'param', type=>'...', ... }, ...]
	# Normalise to the standard named-parameter hashref form before further processing.
	if(ref($schema) eq 'ARRAY') {
		$schema = _schema_from_arrayref($schema, $logger);
	}

	# Check if schema and args are references to hashes
	if(ref($schema) ne 'HASH') {
		_error($logger, 'validate_strict: schema must be a hash reference');
	}

	# Inspired by Data::Processor
	my $schema_description = $params->{'description'} || 'validate_strict';
	my $error_msg = $params->{'error_msg'};

	if($schema->{'members'} && ($schema->{'description'} || $schema->{'error_msg'})) {
		$schema_description = $schema->{'description'};
		$error_msg = $schema->{'error_msg'};
		$schema = $schema->{'members'};
		# The members value may also be in arrayref form
		if(ref($schema) eq 'ARRAY') {
			$schema = _schema_from_arrayref($schema, $logger);
		}
	}

	if(exists($params->{'args'}) && (!defined($args))) {
		$args = {};
	} elsif((ref($args) ne 'HASH') && (ref($args) ne 'ARRAY')) {
		_error($logger, $error_msg || "$schema_description: args must be a hash or array reference");
	}

	if(ref($args) eq 'HASH') {
		# Named args
		foreach my $key (keys %{$args}) {
			if(!exists($schema->{$key})) {
				if($unknown_parameter_handler eq 'die') {
					_error($logger, "$schema_description: Unknown parameter '$key'");
				} elsif($unknown_parameter_handler eq 'warn') {
					_warn($logger, "$schema_description: Unknown parameter '$key'");
					next;
				} elsif($unknown_parameter_handler eq 'ignore') {
					if($logger) {
						$logger->debug(__PACKAGE__ . ": $schema_description: Unknown parameter '$key'");
					}
					next;
				} else {
					_error($logger, "$schema_description: '$unknown_parameter_handler' unknown_parameter_handler must be one of die, warn, ignore");
				}
			}
		}
	}

	# Find out if this routine takes positional arguments
	my $are_positional_args = -1;
	foreach my $key (keys %{$schema}) {
		if(defined(my $rules = $schema->{$key})) {
			if(ref($rules) eq 'HASH') {
				if(!defined($rules->{'position'})) {
					if($are_positional_args == 1) {
						_error($logger, "::validate_strict: $key is missing position value");
					}
					$are_positional_args = 0;
					last;
				}
				$are_positional_args = 1;
			} else {
				$are_positional_args = 0;
				last;
			}
		} else {
			$are_positional_args = 0;
			last;
		}
	}

	my %validated_args;
	my %invalid_args;
	foreach my $key (keys %{$schema}) {
		my $rules = $schema->{$key};
		my $value;
		if($are_positional_args == 1) {
			if(ref($args) ne 'ARRAY') {
				_error($logger, "::validate_strict: position $rules->{position} given for '$key', but args isn't an array");
			}
			$value = @{$args}[$rules->{'position'}];
		} else {
			$value = $args->{$key};
		}

		if(!defined($rules)) {	# Allow anything
			$validated_args{$key} = $value;
			next;
		}

		# If rules are a simple type string
		if(ref($rules) eq '') {
			$rules = { type => $rules };
		}

		my $is_optional = 0;

		my $rule_description = $schema_description;	# Can be overridden in each element

		if(ref($rules) eq 'HASH') {
			if(exists($rules->{'description'})) {
				$rule_description = $rules->{'description'};
			}
			# For stringref: validate and dereference before transform so that
			# transform (and all subsequent rule handlers) see the plain string.
			# Preserve the original ref so optional => CODE receives what the caller passed.
			my $pre_deref_value = $value;
			my $is_stringref_type = defined($value) && defined($rules->{'type'}) && !ref($rules->{'type'}) && lc($rules->{'type'}) eq 'stringref';
			if($is_stringref_type) {
				if(ref($value) ne 'SCALAR') {
					my $got = ref($value) ? 'a ' . ref($value) . ' reference' : 'a plain scalar';
					_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' must be a string reference, not $got");
				}
				$value = ${$value};
			}
			if($rules->{'transform'} && defined($value)) {
				if(ref($rules->{'transform'}) eq 'CODE') {
					$value = &{$rules->{'transform'}}($value);
				} else {
					_error($logger, "$rule_description: transforms must be a code ref");
				}
			}
			if(exists($rules->{optional})) {
				if(ref($rules->{'optional'}) eq 'CODE') {
					# For stringref the coderef receives the original SCALAR ref (what
					# the caller supplied), not the internally-dereferenced plain string.
					# For all other types the post-transform value is passed, as before.
					my $opt_arg = $is_stringref_type ? $pre_deref_value : $value;
					$is_optional = &{$rules->{optional}}($opt_arg, $args);
				} else {
					$is_optional = $rules->{'optional'};
				}
			} elsif($rules->{nullable}) {
				$is_optional = $rules->{'nullable'};
			} elsif(defined($rules->{'type'}) && !ref($rules->{'type'}) && lc($rules->{'type'}) eq 'void') {
				$is_optional = 1;
			}
		}

		# Handle optional parameters
		if((ref($rules) eq 'HASH') && $is_optional) {
			my $look_for_default = 0;
			if($are_positional_args == 1) {
				# if(!defined(@{$args}[$rules->{'position'}])) {
				if(!defined($args->[$rules->{position}])) {
					$look_for_default = 1;
				}
			} else {
				if(!exists($args->{$key})) {
					$look_for_default = 1;
				}
			}
			if($look_for_default) {
				if($are_positional_args == 1) {
					if(scalar(@{$args}) < $rules->{'position'}) {
						# arg array is too short, so it must be missing
						_error($logger, "$rule_description: Required parameter '$key' is missing");
						next;
					}
				}
				if(exists($rules->{'default'})) {
					# Populate missing optional parameters with the specified output values
					$validated_args{$key} = $rules->{'default'};
					next;	# default wins; do not fall through to the schema branch
				}

				if($rules->{'schema'}) {
					$value = _apply_nested_defaults({}, $rules->{'schema'});
					next unless scalar(%{$value});
					# The nested schema has a default value
				} else {
					next;	# optional and missing
				}
			}
		} elsif((ref($args) eq 'HASH') && !exists($args->{$key})) {
			# The parameter is required
			# Use exists rather than defined, so that an undefined value can be passed, but the key is there
			_error($logger, "$rule_description: Required parameter '$key' is missing");
		}

		# Normalise union type shorthand: { type => ['string', 'integer'], ... }
		# into the array-of-rules form that the ARRAY handler below already supports.
		# Each candidate type inherits all other constraints from the parent rule
		# (min, max, matches, optional, etc.) so they are each fully validated.
		# Must run after optional/transform handling above but before rule dispatch below.
		if(ref($rules) eq 'HASH' && ref($rules->{'type'}) eq 'ARRAY') {
			my %base = %{$rules};
			my @type_list = @{delete $base{'type'}};
			if(!@type_list) {
				_error($logger, "$rule_description: Parameter '$key': union type list must not be empty");
			}
			# Expand into one full rule hash per candidate type
			$rules = [ map { { %base, type => $_ } } @type_list ];
		}

		# Validate based on rules
		if(ref($rules) eq 'HASH') {
			if(defined(my $min = $rules->{'min'} // $rules->{'minimum'}) && defined(my $max = $rules->{'max'})) {
				if($min > $max) {
					_error($logger, "validate_strict($key): min must be <= max ($min > $max)");
				}
			}

			# memberof and its synonym enum cannot be combined with min or max
			if($rules->{'memberof'} || $rules->{'enum'} || $rules->{'values'}) {
				if(defined(my $min = $rules->{'min'} // $rules->{'minimum'})) {
					_error($logger, "validate_strict($key): min ($min) makes no sense with memberof/enum/values");
				}
				if(defined(my $max = $rules->{'max'})) {
					_error($logger, "validate_strict($key): max ($max) makes no sense with memberof/enum/values");
				}
			}

			foreach my $rule_name (keys %$rules) {
				my $rule_value = $rules->{$rule_name};

				if((ref($rule_value) eq 'CODE')
					&& ($rule_name ne 'validate')
					&& ($rule_name ne 'callback')
					&& ($rule_name ne 'validator')
					&& ($rule_name ne 'transform')	# already applied before this loop
					&& ($rule_name ne 'optional')) {	# already applied before this loop
					$rule_value = &{$rule_value}($value, $args);
				}

				# Better OOP, the routine has been given an object rather than a scalar
				if(Scalar::Util::blessed($rule_value) && $rule_value->can('as_string')) {
					$rule_value = $rule_value->as_string();
				}

				if($rule_name eq 'type') {
					my $type = lc($rule_value);

					if(($type eq 'string') || ($type eq 'str')) {
						if(ref($value)) {
							_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' must be a string");
						}
						unless((ref($value) eq '') || (defined($value) && length($value))) {	# Allow undef for optional strings
							_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' must be a string");
						}
					} elsif(($type eq 'integer') || ($type eq 'int')) {
						if(!defined($value)) {
							next;	# Skip if number is undefined
						}
						if(!Scalar::Util::looks_like_number($value) || ($value - $value) != 0 || $value != int($value)) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must be an integer");
							}
						}
						$value = int($value); # Coerce to integer
					} elsif(($type eq 'number') || ($type eq 'float') || ($type eq 'num') || ($type eq 'double')) {
						if(!defined($value)) {
							next;	# Skip if number is undefined
						}
						if(!Scalar::Util::looks_like_number($value)) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be a number");
							}
						}
						# $value = eval $value; # Coerce to number (be careful with eval)
						$value = 0 + $value;	# Numeric coercion
					} elsif($type eq 'arrayref') {
						if(!defined($value)) {
							next;	# Skip if arrayref is undefined
						}
						if(ref($value) ne 'ARRAY') {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be an arrayref, not " . ref($value));
							}
						}
					} elsif($type eq 'hashref') {
						if(!defined($value)) {
							next;	# Skip if hashref is undefined
						}
						if(ref($value) ne 'HASH') {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be an hashref");
							}
						}
					} elsif($type eq 'scalar') {
						if(!defined($value)) {
							next;	# Skip if undefined
						}
						if(ref($value)) {
							_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' must be a scalar, not a " . ref($value) . ' reference');
						}
					} elsif($type eq 'scalarref') {
						if(!defined($value)) {
							next;	# Skip if undefined
						}
						if(ref($value) ne 'SCALAR') {
							my $got = ref($value) ? 'a ' . ref($value) . ' reference' : 'a plain scalar';
							_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' must be a scalar reference, not $got");
						}
					} elsif($type eq 'stringref') {
						if(!defined($value)) {
							next;	# Skip if undefined
						}
						# The early-deref block validated the SCALAR ref and set $value to the
						# plain string.  If transform subsequently returned a reference, reject it.
						if(ref($value)) {
							_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' stringref transform must return a plain string, not a " . ref($value) . ' reference');
						}
					} elsif($type eq 'void') {
						if(scalar(keys %{$schema}) != 1) {
							_error($logger, "$rule_description: type 'void' requires exactly one parameter in the schema");
						}
						if(defined($value)) {
							_error($logger, $rules->{'error_msg'} || "$rule_description: Parameter '$key' must be undef (void type accepts no value)");
						}
					} elsif(($type eq 'boolean') || ($type eq 'bool')) {
						if(!defined($value)) {
							next;	# Skip if bool is undefined
						}
						if(defined(my $b = $Readonly::Values::Boolean::booleans{$value})) {
							$value = $b;
						} else {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must be a boolean");
							}
						}
					} elsif($type eq 'coderef') {
						if(!defined($value)) {
							next;	# Skip if code is undefined
						}
						if(ref($value) ne 'CODE') {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be a coderef, not a ref to " . ref($value));
							}
						}
					} elsif($type eq 'object') {
						if(!defined($value)) {
							next;	# Skip if object is undefined
						}
						if(!Scalar::Util::blessed($value)) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be an object");
							}
						}
					} elsif(my $custom_type = $custom_types->{$type}) {
						if($custom_type->{'transform'}) {
							# The custom type has a transform embedded within it
							if(ref($custom_type->{'transform'}) eq 'CODE') {
								$value = &{$custom_type->{'transform'}}($value);
							} else {
								_error($logger, "$rule_description: transforms must be a code ref");
								next;
							}
						}
						validate_strict({ input => { $key => $value }, schema => { $key => $custom_type }, custom_types => $custom_types });
					} else {
						_error($logger, "$rule_description: Unknown type '$type'");
					}
				} elsif(($rule_name eq 'min') || ($rule_name eq 'minimum')) {
					if(!defined($rules->{'type'})) {
						_error($logger, "$rule_description: Don't know type of '$key' to determine its minimum value $rule_value");
					}
					my $type = lc($rules->{'type'});
					if(exists($custom_types->{$type}->{'min'}) || exists($custom_types->{$type}->{minimum})) {
						$rule_value = $custom_types->{$type}->{'min'} // $custom_types->{$type}->{minumum};
						$type = $custom_types->{$type}->{'type'};
					}
					if(($type eq 'string') || ($type eq 'str') || ($type eq 'stringref')) {
						if($rule_value < 0) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: String parameter '$key' has meaningless minimum value that is less than zero");
							}
						}
						if(!defined($value)) {
							next;	# Skip if string is undefined
						}
						if(defined(my $len = _number_of_characters($value))) {
							if($len < $rule_value) {
								_error($logger, $rules->{'error_msg'} || "$rule_description: String parameter '$key' too short, ($len characters), must be at least $rule_value characters");
								$invalid_args{$key} = 1;
							}
						} else {
							_error($logger, $rules->{'error_msg'} || "$rule_description: '$key' can't be decoded");
							$invalid_args{$key} = 1;
						}
					} elsif($type eq 'arrayref') {
						if(!defined($value)) {
							next;	# Skip if array is undefined
						}
						if(ref($value) ne 'ARRAY') {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be an arrayref, not " . ref($value));
							}
						} elsif(scalar(@{$value}) < $rule_value) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must have at least $rule_value member" . (($rule_value > 1) ? 's' : ''));
							}
							$invalid_args{$key} = 1;
						}
					} elsif($type eq 'hashref') {
						if(!defined($value)) {
							next;	# Skip if hash is undefined
						}
						if(scalar(keys(%{$value})) < $rule_value) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must contain at least $rule_value keys");
							}
							$invalid_args{$key} = 1;
						}
					} elsif(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) {
						if(!defined($value)) {
							next;	# Skip if hash is undefined
						}
						if(Scalar::Util::looks_like_number($value)) {
							if($value < $rule_value) {
								if($rules->{'error_msg'}) {
									_error($logger, $rules->{'error_msg'});
								} elsif(($type eq 'integer') && ($value == 0)) {
									_error($logger, "$rule_description: Parameter '$key' ($value) must be a positive number");
								} elsif(($type eq 'integer') && ($value == 1)) {
									_error($logger, "$rule_description: Parameter '$key' ($value) must be a positive, non-zero number");
								} else {
									_error($logger, "$rule_description: Parameter '$key' ($value) must be at least $rule_value");
								}
								$invalid_args{$key} = 1;
								next;
							}
						} else {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must be a number");
							}
							next;
						}
					} else {
						_error($logger, "$rule_description: Parameter '$key' of type '$type' has meaningless min value $rule_value");
					}
				} elsif($rule_name eq 'max') {
					if(!defined($rules->{'type'})) {
						_error($logger, "$rule_description: Don't know type of '$key' to determine its maximum value $rule_value");
					}
					my $type = lc($rules->{'type'});
					if(exists($custom_types->{$type}->{'max'})) {
						$rule_value = $custom_types->{$type}->{'max'};
						$type = $custom_types->{$type}->{'type'};
					}
					if(($type eq 'string') || ($type eq 'str') || ($type eq 'stringref')) {
						if(!defined($value)) {
							next;	# Skip if string is undefined
						}
						if(defined(my $len = _number_of_characters($value))) {
							if($len > $rule_value) {
								_error($logger, $rules->{'error_msg'} || "$rule_description: String parameter '$key' too long, ($len characters), must be no longer than $rule_value");
								$invalid_args{$key} = 1;
							}
						} else {
							_error($logger, $rules->{'error_msg'} || "$rule_description: '$key' can't be decoded");
							$invalid_args{$key} = 1;
						}
					} elsif($type eq 'arrayref') {
						if(!defined($value)) {
							next;	# Skip if string is undefined
						}
						if(ref($value) ne 'ARRAY') {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must be an arrayref, not " . ref($value));
							}
						}
						if(scalar(@{$value}) > $rule_value) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must contain no more than $rule_value items");
							}
							$invalid_args{$key} = 1;
						}
					} elsif($type eq 'hashref') {
						if(!defined($value)) {
							next;	# Skip if hash is undefined
						}
						if(scalar(keys(%{$value})) > $rule_value) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' must contain no more than $rule_value keys");
							}
							$invalid_args{$key} = 1;
						}
					} elsif(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) {
						if(!defined($value)) {
							next;	# Skip if hash is undefined
						}
						if(Scalar::Util::looks_like_number($value)) {
							if($value > $rule_value) {
								if($rules->{'error_msg'}) {
									_error($logger, $rules->{'error_msg'});
								} elsif(($type eq 'integer') && ($value == 0)) {
									_error($logger, "$rule_description: Parameter '$key' ($value) must be a negative number");
								} elsif(($type eq 'integer') && ($value == -1)) {
									_error($logger, "$rule_description: Parameter '$key' ($value) must be a negative, non-zero number");
								} else {
									_error($logger, "$rule_description: Parameter '$key' ($value) must be no more than $rule_value");
								}
								$invalid_args{$key} = 1;
								next;
							}
						} else {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must be a number");
							}
							next;
						}
					} else {
						_error($logger, "$rule_description: Parameter '$key' of type '$type' has meaningless max value $rule_value");
					}
				} elsif(($rule_name eq 'matches') || ($rule_name eq 'regex')) {
					if(!defined($value)) {
						next;	# Skip if string is undefined
					}
					eval {
						my $re = (ref($rule_value) eq 'Regexp') ? $rule_value : qr/\Q$rule_value\E/;
						if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
							my @matches = grep { $_ =~ $re } @{$value};
							if(scalar(@matches) != scalar(@{$value})) {
								if($rules->{'error_msg'}) {
									_error($logger, $rules->{'error_msg'});
								} else {
									_error($logger, "$rule_description: All members of parameter '$key' [", join(', ', @{$value}), "] must match pattern '$rule_value'");
								}
							}
						} elsif($value !~ $re) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must match pattern '$re'");
							}
						}
						1;
					};
					if($@) {
						if($rules->{'error_msg'}) {
							_error($logger, $rules->{'error_msg'});
						} else {
							_error($logger, "$rule_description: Parameter '$key' regex '$rule_value' error: $@");
						}
						$invalid_args{$key} = 1;
					}
				} elsif($rule_name eq 'nomatch') {
					if(!defined($value)) {
						next;	# Skip if string is undefined
					}
					if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
						my @matches = grep { /$rule_value/ } @{$value};
						if(scalar(@matches)) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: No member of parameter '$key' [", join(', ', @{$value}), "] must match pattern '$rule_value'");
							}
						}
					} elsif($value =~ $rule_value) {
						if($rules->{'error_msg'}) {
							_error($logger, $rules->{'error_msg'});
						} else {
							_error($logger, "$rule_description: Parameter '$key' ($value) must not match pattern '$rule_value'");
						}
						$invalid_args{$key} = 1;
					}
				} elsif(($rule_name eq 'memberof') || ($rule_name eq 'enum') || ($rule_name eq 'values')) {
					if(!defined($value)) {
						next;	# Skip if string is undefined
					}
					if(ref($rule_value) eq 'ARRAY') {
						my $ok = 1;
						if(($rules->{'type'} eq 'integer') || ($rules->{'type'} eq 'number') || ($rules->{'type'} eq 'float')) {
							unless(List::Util::any { $_ == $value } @{$rule_value}) {
								$ok = 0;
							}
						} else {
							my $l = lc($value);
							unless(List::Util::any { (!defined($rules->{'case_sensitive'}) || ($rules->{'case_sensitive'} == 1)) ? $_ eq $value : lc($_) eq $l } @{$rule_value}) {
								$ok = 0;
							}
						}

						if(!$ok) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must be one of ", join(', ', @{$rule_value}));
							}
							$invalid_args{$key} = 1;
						}
					} else {
						if($rules->{'error_msg'}) {
							_error($logger, $rules->{'error_msg'});
						} else {
							_error($logger, "$rule_description: Parameter '$key' rule ($rule_value) must be an array reference");
						}
					}
				} elsif($rule_name eq 'notmemberof') {
					if(!defined($value)) {
						next;	# Skip if string is undefined
					}
					if(ref($rule_value) eq 'ARRAY') {
						my $ok = 1;
						if(($rules->{'type'} eq 'integer') || ($rules->{'type'} eq 'number') || ($rules->{'type'} eq 'float')) {
							if(List::Util::any { $_ == $value } @{$rule_value}) {
								$ok = 0;
							}
						} else {
							my $l = lc($value);
							if(List::Util::any { (!defined($rules->{'case_sensitive'}) || ($rules->{'case_sensitive'} == 1)) ? $_ eq $value : lc($_) eq $l } @{$rule_value}) {
								$ok = 0;
							}
						}

						if(!$ok) {
							if($rules->{'error_msg'}) {
								_error($logger, $rules->{'error_msg'});
							} else {
								_error($logger, "$rule_description: Parameter '$key' ($value) must not be one of ", join(', ', @{$rule_value}));
							}
							$invalid_args{$key} = 1;
						}
					} else {
						if($rules->{'error_msg'}) {
							_error($logger, $rules->{'error_msg'});
						} else {
							_error($logger, "$rule_description: Parameter '$key' rule ($rule_value) must be an array reference");
						}
					}
				} elsif($rule_name eq 'isa') {
					if(!defined($value)) {
						next;	# Skip if object not given
					}
					if($rules->{'type'} eq 'object') {
						if(!$value->isa($rule_value)) {
							_error($logger, "$rule_description: Parameter '$key' must be a '$rule_value' object got a " . (ref($value) ? ref($value) : $value) . ' object instead');
							$invalid_args{$key} = 1;
						}
					} else {
						_error($logger, "$rule_description: Parameter '$key' has meaningless isa value $rule_value");
					}
				} elsif($rule_name eq 'can') {
					if(!defined($value)) {
						next;	# Skip if object not given
					}
					if($rules->{'type'} eq 'object') {
						if(ref($rule_value) eq 'ARRAY') {
							# List of methods
							foreach my $method(@{$rule_value}) {
								if(!$value->can($method)) {
									_error($logger, "$rule_description: Parameter '$key' must be an object that understands the $method method");
									$invalid_args{$key} = 1;
								}
							}
						} elsif(!ref($rule_value)) {
							if(!$value->can($rule_value)) {
								_error($logger, "$rule_description: Parameter '$key' must be an object that understands the $rule_value method");
								$invalid_args{$key} = 1;
							}
						} else {
							_error($logger, "$rule_description: 'can' rule for Parameter '$key must be either a scalar or an arrayref");
						}
					} else {
						_error($logger, "$rule_description: Parameter '$key' has meaningless can value '$rule_value' for parameter type $rules->{type}");
					}
				} elsif($rule_name eq 'element_type') {
					if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
						my $type = $rule_value;
						my $custom_type = $custom_types->{$rule_value};
						if($custom_type && $custom_type->{'type'}) {
							$type = $custom_type->{'type'};
						}
						foreach my $member(@{$value}) {
							if($custom_type && $custom_type->{'transform'}) {
								# The custom type has a transform embedded within it
								if(ref($custom_type->{'transform'}) eq 'CODE') {
									$member = &{$custom_type->{'transform'}}($member);
								} else {
									_error($logger, "$rule_description: transforms must be a code ref");
									last;
								}
							}
							if(($type eq 'string') || ($type eq 'Str')) {
								if(ref($member)) {
									if($rules->{'error_msg'}) {
										_error($logger, $rules->{'error_msg'});
									} else {
										_error($logger, "$key can only contain strings");
									}
									$invalid_args{$key} = 1;
								}
							} elsif($type eq 'integer') {
								if(ref($member) || ($member =~ /\D/)) {
									if($rules->{'error_msg'}) {
										_error($logger, $rules->{'error_msg'});
									} else {
										_error($logger, "$key can only contain integers (found $member)");
									}
									$invalid_args{$key} = 1;
								}
							} elsif(($type eq 'number') || ($rule_value eq 'float')) {
								if(ref($member) || ($member !~ /^[-+]?(\d*\.\d+|\d+\.?\d*)$/)) {
									if($rules->{'error_msg'}) {
										_error($logger, $rules->{'error_msg'});
									} else {
										_error($logger, "$key can only contain numbers (found $member)");
									}
									$invalid_args{$key} = 1;
								}
							} else {
								_error($logger, "BUG: Add $type to element_type list");
							}
						}
					} else {
						_error($logger, "$rule_description: Parameter '$key' has meaningless element_type value $rule_value");
					}
				} elsif($rule_name eq 'optional') {
					# Already handled at the beginning of the loop
				} elsif($rule_name eq 'nullable') {
					# Already handled at the beginning of the loop (same as optional)
				} elsif($rule_name eq 'default') {
					# Handled earlier
				} elsif($rule_name eq 'error_msg') {
					# Handled inline
				} elsif($rule_name eq 'transform') {
					# Handled before the loop
				} elsif($rule_name eq 'case_sensitive') {
					# Handled inline
				} elsif($rule_name eq 'description') {
					# A la, Data::Processor
				} elsif($rule_name =~ /^_/) {
					# Ignore internal/metadata fields from schema extraction
				} elsif($rule_name eq 'semantic') {
					if($rule_value eq 'unix_timestamp') {
						if($value < 0 || $value > 2147483647) {
							_error($logger, "Invalid Unix timestamp: $value");
						}
					} else {
						_warn($logger, "semantic type $rule_value is not yet supported");
					}
				} elsif($rule_name eq 'schema') {
					# Nested schema Run the given schema against each element of the array
					if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {
						if(ref($value) eq 'ARRAY') {
							foreach my $member(@{$value}) {
								# Distinguish two schema forms:
								# (a) Rule hash   — has a top-level 'type' key, e.g. { type=>'string', matches=>qr/.../ }
								#     → validate each element against that rule directly.
								# (b) Field-schema hash — keys are field names whose values are rule hashes,
								#     e.g. { name=>{type=>'string'}, age=>{type=>'integer'} }
								#     → validate each hashref element against the field schema directly.
								my $is_field_schema = (ref($rule_value) eq 'HASH') && !exists($rule_value->{'type'});
								my %inner = (custom_types => $custom_types);
								if($is_field_schema) {
									$inner{input}  = $member;
									$inner{schema} = $rule_value;
								} else {
									$inner{input}  = { $key => $member };
									$inner{schema} = { $key => $rule_value };
								}
								if(!validate_strict(\%inner)) {
									$invalid_args{$key} = 1;
								}
							}
						} elsif(defined($value)) {	# Allow undef for optional values
							_error($logger, "$rule_description: nested schema: Parameter '$value' must be an arrayref");
						}
					} elsif($rules->{'type'} eq 'hashref') {
						if(ref($rule_value) eq 'HASH') {
							# Apply nested defaults before validation
							my $nested_with_defaults = _apply_nested_defaults($value, $rule_value);
							if(scalar keys(%{$nested_with_defaults})) {
								if(my $new_args = validate_strict({ input => $nested_with_defaults, schema => $rule_value, custom_types => $custom_types })) {
									$value = $new_args;
								} else {
									$invalid_args{$key} = 1;
								}
							}
						} else {
							_error($logger, "$rule_description: nested schema: Parameter '$value' must be an hashref");
						}
					} else {
						_error($logger, "$rule_description: Parameter '$key': 'schema' only supports arrayref and hashref, not $rules->{type}");
					}
				} elsif(($rule_name eq 'validate') || ($rule_name eq 'validator')) {
					if(ref($rule_value) eq 'CODE') {
						if(my $error = &{$rule_value}($args)) {
							_error($logger, "$rule_description: $key not valid: $error");
							$invalid_args{$key} = 1;
						}
					} else {
						# _error($logger, "$rule_description: Parameter '$key': 'validate' only supports coderef, not $value");
						_error($logger, "$rule_description: Parameter '$key': 'validate' only supports coderef, not " . ref($rule_value) // $rule_value);
					}
				} elsif ($rule_name eq 'callback') {
					# Custom validation code
					unless (defined &$rule_value) {
						_error($logger, "$rule_description: callback for '$key' must be a code reference");
					}
					my $res = $rule_value->($value, $args, $schema);
					unless ($res) {
						if($rules->{'error_msg'}) {
							_error($logger, $rules->{'error_msg'});
						} else {
							_error($logger, "$rule_description: Parameter '$key' failed custom validation");
						}
						$invalid_args{$key} = 1;
					}
				} elsif($rule_name eq 'position') {
					if($rule_value =~ /\D/) {
						_error($logger, "$rule_description: Parameter '$key': 'position' must be an integer");
					}
					if($rule_value < 0) {
						_error($logger, "$rule_description: Parameter '$key': 'position' must be a positive integer, not $value");
					}
				} else {
					_error($logger, "$rule_description: Unknown rule '$rule_name'");
				}
			}
		} elsif(ref($rules) eq 'ARRAY') {
			if(scalar(@{$rules})) {
				# An argument can be one of several different types.
				# This path handles both explicit array-of-rules schemas and the
				# normalised form of union type shorthand (type => ['a', 'b', ...]).
				my $rc = 0;
				my @types;
				foreach my $rule(@{$rules}) {
					if(ref($rule) ne 'HASH') {
						_error($logger, "$rule_description: Parameter '$key' rules must be a hash reference");
						next;
					}
					if(!defined($rule->{'type'})) {
						_error($logger, "$rule_description: Parameter '$key' is missing a type in an alternative");
						next;
					}
					push @types, $rule->{'type'};
					my $result;
					eval {
						$result = validate_strict({ input => { $key => $value }, schema => { $key => $rule }, logger => undef, custom_types => $custom_types });
					};
					if(!$@) {
						# Capture coercion performed by the successful sub-validation
						# (e.g. integer/number coercion) so the outer scope sees it.
						$value = $result->{$key} if(defined($result));
						$rc = 1;
						last;
					}
				}
				if(!$rc) {
					_error($logger, "$rule_description: Parameter: '$key': must be one of " . join(', ', @types));
					$invalid_args{$key} = 1;
				}
			} else {
				_error($logger, "$rule_description: Parameter: '$key': schema is empty arrayref");
			}
		} elsif(ref($rules)) {
			_error($logger, 'rules must be a hash reference or string');
		}

		$validated_args{$key} = $value;
	}

	# Validate parameter relationships
	if (my $relationships = $params->{'relationships'}) {
		_validate_relationships(\%validated_args, $relationships, $logger, $schema_description);
	}

	if(my $cross_validation = $params->{'cross_validation'}) {
		foreach my $validator_name(keys %{$cross_validation}) {
			my $validator = $cross_validation->{$validator_name};
			if((!ref($validator)) || (ref($validator) ne 'CODE')) {
				_error($logger, "$schema_description: cross_validation $validator is not a code snippet");
				next;
			}
			if(my $error = &{$validator}(\%validated_args, $validator)) {
				_error($logger, $error);
				# We have no idea which parameters are still valid, so let's invalidate them all
				return;
			}
		}
	}

	foreach my $key(keys %invalid_args) {
		delete $validated_args{$key};
	}

	if($are_positional_args == 1) {
		my @rc;
		foreach my $key (keys %{$schema}) {
			# Use exists() rather than if(my $value = ...) so that falsy but
			# valid coerced values (integer 0, empty string, undef from an
			# absent optional) are not silently dropped from the return array.
			if(exists $validated_args{$key}) {
				my $value = delete $validated_args{$key};
				my $position = $schema->{$key}->{'position'};
				if(defined($rc[$position])) {
					_error($logger, "$schema_description: $key: position $position appears twice");
				}
				$rc[$position] = $value;
			}
		}
		return \@rc;
	}
	return \%validated_args;
}

# _schema_from_arrayref($arrayref, $logger)
#
# Normalise an arrayref schema:
#   [ { name => 'param', type => 'string', ... }, ... ]
# to the standard named-parameter hashref form:
#   { param => { type => 'string', ... }, ... }
#
# The 'name' key is consumed during conversion and does not become a rule.
# Croaks if any element is not a hashref, is missing 'name', or if a name
# appears more than once.
sub _schema_from_arrayref
{
	my ($arrayref, $logger) = @_;

	my %schema;
	foreach my $spec (@{$arrayref}) {
		_error($logger, "validate_strict: each arrayref schema element must be a hashref")
			unless ref($spec) eq 'HASH';
		_error($logger, "validate_strict: arrayref schema element must have a 'name' key")
			unless exists($spec->{'name'});
		my %rule = %{$spec};
		my $name = delete $rule{'name'};
		_error($logger, "validate_strict: duplicate parameter '$name' in arrayref schema")
			if exists($schema{$name});
		$schema{$name} = \%rule;
	}
	return \%schema;
}

# Return number of visible characters not number of bytes
# Ensure string is decoded into Perl characters
sub _number_of_characters
{
	my $value = $_[0];

	return if(!defined($value));

	if($value !~ /[^[:ascii:]]/) {
		return length($value);
	}
	# Decode only if it's not already a Perl character string
	$value = decode_utf8($value) unless utf8::is_utf8($value);

	# Count grapheme clusters (visible characters)
	# The pseudo-operator () = forces list context to count matches
	# return scalar( () = $value =~ /\X/g );

	return Unicode::GCString->new($value)->length();
}

sub _apply_nested_defaults {
	my ($input, $schema) = @_;
	my %result = %$input;

	foreach my $key (keys %$schema) {
		my $rules = $schema->{$key};

		if (ref $rules eq 'HASH' && exists $rules->{default} && !exists $result{$key}) {
			$result{$key} = $rules->{default};
		}

		# Recursively handle nested schema
		if((ref $rules eq 'HASH') && $rules->{schema} && (ref $result{$key} eq 'HASH')) {
			$result{$key} = _apply_nested_defaults($result{$key}, $rules->{schema});
		}
	}

	return \%result;
}

sub _validate_relationships {
	my ($validated_args, $relationships, $logger, $description) = @_;

	return unless ref($relationships) eq 'ARRAY';

	foreach my $rel (@$relationships) {
		my $type = $rel->{type} or next;

		if ($type eq 'mutually_exclusive') {
			_validate_mutually_exclusive($validated_args, $rel, $logger, $description);
		} elsif ($type eq 'required_group') {
			_validate_required_group($validated_args, $rel, $logger, $description);
		} elsif ($type eq 'conditional_requirement') {
			_validate_conditional_requirement($validated_args, $rel, $logger, $description);
		} elsif ($type eq 'dependency') {
			_validate_dependency($validated_args, $rel, $logger, $description);
		} elsif ($type eq 'value_constraint') {
			_validate_value_constraint($validated_args, $rel, $logger, $description);
		} elsif ($type eq 'value_conditional') {
			_validate_value_conditional($validated_args, $rel, $logger, $description);
		} else {
			_error($logger, "Unknown relationship type $type");
		}
	}
}

sub _validate_mutually_exclusive {
	my ($args, $rel, $logger, $description) = @_;

	my @params = @{$rel->{params} || []};
	return unless @params >= 2;

	my @present = grep { exists($args->{$_}) && defined($args->{$_}) } @params;

	if (@present > 1) {
		my $msg = $rel->{description} || 'Cannot specify both ' . join(' and ', @present);
		_error($logger, "$description: $msg");
	}
}

sub _validate_required_group {
	my ($args, $rel, $logger, $description) = @_;

	my @params = @{$rel->{params} || []};
	return unless @params >= 2;

	my @present = grep { exists($args->{$_}) && defined($args->{$_}) } @params;

	if (@present == 0) {
		my $msg = $rel->{description} ||
			'Must specify at least one of: ' . join(', ', @params);
		_error($logger, "$description: $msg");
	}
}

sub _validate_conditional_requirement {
	my ($args, $rel, $logger, $description) = @_;

	my $if_param = $rel->{if} or return;
	my $then_param = $rel->{then_required} or return;

	# If the condition parameter is present and defined
	if (exists($args->{$if_param}) && defined($args->{$if_param})) {
		# Check if it's truthy (for booleans and general values)
		if ($args->{$if_param}) {
			# Then the required parameter must also be present
			unless (exists($args->{$then_param}) && defined($args->{$then_param})) {
				my $msg = $rel->{description} || "When $if_param is specified, $then_param is required";
				_error($logger, "$description: $msg");
			}
		}
	}
}

sub _validate_dependency {
	my ($args, $rel, $logger, $description) = @_;

	my $param = $rel->{param} or return;
	my $requires = $rel->{requires} or return;

	# If param is present, requires must also be present
	if (exists($args->{$param}) && defined($args->{$param})) {
		unless (exists($args->{$requires}) && defined($args->{$requires})) {
			my $msg = $rel->{description} || "$param requires $requires to be specified";
			_error($logger, "$description: $msg");
		}
	}
}

sub _validate_value_constraint {
	my ($args, $rel, $logger, $description) = @_;

	my $if_param = $rel->{if} or return;
	my $then_param = $rel->{then} or return;
	my $operator = $rel->{operator} or return;
	my $value = $rel->{value};
	return unless defined $value;

	# If the condition parameter is present and truthy
	if (exists($args->{$if_param}) && defined($args->{$if_param}) && $args->{$if_param}) {
		# Check if the then parameter exists
		if (exists($args->{$then_param}) && defined($args->{$then_param})) {
			my $actual = $args->{$then_param};
			my $valid = 0;

			if ($operator eq '==') {
				$valid = ($actual == $value);
			} elsif ($operator eq '!=') {
				$valid = ($actual != $value);
			} elsif ($operator eq '<') {
				$valid = ($actual < $value);
			} elsif ($operator eq '<=') {
				$valid = ($actual <= $value);
			} elsif ($operator eq '>') {
				$valid = ($actual > $value);
			} elsif ($operator eq '>=') {
				$valid = ($actual >= $value);
			}

			unless ($valid) {
				my $msg = $rel->{description} || "When $if_param is specified, $then_param must be $operator $value (got $actual)";
				_error($logger, "$description: $msg");
			}
		}
	}
}

sub _validate_value_conditional {
	my ($args, $rel, $logger, $description) = @_;

	my $if_param = $rel->{if} or return;
	my $equals = $rel->{equals};
	my $then_param = $rel->{then_required} or return;
	return unless defined $equals;

	# If the parameter has the specific value
	if (exists($args->{$if_param}) && defined($args->{$if_param})) {
		if ($args->{$if_param} eq $equals) {
			# Then the required parameter must be present
			unless (exists($args->{$then_param}) && defined($args->{$then_param})) {
				my $msg = $rel->{description} ||
					"When $if_param equals '$equals', $then_param is required";
				_error($logger, "$description: $msg");
			}
		}
	}
}

# Helper to log error or croak
sub _error
{
	my $logger = shift;
	my $message = join('', @_);
	# Strip ASCII control characters to prevent log-injection / CRLF attacks
	# when user-supplied values appear in the message.
	$message =~ s/[[:cntrl:]]/ /g;

	my @call_details = caller(0);
	if($logger) {
		$logger->error(__PACKAGE__, ' line ', $call_details[2], ": $message");
	}
	croak(__PACKAGE__, ' line ', $call_details[2], ": $message");
	# Be absolutely sure, sometimes croak doesn't die for me in Test::Most scripts
	die (__PACKAGE__, ' line ', $call_details[2], ": $message");
}

# Helper to log warning or carp
sub _warn
{
	my $logger = shift;
	my $message = join('', @_);
	# Strip ASCII control characters to prevent log-injection / CRLF attacks.
	$message =~ s/[[:cntrl:]]/ /g;

	if($logger) {
		$logger->warn(__PACKAGE__, ": $message");
	} else {
		carp(__PACKAGE__, ": $message");
	}
}

=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 | scalar | scalarref | stringref | arrayref | hashref | coderef | object

    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;
        can: METHOD_NAME
    ]

    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

=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>

=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

1;

__END__
