lib/Params/Validate/Strict.pm

Structural Coverage (Approximate)

TER1 (Statement): 90.61%
TER2 (Branch): 92.40%
TER3 (LCSAJ): 100.0% (39/39)
Approximate LCSAJ segments: 975

LCSAJ Legend

● Covered — this LCSAJ path was executed during testing.

● Not covered — this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start → end → jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    1: package Params::Validate::Strict;
    2: 
    3: use strict;
    4: use warnings;
    5: 
    6: use Carp ();
    7: use Exporter qw(import);	# Required for @EXPORT_OK
    8: use Encode qw(decode_utf8);
    9: use List::Util 1.33 qw(all any);	# Required for memberof/matches validation
   10: use Readonly::Values::Boolean;
   11: use Scalar::Util;
   12: 
   13: our @ISA = qw(Exporter);
   14: our @EXPORT_OK = qw(validate_strict compile_schema);
   15: 
   16: =head1 NAME
   17: 
   18: Params::Validate::Strict - Validates a set of parameters against a schema
   19: 
   20: =head1 VERSION
   21: 
   22: Version 0.43
   23: 
   24: =cut
   25: 
   26: our $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.
   31: our $_depth = 0;
   32: 
   33: # Type codes used by compiled schemas (see _compile_schema).  Numeric codes
   34: # keep the per-call dispatch to integer comparisons.
   35: use constant {
   36: 	_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: };
   46: 
   47: =head1 SYNOPSIS
   48: 
   49:     my $schema = {
   50:         username => { type => 'string', min => 3, max => 50 },
   51:         age => { type => 'integer', min => 0, max => 150 },
   52:     };
   53: 
   54:     my $input = {
   55:          username => 'john_doe',
   56:          age => '30',	# Will be coerced to integer
   57:     };
   58: 
   59:     my $validated_input = validate_strict(schema => $schema, input => $input);
   60: 
   61:     if(defined($validated_input)) {
   62:         print "Example 1: Validation successful!\n";
   63:         print 'Username: ', $validated_input->{username}, "\n";
   64:         print 'Age: ', $validated_input->{age}, "\n";	# It's an integer now
   65:     } else {
   66:         print "Example 1: Validation failed: $@\n";
   67:     }
   68: 
   69: Upon first reading this may seem overly complex and full of scope creep in a sledgehammer to crack a nut sort of way,
   70: however two use cases make use of the extensive logic that comes with this code
   71: and I have a couple of other reasons for writing it.
   72: 
   73: =over 4
   74: 
   75: =item * Black Box Testing
   76: 
   77: The schema can be plumbed into L<App::Test::Generator> to automatically create a set of black-box test cases.
   78: 
   79: =item * WAF
   80: 
   81: The schema can be plumbed into a WAF,
   82: e.g., L<VWF|https://github.com/nigelhorne/VWF/>,
   83: to protect from random user input.
   84: 
   85: =item * Improved API Documentation
   86: 
   87: Even if you don't use this module,
   88: the specification syntax can help with documentation.
   89: 
   90: =item * I like it
   91: 
   92: I found it fun to write this,
   93: even if nobody else finds it useful,
   94: though I hope you will.
   95: 
   96: =back
   97: 
   98: =head1	METHODS
   99: 
  100: =head2 validate_strict
  101: 
  102: Validates a set of parameters against a schema.
  103: 
  104: This function takes two mandatory arguments:
  105: 
  106: =over 4
  107: 
  108: =item * C<schema> || C<members>
  109: 
  110: A reference to a hash that defines the validation rules for each parameter.
  111: 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.
  112: 
  113: As an alternative the schema may be supplied as an B<arrayref of parameter hashrefs>,
  114: where every element describes one parameter and carries a mandatory
  115: C<name> key:
  116: 
  117:   $schema = [
  118:     { name => 'username', type => 'string', min => 3, max => 50 },
  119:     { name => 'age',      type => 'integer', min => 0, max => 150 },
  120:     { name => 'role',     type => 'string', optional => 1, default => 'user' },
  121:   ];
  122: 
  123: The arrayref form is normalised to the standard hashref form before any further
  124: processing.  It is particularly useful when declaration order matters (e.g.
  125: for positional or mixed calling conventions used by some CPAN modules).  The
  126: C<name> key is consumed during normalisation and does not appear as a
  127: validation rule.
  128: 
  129: For some sort of compatibility with L<Data::Processor>,
  130: it is possible to wrap the schema within a hash like this:
  131: 
  132:   $schema = {
  133:     description => 'Describe what this schema does',
  134:     error_msg => 'An error message',
  135:     schema => {
  136:       # ... schema goes here
  137:     }
  138:   }
  139: 
  140: =item * C<args> || C<input>
  141: 
  142: A reference to a hash containing the parameters to be validated.
  143: The keys of the hash are the parameter names, and the values are the parameter values.
  144: 
  145: =back
  146: 
  147: It takes optional arguments:
  148: 
  149: =over 4
  150: 
  151: =item * C<description>
  152: 
  153: What the schema does,
  154: used in error messages.
  155: 
  156: =item * C<error_msg>
  157: 
  158: Overrides the default message when something doesn't validate.
  159: 
  160: =item * C<unknown_parameter_handler>
  161: 
  162: This parameter describes what to do when a parameter is given that is not in the schema of valid parameters.
  163: It must be one of C<die>, C<warn>, or C<ignore>.
  164: 
  165: It defaults to C<die> unless C<carp_on_warn> is given, in which case it defaults to C<warn>.
  166: 
  167: =item * C<logger>
  168: 
  169: A logging object that understands messages such as C<error> and C<warn>.
  170: 
  171: =item * C<custom_types>
  172: 
  173: A reference to a hash that defines reusable custom types.
  174: Custom types allow you to define validation rules once and reuse them throughout your schema,
  175: making your validation logic more maintainable and readable.
  176: 
  177: Each custom type is defined as a hash reference containing the same validation rules available for regular parameters
  178: (C<type>, C<min>, C<max>, C<matches>, C<memberof>, C<values>, C<enum>, C<notmemberof>, C<callback>, etc.).
  179: 
  180:   my $custom_types = {
  181:     email => {
  182:       type => 'string',
  183:       matches => qr/^[^@\s]+\@[^@\s]+\.[^@\s]+$/,
  184:       error_msg => 'Invalid email address format'
  185:     }, phone => {
  186:       type => 'string',
  187:       matches => qr/^\+?[1-9]\d{1,14}$/,
  188:       min => 10,
  189:       max => 15
  190:     }, percentage => {
  191:       type => 'number',
  192:       min => 0,
  193:       max => 100
  194:     }, status => {
  195:       type => 'string',
  196:       memberof => ['draft', 'published', 'archived']
  197:     }
  198:   };
  199: 
  200:   my $schema = {
  201:     user_email => { type => 'email' },
  202:     contact_number => { type => 'phone', optional => 1 },
  203:     completion => { type => 'percentage' },
  204:     post_status => { type => 'status' }
  205:   };
  206: 
  207:   my $validated = validate_strict(
  208:     schema => $schema,
  209:     input => $input,
  210:     custom_types => $custom_types
  211:   );
  212: 
  213: Custom types can be extended or overridden in the schema by specifying additional constraints:
  214: 
  215:   my $schema = {
  216:     admin_username => {
  217:       type => 'username',  # Uses custom type definition
  218:       min => 5,            # Overrides custom type's min value
  219:       max => 15            # Overrides custom type's max value
  220:     }
  221:   };
  222: 
  223: Custom types work seamlessly with nested schema, optional parameters, and all other validation features.
  224: 
  225: =back
  226: 
  227: The schema can define the following rules for each parameter:
  228: 
  229: =over 4
  230: 
  231: =item * C<type>
  232: 
  233: The data type of the parameter.
  234: 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>.
  235: C<scalar> accepts any plain scalar value (string, number, boolean, etc.) but rejects references (arrayrefs, hashrefs, coderefs, objects).
  236: C<scalarref> accepts a reference to a scalar value (e.g. C<\$var>) but rejects plain scalars, arrayrefs, hashrefs, coderefs, and objects.
  237: 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.
  238: C<void> asserts that the parameter value is C<undef> (the parameter represents a void return or absent output).
  239: When C<void> is used the schema must contain exactly one parameter.
  240: The C<min>/C<max> constraints apply to the B<length> (in characters) of the referenced string.
  241: All other string rules (C<matches>, C<nomatch>, C<memberof>, etc.) operate on the dereferenced string value.
  242: The validated return value is the dereferenced plain string.
  243: C<regex> accepts a compiled regular expression (C<qr//> object); the value is returned unchanged.
  244: 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.
  245: C<arraylike> accepts an array reference or a blessed object that overloads C<@{}> array dereferencing.
  246: C<hashlike> accepts a hash reference or a blessed object that overloads C<%{}> hash dereferencing.
  247: C<codelike> accepts a code reference or a blessed object that overloads C<&{}> code dereferencing.
  248: 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'>).
  249: 
  250: A type can be an arrayref when a parameter could have different types (e.g. a string or an object).
  251: 
  252:   $schema = {
  253:     username => [
  254:       { type => 'string', min => 3, max => 50 },	# Name
  255:       { type => 'integer', 'min' => 1 },	# UID that isn't root
  256:     ]
  257:   };
  258: 
  259: As a shorthand, C<type> itself may be an arrayref of type name strings (a I<union type>),
  260: or a pipe-separated string, when all other constraints are shared between the alternatives:
  261: 
  262:   $schema = {
  263:     data => { type => ['string', 'arrayref'] },
  264:     id   => { type => 'string|integer', optional => 1 },
  265:   };
  266: 
  267: This is equivalent to the full array-of-rules form but more concise.
  268: Whitespace around the C<|> is ignored, so C<'string | arrayref'> is the same as C<'string|arrayref'>.
  269: Every other key in the rule hash (C<optional>, C<min>, C<max>, C<matches>, etc.)
  270: is inherited by each candidate type and validated independently against it.
  271: Type names are tried left-to-right; the first match wins and its coercion
  272: (e.g. numeric types) is propagated back to the caller.
  273: If the value fails all candidate types, validation croaks with a message
  274: listing the union members.
  275: 
  276: =item * C<can>
  277: 
  278: The parameter must be an object, or with C<type =E<gt> 'invocant'> an object or a class name,
  279: that understands the method C<can>.
  280: C<can> can be a simple scalar string of a method name,
  281: or an arrayref of a list of method names, all of which must be supported by the object.
  282: 
  283:    $schema = {
  284:      gedcom => { type => object, can => 'get_individual' }
  285:    }
  286: 
  287: =item * C<isa>
  288: 
  289: The parameter must be an object of type C<isa>.
  290: Requires C<type =E<gt> 'object'>.
  291: 
  292: =item * C<does>
  293: 
  294: The parameter must be a blessed object that satisfies the role via C<-E<gt>DOES>.
  295: Requires C<type =E<gt> 'object'>.
  296: 
  297:   handler => { type => 'object', does => 'My::Role::Printable' }
  298: 
  299: =item * C<classcan>
  300: 
  301: The parameter must be a string holding a syntactically valid Perl class name
  302: whose class understands the given method (or every method in an arrayref).
  303: The check is always a C<-E<gt>can> method call, so an overridden C<can> is respected.
  304: The class must already be loaded.
  305: Symmetric with C<classisa> and C<classdoes>.
  306: 
  307:   backend => { type => 'string', classcan => ['connect', 'disconnect'] }
  308: 
  309: =item * C<element_isa>
  310: 
  311: Requires C<type =E<gt> 'arrayref'>.
  312: Every element must be a blessed object that passes C<-E<gt>isa('Base::Class')>.
  313: An empty arrayref is accepted; add C<min =E<gt> 1> to require at least one element.
  314: Unlike C<element_type =E<gt> 'object'>, this checks the inheritance chain, not just blessedness.
  315: 
  316:   handlers => { type => 'arrayref', min => 1, element_isa => 'My::Handler' }
  317: 
  318: =item * C<needs>
  319: 
  320: A parameter name, or an arrayref of names, that must also be given whenever this parameter is.
  321: A shorthand for one C<dependency> relationship per name (see C<relationships>).
  322: 
  323:   user => { type => 'string', optional => 1, needs => ['password', 'realm'] }
  324: 
  325: =item * C<classisa>
  326: 
  327: The parameter must be a string holding a syntactically valid Perl class name
  328: that passes C<-E<gt>isa('Base::Class')>.
  329: The class must already be loaded (its C<@ISA> must be reachable).
  330: Does not accept blessed object references; use C<isa> for those.
  331: 
  332:   backend => { type => 'string', classisa => 'My::Backend::Base' }
  333: 
  334: =item * C<subclass>
  335: 
  336: Like C<classisa>, but requires a I<strict> subclass: the value must not equal
  337: the base class name itself.
  338: 
  339:   plugin => { type => 'string', subclass => 'My::Plugin::Base' }
  340: 
  341: =item * C<classdoes>
  342: 
  343: Like C<classisa>, but tests C<-E<gt>DOES> (role consumption) instead of C<-E<gt>isa>.
  344: 
  345:   consumer => { type => 'string', classdoes => 'My::Role::Loggable' }
  346: 
  347: =item * C<driver>
  348: 
  349: The parameter must be a valid class name that: (1) can be loaded via C<require>,
  350: and (2) passes C<-E<gt>isa('Base::Class')>.
  351: The module is actually loaded as a side effect of validation.
  352: 
  353:   store => { type => 'string', driver => 'Cache::Store' }
  354: 
  355: =item * C<memberof>
  356: 
  357: The parameter must be a member of the given arrayref.
  358: 
  359:   status => {
  360:     type => 'string',
  361:     memberof => ['draft', 'published', 'archived']
  362:   }
  363: 
  364:   priority => {
  365:     type => 'integer',
  366:     memberof => [1, 2, 3, 4, 5]
  367:   }
  368: 
  369: For string types, the comparison is case-sensitive by default. Use the C<case_sensitive>
  370: flag to control this behavior:
  371: 
  372:   # Case-sensitive (default) - must be exact match
  373:   code => {
  374:     type => 'string',
  375:     memberof => ['ABC', 'DEF', 'GHI']
  376:     # 'abc' will fail
  377:   }
  378: 
  379:   # Case-insensitive - any case accepted
  380:   code => {
  381:     type => 'string',
  382:     memberof => ['ABC', 'DEF', 'GHI'],
  383:     case_sensitive => 0
  384:     # 'abc', 'Abc', 'ABC' all pass, original case preserved
  385:   }
  386: 
  387: For numeric types (C<integer>, C<number>, C<float>), the comparison uses numeric
  388: equality (C<==> operator):
  389: 
  390:   rating => {
  391:     type => 'number',
  392:     memberof => [0.5, 1.0, 1.5, 2.0]
  393:   }
  394: 
  395: Note that C<memberof> cannot be combined with C<min> or C<max> constraints as they
  396: serve conflicting purposes - C<memberof> defines an explicit whitelist while C<min>/C<max>
  397: define ranges.
  398: 
  399: =item * C<enum>
  400: 
  401: Same as C<memberof>.
  402: 
  403: =item * C<values>
  404: 
  405: Same as C<memberof>.
  406: 
  407: =item * C<notmemberof>
  408: 
  409: The parameter must not be a member of the given arrayref (blacklist).
  410: This is the inverse of C<memberof>.
  411: 
  412:   username => {
  413:     type => 'string',
  414:     notmemberof => ['admin', 'root', 'system', 'administrator']
  415:   }
  416: 
  417:   port => {
  418:     type => 'integer',
  419:     notmemberof => [22, 23, 25, 80, 443]  # Reserved ports
  420:   }
  421: 
  422: Like C<memberof>, string comparisons are case-sensitive by default but can be controlled
  423: with the C<case_sensitive> flag:
  424: 
  425:   # Case-sensitive (default)
  426:   username => {
  427:     type => 'string',
  428:     notmemberof => ['Admin', 'Root']
  429:     # 'admin' would pass, 'Admin' would fail
  430:   }
  431: 
  432:   # Case-insensitive
  433:   username => {
  434:     type => 'string',
  435:     notmemberof => ['Admin', 'Root'],
  436:     case_sensitive => 0
  437:     # 'admin', 'ADMIN', 'Admin' all fail
  438:   }
  439: 
  440: The blacklist is checked after any C<transform> rules are applied, allowing you to
  441: normalize input before checking:
  442: 
  443:   username => {
  444:     type => 'string',
  445:     transform => sub { lc($_[0]) },  # Normalize to lowercase
  446:     notmemberof => ['admin', 'root', 'system']
  447:   }
  448: 
  449: C<notmemberof> can be combined with other validation rules:
  450: 
  451:   username => {
  452:     type => 'string',
  453:     notmemberof => ['admin', 'root', 'system'],
  454:     min => 3,
  455:     max => 20,
  456:     matches => qr/^[a-z0-9_]+$/
  457:   }
  458: 
  459: =item * C<case_sensitive>
  460: 
  461: A boolean value indicating whether string comparisons should be case-sensitive.
  462: This flag affects the C<memberof> and C<notmemberof> validation rules.
  463: The default value is C<1> (case-sensitive).
  464: 
  465: When set to C<0>, string comparisons are performed case-insensitively, allowing values
  466: with different casing to match. The original case of the input value is preserved in
  467: the validated output.
  468: 
  469:   # Case-sensitive (default)
  470:   status => {
  471:     type => 'string',
  472:     memberof => ['Draft', 'Published', 'Archived'] # Input 'draft' will fail - must match exact case
  473:   }
  474: 
  475:   # Case-insensitive
  476:   status => {
  477:     type => 'string',
  478:     memberof => ['Draft', 'Published', 'Archived'],
  479:     case_sensitive => 0 # Input 'draft', 'DRAFT', or 'DrAfT' will all pass
  480:   }
  481: 
  482:   country_code => {
  483:     type => 'string',
  484:     memberof => ['US', 'UK', 'CA', 'FR'],
  485:     case_sensitive => 0  # Accept 'us', 'US', 'Us', etc.
  486:   }
  487: 
  488: This flag has no effect on numeric types (C<integer>, C<number>, C<float>) as numbers
  489: do not have case.
  490: 
  491: =item * C<min>/C<minimum>
  492: 
  493: The minimum length (for strings in characters not bytes), value (for numbers) or number of keys (for hashrefs).
  494: 
  495: =item * C<max>
  496: 
  497: The maximum length (for strings in characters not bytes), value (for numbers) or number of keys (for hashrefs).
  498: 
  499: =item * C<matches>
  500: 
  501: A regular expression that the parameter value must match.
  502: Checks all members of arrayrefs.
  503: 
  504: =item * C<nomatch>
  505: 
  506: A regular expression that the parameter value must not match.
  507: Checks all members of arrayrefs.
  508: 
  509: =item * C<bnf>
  510: 
  511: An arrayref of BNF grammar lines that defines the set of strings the
  512: parameter value must belong to.
  513: The first rule in the grammar is the start rule; the value must match it
  514: exactly (anchored).
  515: 
  516: Each element is either a rule definition (C<< <name> ::= ... >>) or a
  517: continuation of the previous rule.  Terminals are double-quoted; non-terminals
  518: use angle brackets.  Alternatives are separated by C<|>.
  519: 
  520:   $schema = {
  521:     na_tel_no => {
  522:       type => 'string',
  523:       bnf  => [
  524:         '<telephone-number> ::= <country-code-opt> <area-code> <separator-opt>',
  525:         '<central-office-code> <separator-opt> <station-code>',
  526:         '<country-code-opt> ::= "" | "+1" | "1"',
  527:         '<separator-opt>    ::= "" | "-" | " " | "."',
  528:         '<area-code>        ::= <digit2-9> <digit0-9> <digit0-9>',
  529:         '<central-office-code> ::= <digit2-9> <digit0-9> <digit0-9>',
  530:         '<station-code>     ::= <digit0-9> <digit0-9> <digit0-9> <digit0-9>',
  531:         '<digit0-9> ::= "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"',
  532:         '<digit2-9> ::= "2"|"3"|"4"|"5"|"6"|"7"|"8"|"9"',
  533:       ],
  534:     },
  535:   };
  536: 
  537: Implemented by L<Params::Validate::Strict::BNF>.  Recursive grammars are not
  538: supported.
  539: 
  540: =item * C<position>
  541: 
  542: For routines and methods that take positional args,
  543: this integer value defines which position the argument will be in.
  544: If this is set for all arguments,
  545: C<validate_strict> will return a reference to an array, rather than a reference to a hash.
  546: 
  547: =item * C<slurp>
  548: 
  549: Valid only in positional-argument schemas (those where every parameter has a
  550: C<position> value).  When C<slurp =E<gt> 1> is set, this parameter collects
  551: I<all> remaining positional arguments starting from C<position> into an
  552: arrayref, rather than taking only the single element at that index.
  553: 
  554:   # sub log_message($level, @messages)
  555:   my $schema = {
  556:     level    => { type => 'string',   position => 0 },
  557:     messages => { type => 'arrayref', position => 1, slurp => 1 },
  558:   };
  559: 
  560: The slurp parameter is implicitly optional: if there are no arguments at or
  561: beyond C<position>, the value is an empty arrayref.  Combine with C<min =E<gt>
  562: 1> to require at least one element:
  563: 
  564:   messages => { type => 'arrayref', position => 1, slurp => 1, min => 1 }
  565: 
  566: At most one slurp parameter may be defined per schema, and it must have the
  567: highest C<position> value.  The return value at that position is an arrayref.
  568: 
  569: =item * C<aliases>
  570: 
  571: An arrayref of alternative input-key names that are also accepted for this
  572: parameter.  When any alias is found in the input the parameter is stored
  573: under its canonical schema key; if both the canonical name and an alias are
  574: present the canonical name takes precedence.  Aliases are not treated as
  575: unknown parameters regardless of the C<unknown_parameter_handler> setting.
  576: 
  577:   colour => {
  578:     type    => 'string',
  579:     aliases => ['color'],
  580:     memberof => ['red', 'green', 'blue'],
  581:   }
  582: 
  583: Only named (hashref) input supports aliases; positional (arrayref) input
  584: ignores them.
  585: 
  586: =item * C<regex>
  587: 
  588: Synonym of matches
  589: 
  590: =item * C<description>
  591: 
  592: The description of the rule
  593: 
  594: =item * C<callback>
  595: 
  596: A code reference to a subroutine that performs custom validation logic.
  597: The subroutine is called with four arguments: the parameter value, the argument list, the schema and the name of the parameter being validated
  598: (the canonical name, even if the value was supplied under an alias).
  599: It should return true if the value is valid, false otherwise.
  600: The name lets one callback be shared between several parameters.
  601: 
  602: Use this to test more complex examples:
  603: 
  604:   my $schema = {
  605:     even_number => {
  606:       type => 'integer',
  607:       callback => sub { $_[0] % 2 == 0 }
  608:   };
  609: 
  610:   # Specify the arguments for a routine which has a second, optional argument, which, if given, must be less than or equal to the first
  611:   my $schema = {
  612:     first => {
  613:       type => 'integer'
  614:     }, second => {
  615:       type => 'integer',
  616:       optional => 1,
  617:       callback => sub {
  618:         my($value, $args) = @_;
  619: 	# The 'defined' is needed in case 'second' is evaluated before 'first'
  620: 	return (defined($args->{first}) && $value <= $args->{first}) ? 1 : 0
  621:       }
  622:     }
  623:   };
  624: 
  625: =item * C<optional>
  626: 
  627: A boolean value indicating whether the parameter is optional.
  628: If true, the parameter is not required.
  629: If false or omitted, the parameter is required.
  630: 
  631: It can be a reference to a code snippet that will return true or false,
  632: to determine if the parameter is optional or not.
  633: The code will be called with two arguments: the value of the parameter and hash ref of all parameters:
  634: 
  635:   my $schema = {
  636:     optional_field => {
  637:       type => 'string',
  638:       optional => sub {
  639:         my ($value, $all_params) = @_;
  640:         return $all_params->{make_optional} ? 1 : 0;
  641:       }
  642:     },
  643:     make_optional => { type => 'boolean' }
  644:   };
  645: 
  646:   my $result = validate_strict(schema => $schema, input => { make_optional => 1 });
  647: 
  648: If the parameter is not optional, it can be passed an undef value, which will not flag an error.
  649: This is by design.
  650: So this will not say that the required parameter 's' is missing:
  651: 
  652:     validate_strict(
  653:         schema => { s => { type => 'string' } },
  654:         input  => { s => undef },
  655:     );
  656: 
  657: =item * C<default>
  658: 
  659: Populate missing optional parameters with the specified value.
  660: Note that this value is not validated.
  661: 
  662:   username => {
  663:     type => 'string',
  664:     optional => 1,
  665:     default => 'guest'
  666:   }
  667: 
  668: =item * C<element_type>
  669: 
  670: Extends the validation to individual elements of arrays.
  671: 
  672:   tags => {
  673:     type => 'arrayref',
  674:     element_type => 'number',	# Float means the same
  675:     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
  676:     max => 5
  677:   }
  678: 
  679: =item * C<error_msg>
  680: 
  681: The custom error message to be used in the event of a validation failure.
  682: 
  683:   age => {
  684:     type => 'integer',
  685:     min => 18,
  686:     error_msg => 'You must be at least 18 years old'
  687:   }
  688: 
  689: =item * C<nullable>
  690: 
  691: Like optional,
  692: though this cannot be a coderef,
  693: only a flag.
  694: 
  695: =item * C<schema>
  696: 
  697: You can validate nested hashrefs and arrayrefs using the C<schema> property:
  698: 
  699:     my $schema = {
  700:         user => {	# 'user' is a hashref
  701:             type => 'hashref',
  702:             schema => {	# Specify what the elements of the hash should be
  703:                 name => { type => 'string' },
  704:                 age => { type => 'integer', min => 0 },
  705:                 hobbies => {	# 'hobbies' is an array ref that this user has
  706:                     type => 'arrayref',
  707:                     schema => { type => 'string' }, # Validate each hobby
  708:                     min => 1 # At least one hobby
  709:                 }
  710:             }
  711:         }, metadata => {
  712:             type => 'hashref',
  713:             schema => {
  714:                 created => { type => 'string' },
  715:                 tags => {
  716:                     type => 'arrayref',
  717:                     schema => {
  718:                         type => 'string',
  719:                         matches => qr/^[a-z]+$/	# Or you can say matches => '^[a-z]+$'
  720:                     }
  721:                 }
  722:             }
  723:         }
  724:     };
  725: 
  726: =item * C<validate>
  727: 
  728: A snippet of code that validates the input.
  729: It's passed the input arguments,
  730: and return a string containing a reason for rejection,
  731: or undef if it's allowed.
  732: 
  733:     my $schema = {
  734:       user => {
  735:         type => 'string',
  736: 	validate => sub {
  737: 	  if($_[0]->{'password'} eq 'bar') {
  738: 	    return undef;
  739: 	  }
  740: 	  return 'Invalid password, try again';
  741: 	}
  742:       }, password => {
  743:          type => 'string'
  744:       }
  745:     };
  746: 
  747: =item * C<transform>
  748: 
  749: A code reference to a subroutine that transforms/sanitizes the parameter value before validation.
  750: The subroutine should accept the parameter value as an argument and return the transformed value.
  751: The transformation is applied before any validation rules are checked, allowing you to normalize
  752: or clean data before it is validated.
  753: 
  754: Common use cases include trimming whitespace, normalizing case, formatting phone numbers,
  755: sanitizing user input, and converting between data formats.
  756: 
  757:   # Simple string transformations
  758:   username => {
  759:     type => 'string',
  760:     transform => sub { lc(trim($_[0])) },  # lowercase and trim
  761:     matches => qr/^[a-z0-9_]+$/
  762:   }
  763: 
  764:   email => {
  765:     type => 'string',
  766:     transform => sub { lc(trim($_[0])) },  # normalize email
  767:     matches => qr/^[^@\s]+\@[^@\s]+\.[^@\s]+$/
  768:   }
  769: 
  770:   # Array transformations
  771:   tags => {
  772:     type => 'arrayref',
  773:     transform => sub { [map { lc($_) } @{$_[0]}] },  # lowercase all elements
  774:     element_type => 'string'
  775:   }
  776: 
  777:   keywords => {
  778:     type => 'arrayref',
  779:     transform => sub {
  780:       my @arr = map { lc(trim($_)) } @{$_[0]};
  781:       my %seen;
  782:       return [grep { !$seen{$_}++ } @arr];  # remove duplicates
  783:     }
  784:   }
  785: 
  786:   # Numeric transformations
  787:   quantity => {
  788:     type => 'integer',
  789:     transform => sub { int($_[0] + 0.5) },  # round to nearest integer
  790:     min => 1
  791:   }
  792: 
  793:   # Sanitization
  794:   slug => {
  795:     type => 'string',
  796:     transform => sub {
  797:       my $str = lc(trim($_[0]));
  798:       $str =~ s/[^\w\s-]//g;  # remove special characters
  799:       $str =~ s/\s+/-/g;      # replace spaces with hyphens
  800:       return $str;
  801:     },
  802:     matches => qr/^[a-z0-9-]+$/
  803:   }
  804: 
  805:   phone => {
  806:     type => 'string',
  807:     transform => sub {
  808:       my $str = $_[0];
  809:       $str =~ s/\D//g;  # remove all non-digits
  810:       return $str;
  811:     },
  812:     matches => qr/^\d{10}$/
  813:   }
  814: 
  815: The C<transform> function is applied to the value before any validation checks (C<min>/C<minimum>, C<max>,
  816: C<matches>, C<callback>, etc.), ensuring that validation rules are checked against the cleaned data.
  817: 
  818: Transformations work with all parameter types including nested structures:
  819: 
  820:   user => {
  821:     type => 'hashref',
  822:     schema => {
  823:       name => {
  824:         type => 'string',
  825:         transform => sub { trim($_[0]) }
  826:       }, email => {
  827:         type => 'string',
  828:         transform => sub { lc(trim($_[0])) }
  829:       }
  830:     }
  831:   }
  832: 
  833: Transformations can also be defined in custom types for reusability:
  834: 
  835:   my $custom_types = {
  836:     email => {
  837:       type => 'string',
  838:       transform => sub { lc(trim($_[0])) },
  839:       matches => qr/^[^@\s]+\@[^@\s]+\.[^@\s]+$/
  840:     }
  841:   };
  842: 
  843: Note that the transformed value is what gets returned in the validated result and is what
  844: subsequent validation rules will check against. If a transformation might fail, ensure it
  845: handles edge cases appropriately.
  846: It is the responsibility of the transformer to ensure that the type of the returned value is correct,
  847: since that is what will be validated.
  848: 
  849: Many validators also allow a code ref to be passed so that you can create your own, conditional validation rule, e.g.:
  850: 
  851:   $schema = {
  852:     age => {
  853:       type => 'integer',
  854:       min => sub {
  855:           my ($value, $all_params) = @_;
  856:           return $all_params->{country} eq 'US' ? 21 : 18;
  857:       }
  858:     }
  859:   }
  860: 
  861: =item * C<validator>
  862: 
  863: A synonym of C<validate>, for compatibility with L<Data::Processor>.
  864: 
  865: =item * C<cross_validation>
  866: 
  867: A reference to a hash that defines validation rules that depend on more than one parameter.
  868: Cross-field validations are performed after all individual parameter validations have passed,
  869: allowing you to enforce business logic that requires checking relationships between different fields.
  870: 
  871: Each cross-validation rule is a key-value pair where the key is a descriptive name for the validation
  872: and the value is a code reference that accepts a hash reference of all validated parameters.
  873: The subroutine should return C<undef> if the validation passes, or an error message string if it fails.
  874: 
  875:   my $schema = {
  876:     password => { type => 'string', min => 8 },
  877:     password_confirm => { type => 'string' }
  878:   };
  879: 
  880:   my $cross_validation = {
  881:     passwords_match => sub {
  882:       my $params = shift;
  883:       return $params->{password} eq $params->{password_confirm}
  884:         ? undef : "Passwords don't match";
  885:     }
  886:   };
  887: 
  888:   my $validated = validate_strict(
  889:     schema => $schema,
  890:     input => $input,
  891:     cross_validation => $cross_validation
  892:   );
  893: 
  894: Common use cases include password confirmation, date range validation, numeric comparisons,
  895: and conditional requirements:
  896: 
  897:   # Date range validation
  898:   my $cross_validation = {
  899:     date_range_valid => sub {
  900:       my $params = shift;
  901:       return $params->{start_date} le $params->{end_date}
  902:         ? undef : "Start date must be before or equal to end date";
  903:     }
  904:   };
  905: 
  906:   # Price range validation
  907:   my $cross_validation = {
  908:     price_range_valid => sub {
  909:       my $params = shift;
  910:       return $params->{min_price} <= $params->{max_price}
  911:         ? undef : "Minimum price must be less than or equal to maximum price";
  912:     }
  913:   };
  914: 
  915:   # Conditional required field
  916:   my $cross_validation = {
  917:     address_required_for_delivery => sub {
  918:       my $params = shift;
  919:       if ($params->{shipping_method} eq 'delivery' && !$params->{delivery_address}) {
  920:         return "Delivery address is required when shipping method is 'delivery'";
  921:       }
  922:       return undef;
  923:     }
  924:   };
  925: 
  926: Multiple cross-validations can be defined in the same hash, and they are all checked in order.
  927: If any cross-validation fails, the function will C<croak> with the error message returned by the validation:
  928: 
  929:   my $cross_validation = {
  930:     passwords_match => sub {
  931:       my $params = shift;
  932:       return $params->{password} eq $params->{password_confirm}
  933:         ? undef : "Passwords don't match";
  934:     },
  935:     emails_match => sub {
  936:       my $params = shift;
  937:       return $params->{email} eq $params->{email_confirm}
  938:         ? undef : "Email addresses don't match";
  939:     },
  940:     age_matches_birth_year => sub {
  941:       my $params = shift;
  942:       my $current_year = (localtime)[5] + 1900;
  943:       my $calculated_age = $current_year - $params->{birth_year};
  944:       return abs($calculated_age - $params->{age}) <= 1
  945:         ? undef : "Age doesn't match birth year";
  946:     }
  947:   };
  948: 
  949: Cross-validations receive the parameters after individual validation and transformation have been applied,
  950: so you can rely on the data being in the correct format and type:
  951: 
  952:   my $schema = {
  953:     email => {
  954:       type => 'string',
  955:       transform => sub { lc($_[0]) }  # Lowercased before cross-validation
  956:     },
  957:     email_confirm => {
  958:       type => 'string',
  959:       transform => sub { lc($_[0]) }
  960:     }
  961:   };
  962: 
  963:   my $cross_validation = {
  964:     emails_match => sub {
  965:       my $params = shift;
  966:       # Both emails are already lowercased at this point
  967:       return $params->{email} eq $params->{email_confirm}
  968:         ? undef : "Email addresses don't match";
  969:     }
  970:   };
  971: 
  972: Cross-validations can access nested structures and optional fields:
  973: 
  974:   my $cross_validation = {
  975:     guardian_required_for_minors => sub {
  976:       my $params = shift;
  977:       if ($params->{user}{age} < 18 && !$params->{guardian}) {
  978:         return "Guardian information required for users under 18";
  979:       }
  980:       return undef;
  981:     }
  982:   };
  983: 
  984: All cross-validations must pass for the overall validation to succeed.
  985: 
  986: =item * metadata
  987: 
  988: Fields starting with <_> are generated by L<App::Test::Generator::SchemaExtractor>,
  989: and are currently ignored.
  990: 
  991: =item * C<semantic>
  992: 
  993: A hint about the semantic meaning of the parameter value.
  994: Supported values: C<unix_timestamp>, C<identifier>, C<class_name>, C<filename>.
  995: 
  996:   ts     => { type => 'integer', semantic => 'unix_timestamp' }
  997:   func   => { type => 'string',  semantic => 'identifier' }
  998:   module => { type => 'string',  semantic => 'class_name' }
  999:   file   => { type => 'string',  semantic => 'filename' }
 1000: 
 1001: When C<semantic> is C<unix_timestamp>, the value must be a non-negative integer no greater than
 1002: C<2147483647> (i.e. a valid 32-bit Unix epoch timestamp).
 1003: Values outside this range cause the function to C<croak>.
 1004: 
 1005: When C<semantic> is C<identifier>, the value must match C</\A[A-Za-z_]\w*\z/>, a single
 1006: valid Perl bareword identifier.  Package separators (C<::>) are not permitted; use
 1007: C<class_name> for those.
 1008: 
 1009: When C<semantic> is C<class_name>, the value must match
 1010: C</\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/>, a syntactically valid Perl class name such
 1011: as C<'Foo'> or C<'Foo::Bar::Baz'>.  The class does not need to be loaded.
 1012: 
 1013: When C<semantic> is C<filename>, the value must be a single path component:
 1014: non-empty, not C<.> or C<..>, containing neither C</> nor a NUL byte, and at most 255
 1015: bytes long when encoded as UTF-8.  Directory parts are rejected, so it is safe against
 1016: path traversal such as C<../../etc/passwd>.  It does not check that the file exists, and
 1017: it does not reject characters that are only illegal on some platforms (such as C<:> on Windows).
 1018: 
 1019: Unknown semantic values emit a warning but do not cause an error.
 1020: 
 1021: =item * C<relationships>
 1022: 
 1023: A reference to an array that defines validation rules based on relationships between parameters.
 1024: Relationship validations are performed after all individual parameter validations have passed,
 1025: but before cross-validations.
 1026: 
 1027: Each relationship is a hash reference with a C<type> field and additional fields depending on the type:
 1028: 
 1029: =over 4
 1030: 
 1031: =item * B<mutually_exclusive>
 1032: 
 1033: Parameters that cannot be specified together.
 1034: 
 1035:   relationships => [
 1036:     {
 1037:       type => 'mutually_exclusive',
 1038:       params => ['file', 'content'],
 1039:       description => 'Cannot specify both file and content'
 1040:     }
 1041:   ]
 1042: 
 1043: =item * B<required_group>
 1044: 
 1045: At least one parameter from the group must be specified.
 1046: 
 1047:   relationships => [
 1048:     {
 1049:       type => 'required_group',
 1050:       params => ['id', 'name'],
 1051:       logic => 'or',
 1052:       description => 'Must specify either id or name'
 1053:     }
 1054:   ]
 1055: 
 1056: =item * B<conditional_requirement>
 1057: 
 1058: If one parameter is specified, another becomes required.
 1059: 
 1060:   relationships => [
 1061:     {
 1062:       type => 'conditional_requirement',
 1063:       if => 'async',
 1064:       then_required => 'callback',
 1065:       description => 'When async is specified, callback is required'
 1066:     }
 1067:   ]
 1068: 
 1069: =item * B<dependency>
 1070: 
 1071: One parameter requires another to be present.
 1072: 
 1073:   relationships => [
 1074:     {
 1075:       type => 'dependency',
 1076:       param => 'port',
 1077:       requires => 'host',
 1078:       description => 'port requires host to be specified'
 1079:     }
 1080:   ]
 1081: 
 1082: =item * B<value_constraint>
 1083: 
 1084: Specific value requirements between parameters.
 1085: 
 1086:   relationships => [
 1087:     {
 1088:       type => 'value_constraint',
 1089:       if => 'ssl',
 1090:       then => 'port',
 1091:       operator => '==',
 1092:       value => 443,
 1093:       description => 'When ssl is specified, port must equal 443'
 1094:     }
 1095:   ]
 1096: 
 1097: =item * B<value_conditional>
 1098: 
 1099: Parameter required when another has a specific value.
 1100: 
 1101:   relationships => [
 1102:     {
 1103:       type => 'value_conditional',
 1104:       if => 'mode',
 1105:       equals => 'secure',
 1106:       then_required => 'key',
 1107:       description => "When mode equals 'secure', key is required"
 1108:     }
 1109:   ]
 1110: 
 1111: =back
 1112: 
 1113: If a parameter is optional and its value is C<undef>,
 1114: validation will be skipped for that parameter.
 1115: 
 1116: If the validation fails, the function will C<croak> with an error message describing the validation failure.
 1117: 
 1118: 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.
 1119: 
 1120: The C<description> field is optional but recommended for clearer error messages.
 1121: 
 1122: =back
 1123: 
 1124: =head3 API SPECIFICATION
 1125: 
 1126: =head4 Input
 1127: 
 1128:   {
 1129:       schema                    => { type => ['hashref', 'arrayref'] },   # or members
 1130:       input                     => { type => ['hashref', 'arrayref'] },   # or args
 1131:       description               => { type => 'string',  optional => 1 },
 1132:       custom_types              => { type => 'hashref', optional => 1 },
 1133:       unknown_parameter_handler => { type => 'string',  optional => 1,
 1134:                                      memberof => ['die', 'warn', 'ignore'] },
 1135:       logger                    => { type => 'object',  optional => 1, can => ['error', 'warn'] },
 1136:       relationships             => { type => 'arrayref', optional => 1 },
 1137:       cross_validation          => { type => 'hashref', optional => 1 },
 1138:   }
 1139: 
 1140: The arguments may be passed as a list of key/value pairs or as a single hashref.
 1141: A hashref C<input> is validated as named parameters; an arrayref C<input> is validated as
 1142: positional parameters, in which case every parameter in the schema needs a C<position>.
 1143: 
 1144: =head4 Output
 1145: 
 1146:   { type => 'hashref' }
 1147: 
 1148: A new hashref of the validated and coerced parameters, keyed by canonical parameter name.
 1149: It croaks (or calls C<< $logger->error >> and then croaks) on the first validation failure.
 1150: 
 1151: =head2 Example Usage
 1152: 
 1153:   my $schema = {
 1154:     host => { type => 'string' },
 1155:     port => { type => 'integer' },
 1156:     ssl => { type => 'boolean' },
 1157:     file => { type => 'string', optional => 1 },
 1158:     content => { type => 'string', optional => 1 }
 1159:   };
 1160: 
 1161:   my $relationships = [
 1162:     {
 1163:       type => 'mutually_exclusive',
 1164:       params => ['file', 'content']
 1165:     }, {
 1166:       type => 'required_group',
 1167:       params => ['host', 'file']
 1168:     },
 1169:     {
 1170:       type => 'dependency',
 1171:       param => 'port',
 1172:       requires => 'host'
 1173:     },
 1174:     {
 1175:       type => 'value_constraint',
 1176:       if => 'ssl',
 1177:       then => 'port',
 1178:       operator => '==',
 1179:       value => 443
 1180:     }
 1181:   ];
 1182: 
 1183:   my $validated = validate_strict(
 1184:     schema => $schema,
 1185:     input => $input,
 1186:     relationships => $relationships
 1187:   );
 1188: 
 1189: =head1 MIGRATION FROM LEGACY VALIDATORS
 1190: 
 1191: =head2 From L<Params::Validate>
 1192: 
 1193:     # Old style
 1194:     validate(@_, {
 1195:         name => { type => SCALAR },
 1196:         age => { type => SCALAR, regex => qr/^\d+$/ }
 1197:     });
 1198: 
 1199:     # New style
 1200:     validate_strict(
 1201:         schema => {	# or "members"
 1202:             name => 'string',
 1203:             age => { type => 'integer', min => 0 }
 1204:         },
 1205:         args => { @_ }
 1206:     );
 1207: 
 1208: =head2 From L<Type::Params>
 1209: 
 1210:     # Old style
 1211:     my ($name, $age) = validate_positional \@_, Str, Int;
 1212: 

Mutants (Total: 3, Killed: 3, Survived: 0)

1213: # New style - requires converting to named parameters first 1214: my %args = (name => $_[0], age => $_[1]); 1215: my $validated = validate_strict( 1216: schema => { name => 'string', age => 'integer' }, 1217: args => \%args 1218: ); 1219: 1220: =cut 1221: 1222: sub validate_strict

Mutants (Total: 1, Killed: 1, Survived: 0)

1223: {

Mutants (Total: 1, Killed: 1, Survived: 0)

●1224 → 1236 → 1244 1224: local $_depth = $_depth + 1; 1225: 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: my $params = (ref($_[0]) eq 'HASH') ? $_[0] : { @_ }; 1230:

Mutants (Total: 2, Killed: 2, Survived: 0)

1231: my $schema = $params->{'schema'} || $params->{'members'}; 1232: my $args = $params->{'args'} || $params->{'input'}; 1233: my $logger = $params->{'logger'}; 1234: my $custom_types = $params->{'custom_types'};

Mutants (Total: 1, Killed: 1, Survived: 0)

1235: my $unknown_parameter_handler = $params->{'unknown_parameter_handler'}; 1236: if(!defined($unknown_parameter_handler)) { 1237: if($params->{'carp_on_warn'}) { 1238: $unknown_parameter_handler = 'warn'; 1239: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

1240: $unknown_parameter_handler = 'die'; 1241: } 1242: } 1243: ●1244 → 1248 → 1253 1244: 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.

Mutants (Total: 1, Killed: 1, Survived: 0)

1248: if(ref($schema) eq 'ARRAY') { 1249: $schema = _schema_from_arrayref($schema, $logger); 1250: } 1251: 1252: # Check if schema and args are references to hashes

Mutants (Total: 1, Killed: 1, Survived: 0)

●1253 → 1253 → 1258 1253: if(ref($schema) ne 'HASH') { 1254: _error($logger, 'validate_strict: schema must be a hash reference'); 1255: } 1256: 1257: # Inspired by Data::Processor

Mutants (Total: 1, Killed: 1, Survived: 0)

●1258 → 1261 → 1271 1258: my $schema_description = $params->{'description'} || 'validate_strict'; 1259: my $error_msg = $params->{'error_msg'}; 1260: 1261: if($schema->{'members'} && ($schema->{'description'} || $schema->{'error_msg'})) { 1262: $schema_description = $schema->{'description'}; 1263: $error_msg = $schema->{'error_msg'};

Mutants (Total: 1, Killed: 1, Survived: 0)

1264: $schema = $schema->{'members'}; 1265: # The members value may also be in arrayref form 1266: if(ref($schema) eq 'ARRAY') { 1267: $schema = _schema_from_arrayref($schema, $logger); 1268: } 1269: }

Mutants (Total: 1, Killed: 1, Survived: 0)

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

Mutants (Total: 1, Killed: 1, Survived: 0)

1276:

Mutants (Total: 1, Killed: 1, Survived: 0)

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 → 1283 → 1289 1281: my $compiled = $params->{'_compiled'}; 1282: my $fields;

Mutants (Total: 1, Killed: 1, Survived: 0)

1283: if($compiled && ref($args) eq 'HASH' && $schema == $compiled->{'schema'}) { 1284: $fields = $compiled->{'fields'}; 1285: } else { 1286: $compiled = undef; 1287: } 1288: ●1289 → 1289 → 1323 1289: 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: my %_alias_to_canonical; 1294: if(!$compiled || $compiled->{'has_aliases'}) { 1295: foreach my $canonical (keys %{$schema}) { 1296: my $r = $schema->{$canonical};

Mutants (Total: 1, Killed: 1, Survived: 0)

1297: if(ref($r) eq 'HASH' && ref($r->{'aliases'}) eq 'ARRAY') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1298: $_alias_to_canonical{$_} = $canonical for @{$r->{'aliases'}};

Mutants (Total: 1, Killed: 1, Survived: 0)

1299: } 1300: } 1301: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1302:

Mutants (Total: 2, Killed: 2, Survived: 0)

1303: foreach my $key (keys %{$args}) { 1304: if(!exists($schema->{$key}) && !exists($_alias_to_canonical{$key})) { 1305: if($unknown_parameter_handler eq 'die') { 1306: _error($logger, "$schema_description: Unknown parameter '$key'"); 1307: } elsif($unknown_parameter_handler eq 'warn') { 1308: _warn($logger, "$schema_description: Unknown parameter '$key'"); 1309: next; 1310: } elsif($unknown_parameter_handler eq 'ignore') { 1311: if($logger) { 1312: $logger->debug(__PACKAGE__ . ": $schema_description: Unknown parameter '$key'"); 1313: } 1314: next; 1315: } else { 1316: _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 → 1327 → 1351 1323: 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: $are_positional_args = $compiled->{'positional'} if($compiled); 1327: foreach my $key ($compiled ? () : keys %{$schema}) {

Mutants (Total: 2, Killed: 2, Survived: 0)

1328: if(defined(my $rules = $schema->{$key})) { 1329: if(ref($rules) eq 'HASH') { 1330: if($rules->{'slurp'} && !defined($rules->{'position'})) { 1331: _error($logger, "::validate_strict: slurp parameter '$key' requires a 'position'");

Mutants (Total: 1, Killed: 1, Survived: 0)

1332: } 1333: if(!defined($rules->{'position'})) { 1334: if($are_positional_args == 1) { 1335: _error($logger, "::validate_strict: $key is missing position value"); 1336: } 1337: $are_positional_args = 0; 1338: last; 1339: }

Mutants (Total: 2, Killed: 2, Survived: 0)

1340: $are_positional_args = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

1341: } else { 1342: $are_positional_args = 0; 1343: last;

Mutants (Total: 1, Killed: 1, Survived: 0)

1344: } 1345: } else { 1346: $are_positional_args = 0; 1347: last; 1348: } 1349: } 1350: ●1351 → 1354 → 2442 1351: my %validated_args; 1352: my %invalid_args; 1353: my $has_needs = 0; # true if any parameter has a 'needs' rule

Mutants (Total: 1, Killed: 1, Survived: 0)

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

Mutants (Total: 1, Killed: 1, Survived: 0)

1360: if($fields && (my $f = $fields->{$key})) { 1361: my $value = $args->{$key}; 1362: 1363: if(!exists($args->{$key})) { 1364: if($f->{'opt'}) { 1365: $validated_args{$key} //= $f->{'default'} if($f->{'has_default'}); 1366: next; 1367: } 1368: _error($logger, "$schema_description: Required parameter $f->{label} is missing");

Mutants (Total: 1, Killed: 1, Survived: 0)

1369: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1370: 1371: my $label = $f->{'label'}; 1372: my $frules = $f->{'rules'}; 1373: my $t = $f->{'t'}; 1374: 1375: if($t == _T_STRING) { 1376: if(ref($value)) { 1377: _rule_error($logger, $frules, "$schema_description: Parameter $label must be a string");

Mutants (Total: 1, Killed: 1, Survived: 0)

1378: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1379: } elsif($t == _T_INT) { 1380: if(defined($value)) { 1381: if(!Scalar::Util::looks_like_number($value) || ($value - $value) != 0 || $value != int($value)) { 1382: _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be an integer"); 1383: } 1384: $value = int($value);

Mutants (Total: 1, Killed: 1, Survived: 0)

1385: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1386: } elsif($t == _T_NUM) { 1387: if(defined($value)) { 1388: if(!Scalar::Util::looks_like_number($value)) { 1389: _rule_error($logger, $frules, "$schema_description: Parameter $label must be a number"); 1390: } 1391: $value = 0 + $value;

Mutants (Total: 1, Killed: 1, Survived: 0)

1392: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1393: } elsif($t == _T_BOOL) { 1394: if(defined($value)) { 1395: if(defined(my $b = $Readonly::Values::Boolean::booleans{$value})) { 1396: $value = $b; 1397: } else { 1398: _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be a boolean"); 1399: } 1400: } 1401: } elsif($t == _T_ARRAY) { 1402: if(defined($value) && ref($value) ne 'ARRAY') { 1403: _rule_error($logger, $frules, "$schema_description: Parameter $label must be an arrayref, not " . ref($value)); 1404: } 1405: } elsif($t == _T_HASH) { 1406: if(defined($value) && ref($value) ne 'HASH') { 1407: _rule_error($logger, $frules, "$schema_description: Parameter $label must be an hashref"); 1408: } 1409: } elsif($t == _T_SCALAR) { 1410: if(defined($value) && ref($value)) { 1411: _rule_error($logger, $frules, "$schema_description: Parameter $label must be a scalar, not a " . ref($value) . ' reference');

Mutants (Total: 1, Killed: 1, Survived: 0)

1412: } 1413: } elsif($t == _T_CODE) {

Mutants (Total: 2, Killed: 2, Survived: 0)

1414: if(defined($value) && ref($value) ne 'CODE') { 1415: _rule_error($logger, $frules, "$schema_description: Parameter $label must be a coderef, not a ref to " . ref($value)); 1416: } 1417: } else { # _T_OBJECT 1418: if(defined($value) && !Scalar::Util::blessed($value)) { 1419: _rule_error($logger, $frules, "$schema_description: Parameter $label must be an object");

Mutants (Total: 1, Killed: 1, Survived: 0)

1420: }

Mutants (Total: 2, Killed: 2, Survived: 0)

1421: }

Mutants (Total: 4, Killed: 4, Survived: 0)

1422: 1423: my $chars; # the character count, computed at most once for min and max 1424: if(defined(my $min = $f->{'min'})) { 1425: my $mk = $f->{'mk'}; 1426: if($mk eq 's') { 1427: if(!defined($value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1428: if($min > 0 && !$f->{'opt'}) { 1429: _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: if($len < $min) { 1433: _rule_error($logger, $frules, "$schema_description: Parameter $label too short, ($len characters), must be at least $min characters");

Mutants (Total: 1, Killed: 1, Survived: 0)

1434: } 1435: } else { 1436: _rule_error($logger, $frules, "$schema_description: Parameter $label can't be decoded"); 1437: } 1438: } elsif($mk eq 'a') { 1439: if(!defined($value)) { 1440: if($min > 0 && !$f->{'opt'}) { 1441: _rule_error($logger, $frules, "$schema_description: Parameter $label is undefined, but must have at least $min member" . ($min > 1 ? 's' : '')); 1442: } 1443: } elsif(scalar(@{$value}) < $min) { 1444: _rule_error($logger, $frules, "$schema_description: Parameter $label must have at least $min member" . (($min > 1) ? 's' : '')); 1445: } 1446: } elsif($mk eq 'h') { 1447: if(!defined($value)) { 1448: if($min > 0 && !$f->{'opt'}) { 1449: _rule_error($logger, $frules, "$schema_description: Parameter $label is undefined, but must contain at least $min keys"); 1450: } 1451: } elsif(scalar(keys(%{$value})) < $min) { 1452: _rule_error($logger, $frules, "$schema_description: Parameter $label must contain at least $min keys"); 1453: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1454: } else { # 'n': integer, number or float 1455: if(!defined($value)) { 1456: if($min > 0 && !$f->{'opt'}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1457: _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)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1460: if($value < $min) { 1461: if($frules->{'error_msg'}) { 1462: _error($logger, $frules->{'error_msg'}); 1463: } elsif(($f->{'tname'} eq 'integer') && ($value == 0)) { 1464: _error($logger, "$schema_description: Parameter $label ($value) must be a positive number"); 1465: } elsif(($f->{'tname'} eq 'integer') && ($value == 1)) { 1466: _error($logger, "$schema_description: Parameter $label ($value) must be a positive, non-zero number"); 1467: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

1468: _error($logger, "$schema_description: Parameter $label ($value) must be at least $min");

Mutants (Total: 1, Killed: 1, Survived: 0)

1469: }

Mutants (Total: 4, Killed: 4, Survived: 0)

1470: } 1471: } else { 1472: _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be a number"); 1473: } 1474: } 1475: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1476:

Mutants (Total: 1, Killed: 1, Survived: 0)

1477: if(defined(my $max = $f->{'max'}) && defined($value)) { 1478: my $mk = $f->{'mk'}; 1479: if($mk eq 's') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1480: if(defined(my $len = $chars // _number_of_characters($value))) { 1481: if($len > $max) { 1482: _rule_error($logger, $frules, "$schema_description: Parameter $label too long, ($len characters), must be no longer than $max"); 1483: } 1484: } else { 1485: _rule_error($logger, $frules, "$schema_description: Parameter $label can't be decoded"); 1486: } 1487: } elsif($mk eq 'a') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1488: if(scalar(@{$value}) > $max) { 1489: _rule_error($logger, $frules, "$schema_description: Parameter $label must contain no more than $max items"); 1490: } 1491: } elsif($mk eq 'h') { 1492: if(scalar(keys(%{$value})) > $max) { 1493: _rule_error($logger, $frules, "$schema_description: Parameter $label must contain no more than $max keys"); 1494: } 1495: } else { # 'n': integer, number or float 1496: if(Scalar::Util::looks_like_number($value)) { 1497: if($value > $max) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1498: if($frules->{'error_msg'}) { 1499: _error($logger, $frules->{'error_msg'}); 1500: } elsif(($f->{'tname'} eq 'integer') && ($value == 0)) { 1501: _error($logger, "$schema_description: Parameter $label ($value) must be a negative number");

Mutants (Total: 1, Killed: 1, Survived: 0)

1502: } elsif(($f->{'tname'} eq 'integer') && ($value == -1)) { 1503: _error($logger, "$schema_description: Parameter $label ($value) must be a negative, non-zero number"); 1504: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

1505: _error($logger, "$schema_description: Parameter $label ($value) must be no more than $max");

Mutants (Total: 1, Killed: 1, Survived: 0)

1506: } 1507: } 1508: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

1509: _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be a number"); 1510: } 1511: } 1512: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1513: 1514: if(defined($value)) { 1515: if(my $re = $f->{'re'}) {

Mutants (Total: 2, Killed: 2, Survived: 0)

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: eval { 1519: if($value !~ $re) { 1520: _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must match pattern '$re'");

Mutants (Total: 1, Killed: 1, Survived: 0)

1521: } 1522: 1; 1523: };

Mutants (Total: 1, Killed: 1, Survived: 0)

1524: if($@) { 1525: _rule_error($logger, $frules, "$schema_description: Parameter $label regex '$f->{match_src}' error: $@"); 1526: } 1527: } 1528: if(my $list = $f->{'list'}) { 1529: unless(_value_in_list($value, $list, $f->{'type'}, $frules->{'case_sensitive'})) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1530: _rule_error($logger, $frules, "$schema_description: Parameter $label ($value) must be one of ", join(', ', @{$list})); 1531: } 1532: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1533: } 1534: 1535: $validated_args{$key} = $value; 1536: next;

Mutants (Total: 1, Killed: 1, Survived: 0)

1537: } 1538: 1539: my $rules = $schema->{$key};

Mutants (Total: 1, Killed: 1, Survived: 0)

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: my $lookup_key = $key;

Mutants (Total: 1, Killed: 1, Survived: 0)

1544: if($are_positional_args != 1 && ref($rules) eq 'HASH' 1545: && ref($rules->{'aliases'}) eq 'ARRAY' 1546: && !exists($args->{$key})) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1547: for my $alias (@{$rules->{'aliases'}}) { 1548: if(exists($args->{$alias})) { 1549: $lookup_key = $alias; 1550: last;

Mutants (Total: 1, Killed: 1, Survived: 0)

1551: } 1552: } 1553: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1554: 1555: my $value; 1556: if($are_positional_args == 1) { 1557: if(ref($args) ne 'ARRAY') { 1558: _error($logger, "::validate_strict: position $rules->{position} given for '$key', but args isn't an array");

Mutants (Total: 1, Killed: 1, Survived: 0)

1559: } 1560: if(ref($rules) eq 'HASH' && $rules->{'slurp'}) { 1561: my $pos = $rules->{'position'}; 1562: $value = [@{$args}[$pos .. $#$args]]; 1563: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

1564: $value = $args->[$rules->{'position'}]; 1565: } 1566: } else { 1567: $value = $args->{$lookup_key};

Mutants (Total: 2, Killed: 2, Survived: 0)

1568: } 1569: 1570: if(!defined($rules)) { # Allow anything

Mutants (Total: 1, Killed: 1, Survived: 0)

1571: $validated_args{$key} = $value; 1572: next; 1573: } 1574:

Mutants (Total: 1, Killed: 1, Survived: 0)

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

Mutants (Total: 1, Killed: 1, Survived: 0)

1578: } 1579: 1580: $has_needs = 1 if(ref($rules) eq 'HASH' && defined($rules->{'needs'})); 1581: 1582: my $is_optional = 0; 1583:

Mutants (Total: 1, Killed: 1, Survived: 0)

1584: my $rule_description = $schema_description; # Can be overridden in each element 1585: my $param_label = "'$key'"; 1586:

Mutants (Total: 1, Killed: 1, Survived: 0)

1587: if(ref($rules) eq 'HASH') { 1588: if(exists($rules->{'description'})) { 1589: $param_label = "'$key' ($rules->{description})"; 1590: }

Mutants (Total: 1, Killed: 1, Survived: 0)

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.

Mutants (Total: 1, Killed: 1, Survived: 0)

1594: my $pre_deref_value = $value; 1595: my $is_stringref_type = defined($value) && defined($rules->{'type'}) && !ref($rules->{'type'}) && lc($rules->{'type'}) eq 'stringref'; 1596: if($is_stringref_type) { 1597: if(ref($value) ne 'SCALAR') { 1598: my $got = ref($value) ? 'a ' . ref($value) . ' reference' : 'a plain scalar';

Mutants (Total: 1, Killed: 1, Survived: 0)

1599: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a string reference, not $got"); 1600: } 1601: $value = ${$value}; 1602: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1603: if($rules->{'transform'} && defined($value)) { 1604: if(ref($rules->{'transform'}) eq 'CODE') { 1605: $value = &{$rules->{'transform'}}($value); 1606: } else { 1607: _error($logger, "$rule_description: transforms must be a code ref"); 1608: } 1609: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1610: if(exists($rules->{optional})) { 1611: 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.

Mutants (Total: 1, Killed: 1, Survived: 0)

1614: # For all other types the post-transform value is passed, as before. 1615: my $opt_arg = $is_stringref_type ? $pre_deref_value : $value; 1616: $is_optional = &{$rules->{optional}}($opt_arg, $args);

Mutants (Total: 1, Killed: 1, Survived: 0)

1617: } else { 1618: $is_optional = $rules->{'optional'}; 1619: } 1620: } elsif($rules->{nullable}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1621: $is_optional = $rules->{'nullable'}; 1622: } elsif(defined($rules->{'type'}) && !ref($rules->{'type'}) && lc($rules->{'type'}) eq 'void') { 1623: $is_optional = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

1624: } elsif($rules->{'slurp'}) { 1625: $is_optional = 1; 1626: } 1627: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1628: 1629: # Handle optional parameters 1630: if((ref($rules) eq 'HASH') && $is_optional) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1631: my $missing; 1632: if($are_positional_args == 1) { 1633: # A slurp parameter is never missing: at worst it yields an empty arrayref. 1634: $missing = $rules->{'slurp'} ? 0 : !defined($args->[$rules->{position}]);

Mutants (Total: 1, Killed: 1, Survived: 0)

1635: } else { 1636: $missing = !exists($args->{$lookup_key}); 1637: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1638: if($missing) { 1639: if($are_positional_args == 1) { 1640: if(scalar(@{$args}) < $rules->{'position'}) { 1641: # arg array is too short, so it must be missing

Mutants (Total: 1, Killed: 1, Survived: 0)

1642: _error($logger, "$rule_description: Required parameter $param_label is missing"); 1643: _unreachable($logger); # Defensive: _error always croaks, so this is never reached. 1644: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1645: } 1646: if(exists($rules->{'default'})) { 1647: # Populate missing optional parameters with the specified output values 1648: $validated_args{$key} //= $rules->{'default'};

Mutants (Total: 1, Killed: 1, Survived: 0)

1649: next; # default wins; do not fall through to the schema branch 1650: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1651: 1652: if($rules->{'schema'}) { 1653: $value = _apply_nested_defaults({}, $rules->{'schema'}); 1654: next unless scalar(%{$value}); 1655: # The nested schema has a default value 1656: } else { 1657: next; # optional and missing 1658: } 1659: } 1660: } elsif((ref($args) eq 'HASH') && !exists($args->{$lookup_key})) { 1661: # The parameter is required

Mutants (Total: 1, Killed: 1, Survived: 0)

1662: # Use exists rather than defined, so that an undefined value can be passed, but the key is there 1663: _error($logger, "$rule_description: Required parameter $param_label is missing"); 1664: } 1665:

Mutants (Total: 1, Killed: 1, Survived: 0)

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

Mutants (Total: 1, Killed: 1, Survived: 0)

1670: # (min, max, matches, optional, etc.) so they are each fully validated.

Mutants (Total: 4, Killed: 4, Survived: 0)

1671: # Must run after optional/transform handling above but before rule dispatch below. 1672: if(ref($rules) eq 'HASH' && !ref($rules->{'type'}) && defined($rules->{'type'}) && index($rules->{'type'}, '|') >= 0) { 1673: $rules = { %$rules, type => [ split /\s*\|\s*/, $rules->{'type'} ] };

Mutants (Total: 1, Killed: 1, Survived: 0)

1674: }

Mutants (Total: 4, Killed: 4, Survived: 0)

1675: if(ref($rules) eq 'HASH' && ref($rules->{'type'}) eq 'ARRAY') {

Mutants (Total: 1, Killed: 0, Survived: 1)
1676: my %base = %{$rules}; 1677: my @type_list = @{delete $base{'type'}}; 1678: if(!@type_list) { 1679: _error($logger, "$rule_description: Parameter $param_label: union type list must not be empty"); 1680: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1681: # Expand into one full rule hash per candidate type

Mutants (Total: 4, Killed: 4, Survived: 0)

1682: $rules = [ map { { %base, type => $_ } } @type_list ]; 1683: } 1684: 1685: # Validate based on rules 1686: if(ref($rules) eq 'HASH') { 1687: if(defined(my $min = $rules->{'min'} // $rules->{'minimum'}) && defined(my $max = $rules->{'max'})) { 1688: if($min > $max) { 1689: _error($logger, "validate_strict($key): min must be <= max ($min > $max)"); 1690: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1691: }

Mutants (Total: 4, Killed: 4, Survived: 0)

1692:

Mutants (Total: 3, Killed: 0, Survived: 3)
1693: # memberof and its synonym enum cannot be combined with min or max 1694: if($rules->{'memberof'} || $rules->{'enum'} || $rules->{'values'}) { 1695: if(defined(my $min = $rules->{'min'} // $rules->{'minimum'})) { 1696: _error($logger, "validate_strict($key): min ($min) makes no sense with memberof/enum/values"); 1697: }

Mutants (Total: 4, Killed: 4, Survived: 0)

1698: if(defined(my $max = $rules->{'max'})) {

Mutants (Total: 3, Killed: 0, Survived: 3)
1699: _error($logger, "validate_strict($key): max ($max) makes no sense with memberof/enum/values"); 1700: } 1701: } 1702:

Mutants (Total: 1, Killed: 1, Survived: 0)

1703: foreach my $rule_name ('type', grep { $_ ne 'type' } keys %$rules) {

Mutants (Total: 4, Killed: 4, Survived: 0)

1704: my $rule_value = $rules->{$rule_name}; 1705: 1706: if((ref($rule_value) eq 'CODE') 1707: && ($rule_name ne 'validate') 1708: && ($rule_name ne 'callback') 1709: && ($rule_name ne 'validator')

Mutants (Total: 4, Killed: 4, Survived: 0)

1710: && ($rule_name ne 'transform') # already applied before this loop 1711: && ($rule_name ne 'optional')) { # already applied before this loop 1712: $rule_value = &{$rule_value}($value, $args); 1713: } 1714:

Mutants (Total: 1, Killed: 1, Survived: 0)

1715: # Better OOP, the routine has been given an object rather than a scalar

Mutants (Total: 4, Killed: 4, Survived: 0)

1716: if(ref($rule_value) && Scalar::Util::blessed($rule_value) && $rule_value->can('as_string')) { 1717: $rule_value = $rule_value->as_string(); 1718: } 1719: 1720: if($rule_name eq 'type') { 1721: my $type = lc($rule_value);

Mutants (Total: 1, Killed: 1, Survived: 0)

1722:

Mutants (Total: 4, Killed: 4, Survived: 0)

1723: if(($type eq 'string') || ($type eq 'str')) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1724: if(ref($value)) { 1725: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a string");

Mutants (Total: 1, Killed: 1, Survived: 0)

1726: } 1727: unless((ref($value) eq '') || (defined($value) && length($value))) { # Allow undef for optional strings

Mutants (Total: 1, Killed: 1, Survived: 0)

1728: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a string"); 1729: } 1730: } elsif(($type eq 'integer') || ($type eq 'int')) { 1731: if(!defined($value)) { 1732: next; # Skip if number is undefined 1733: } 1734: if(!Scalar::Util::looks_like_number($value) || ($value - $value) != 0 || $value != int($value)) { 1735: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be an integer"); 1736: } 1737: $value = int($value); # Coerce to integer 1738: } elsif(($type eq 'number') || ($type eq 'float') || ($type eq 'num') || ($type eq 'double')) { 1739: if(!defined($value)) { 1740: next; # Skip if number is undefined 1741: } 1742: if(!Scalar::Util::looks_like_number($value)) { 1743: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a number");

Mutants (Total: 1, Killed: 1, Survived: 0)

1744: } 1745: # $value = eval $value; # Coerce to number (be careful with eval) 1746: $value = 0 + $value; # Numeric coercion 1747: } elsif($type eq 'arrayref') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1748: if(!defined($value)) { 1749: next; # Skip if arrayref is undefined 1750: } 1751: if(ref($value) ne 'ARRAY') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1752: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an arrayref, not " . ref($value));

Mutants (Total: 1, Killed: 1, Survived: 0)

1753: } 1754: } elsif($type eq 'hashref') { 1755: if(!defined($value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1756: next; # Skip if hashref is undefined

Mutants (Total: 4, Killed: 4, Survived: 0)

1757: } 1758: if(ref($value) ne 'HASH') { 1759: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an hashref"); 1760: } 1761: } elsif($type eq 'scalar') { 1762: if(!defined($value)) { 1763: next; # Skip if undefined 1764: } 1765: if(ref($value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1766: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a scalar, not a " . ref($value) . ' reference'); 1767: } 1768: } elsif($type eq 'scalarref') {

Mutants (Total: 4, Killed: 4, Survived: 0)

1769: if(!defined($value)) { 1770: next; # Skip if undefined 1771: } 1772: if(ref($value) ne 'SCALAR') { 1773: my $got = ref($value) ? 'a ' . ref($value) . ' reference' : 'a plain scalar';

Mutants (Total: 1, Killed: 1, Survived: 0)

1774: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a scalar reference, not $got"); 1775: } 1776: } elsif($type eq 'stringref') {

Mutants (Total: 4, Killed: 4, Survived: 0)

1777: if(!defined($value)) { 1778: 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.

Mutants (Total: 1, Killed: 1, Survived: 0)

1782: if(ref($value)) { 1783: _rule_error($logger, $rules, "$rule_description: Parameter $param_label stringref transform must return a plain string, not a " . ref($value) . ' reference'); 1784: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1785: } elsif($type eq 'void') {

Mutants (Total: 4, Killed: 4, Survived: 0)

1786: if(scalar(keys %{$schema}) != 1) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1787: _error($logger, "$rule_description: type 'void' requires exactly one parameter in the schema"); 1788: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1789: if(defined($value)) { 1790: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be undef (void type accepts no value)");

Mutants (Total: 1, Killed: 1, Survived: 0)

1791: } 1792: } elsif(($type eq 'boolean') || ($type eq 'bool')) { 1793: if(!defined($value)) { 1794: next; # Skip if bool is undefined 1795: } 1796: if(defined(my $b = $Readonly::Values::Boolean::booleans{$value})) { 1797: $value = $b; 1798: } else { 1799: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be a boolean"); 1800: } 1801: } elsif($type eq 'coderef') { 1802: if(!defined($value)) { 1803: next; # Skip if code is undefined 1804: } 1805: if(ref($value) ne 'CODE') { 1806: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a coderef, not a ref to " . ref($value));

Mutants (Total: 1, Killed: 1, Survived: 0)

1807: } 1808: } elsif($type eq 'regex') { 1809: if(!defined($value)) { 1810: next; 1811: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1812: if(ref($value) ne 'Regexp') { 1813: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a compiled regex (qr//)" .

Mutants (Total: 1, Killed: 1, Survived: 0)

1814: (ref($value) ? ", not a " . ref($value) . " reference" : ", not a plain scalar")); 1815: } 1816: } elsif($type eq 'handle') { 1817: if(!defined($value)) { 1818: next; 1819: } 1820: my $is_handle = 0; 1821: if(ref($value) eq 'GLOB' && defined(fileno($value))) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1822: $is_handle = 1; 1823: } elsif(Scalar::Util::blessed($value) && $value->isa('IO::Handle')) { 1824: $is_handle = 1; 1825: } else { 1826: $is_handle = defined(eval { fileno($value) });

Mutants (Total: 1, Killed: 1, Survived: 0)

1827: } 1828: unless($is_handle) { 1829: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a file handle"); 1830: } 1831: } elsif($type eq 'arraylike') { 1832: if(!defined($value)) { 1833: next;

Mutants (Total: 1, Killed: 1, Survived: 0)

1834: } 1835: unless(ref($value) eq 'ARRAY' || (Scalar::Util::blessed($value) && overload::Method($value, '@{}'))) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1836: _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: if(!defined($value)) { 1840: next; 1841: } 1842: unless(ref($value) eq 'HASH' || (Scalar::Util::blessed($value) && overload::Method($value, '%{}'))) { 1843: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a hash reference or hash-like object"); 1844: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1845: } elsif($type eq 'codelike') { 1846: if(!defined($value)) { 1847: next; 1848: } 1849: unless(ref($value) eq 'CODE' || (Scalar::Util::blessed($value) && overload::Method($value, '&{}'))) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1850: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a code reference or code-like object"); 1851: } 1852: } elsif($type eq 'invocant') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1853: if(!defined($value)) { 1854: next; 1855: } 1856: unless(Scalar::Util::blessed($value) || (!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/)) { 1857: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be a blessed object or a class name");

Mutants (Total: 1, Killed: 1, Survived: 0)

1858: } 1859: } elsif($type eq 'object') { 1860: if(!defined($value)) { 1861: next; # Skip if object is undefined 1862: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1863: if(!Scalar::Util::blessed($value)) { 1864: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must be an object"); 1865: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1866: } elsif(my $custom_type = $custom_types->{$type}) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1867: if($custom_type->{'transform'}) { 1868: # The custom type has a transform embedded within it 1869: if(ref($custom_type->{'transform'}) eq 'CODE') { 1870: $value = &{$custom_type->{'transform'}}($value); 1871: } else { 1872: _error($logger, "$rule_description: transforms must be a code ref"); 1873: } 1874: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1875: validate_strict({ input => { $key => $value }, schema => { $key => $custom_type }, custom_types => $custom_types }); 1876: } else { 1877: _error($logger, "$rule_description: Unknown type '$type'");

Mutants (Total: 1, Killed: 1, Survived: 0)

1878: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1879: } elsif(($rule_name eq 'min') || ($rule_name eq 'minimum')) { 1880: if(!defined($rules->{'type'})) { 1881: _error($logger, "$rule_description: Don't know type of $param_label to determine its minimum value $rule_value"); 1882: } 1883: my $type = lc($rules->{'type'}); 1884: if(exists($custom_types->{$type}->{'min'}) || exists($custom_types->{$type}->{minimum})) { 1885: $rule_value = $custom_types->{$type}->{'min'} // $custom_types->{$type}->{minimum}; 1886: $type = $custom_types->{$type}->{'type'};

Mutants (Total: 1, Killed: 1, Survived: 0)

1887: } 1888: if(($type eq 'string') || ($type eq 'str') || ($type eq 'stringref')) { 1889: if($rule_value < 0) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1890: _rule_error($logger, $rules, "$rule_description: Parameter $param_label has meaningless minimum value that is less than zero");

Mutants (Total: 1, Killed: 1, Survived: 0)

1891: } 1892: if(!defined($value)) { 1893: if($rule_value > 0 && !$is_optional) { 1894: _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must be at least $rule_value character" . ($rule_value == 1 ? '' : 's')); 1895: $invalid_args{$key} = 1; 1896: } 1897: next; 1898: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1899: if(defined(my $len = _number_of_characters($value))) { 1900: if($len < $rule_value) { 1901: _rule_error($logger, $rules, "$rule_description: Parameter $param_label too short, ($len characters), must be at least $rule_value characters");

Mutants (Total: 1, Killed: 1, Survived: 0)

1902: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

1903: } 1904: } else { 1905: _rule_error($logger, $rules, "$rule_description: Parameter $param_label can't be decoded");

Mutants (Total: 1, Killed: 1, Survived: 0)

1906: $invalid_args{$key} = 1; 1907: } 1908: } elsif($type eq 'arrayref') { 1909: if(!defined($value)) { 1910: if($rule_value > 0 && !$is_optional) { 1911: _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must have at least $rule_value member" . ($rule_value > 1 ? 's' : ''));

Mutants (Total: 1, Killed: 1, Survived: 0)

1912: $invalid_args{$key} = 1; 1913: } 1914: next; 1915: } 1916: if(scalar(@{$value}) < $rule_value) { 1917: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must have at least $rule_value member" . (($rule_value > 1) ? 's' : '')); 1918: $invalid_args{$key} = 1; 1919: } 1920: } elsif($type eq 'hashref') { 1921: if(!defined($value)) { 1922: if($rule_value > 0 && !$is_optional) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1923: _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must contain at least $rule_value keys"); 1924: $invalid_args{$key} = 1; 1925: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1926: next; 1927: } 1928: if(scalar(keys(%{$value})) < $rule_value) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1929: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must contain at least $rule_value keys"); 1930: $invalid_args{$key} = 1; 1931: } 1932: } elsif(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) { 1933: if(!defined($value)) { 1934: if($rule_value > 0 && !$is_optional) { 1935: _rule_error($logger, $rules, "$rule_description: Parameter $param_label is undefined, but must be at least $rule_value");

Mutants (Total: 1, Killed: 1, Survived: 0)

1936: $invalid_args{$key} = 1; 1937: } 1938: next; 1939: } 1940: if(Scalar::Util::looks_like_number($value)) { 1941: if($value < $rule_value) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1942: if($rules->{'error_msg'}) { 1943: _error($logger, $rules->{'error_msg'}); 1944: } elsif(($type eq 'integer') && ($value == 0)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1945: _error($logger, "$rule_description: Parameter $param_label ($value) must be a positive number");

Mutants (Total: 1, Killed: 1, Survived: 0)

1946: } elsif(($type eq 'integer') && ($value == 1)) { 1947: _error($logger, "$rule_description: Parameter $param_label ($value) must be a positive, non-zero number"); 1948: } else { 1949: _error($logger, "$rule_description: Parameter $param_label ($value) must be at least $rule_value"); 1950: } 1951: $invalid_args{$key} = 1; 1952: next; 1953: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1954: } else { 1955: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be a number"); 1956: _unreachable($logger); # Defensive: _error always croaks, so this is never reached.

Mutants (Total: 1, Killed: 1, Survived: 0)

1957: } 1958: } else { 1959: _error($logger, "$rule_description: Parameter $param_label of type '$type' has meaningless min value $rule_value"); 1960: } 1961: } elsif($rule_name eq 'max') {

Mutants (Total: 1, Killed: 1, Survived: 0)

1962: if(!defined($rules->{'type'})) { 1963: _error($logger, "$rule_description: Don't know type of $param_label to determine its maximum value $rule_value"); 1964: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1965: my $type = lc($rules->{'type'}); 1966: if(exists($custom_types->{$type}->{'max'})) { 1967: $rule_value = $custom_types->{$type}->{'max'}; 1968: $type = $custom_types->{$type}->{'type'}; 1969: } 1970: if(($type eq 'string') || ($type eq 'str') || ($type eq 'stringref')) {

Mutants (Total: 1, Killed: 1, Survived: 0)

1971: if(!defined($value)) { 1972: next; # Skip if string is undefined 1973: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1974: if(defined(my $len = _number_of_characters($value))) { 1975: if($len > $rule_value) { 1976: _rule_error($logger, $rules, "$rule_description: Parameter $param_label too long, ($len characters), must be no longer than $rule_value"); 1977: $invalid_args{$key} = 1; 1978: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1979: } else { 1980: _rule_error($logger, $rules, "$rule_description: Parameter $param_label can't be decoded"); 1981: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

1982: } 1983: } elsif($type eq 'arrayref') { 1984: if(!defined($value)) { 1985: next; # Skip if string is undefined 1986: } 1987: if(scalar(@{$value}) > $rule_value) { 1988: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must contain no more than $rule_value items"); 1989: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

1990: } 1991: } elsif($type eq 'hashref') { 1992: if(!defined($value)) { 1993: next; # Skip if hash is undefined 1994: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1995: if(scalar(keys(%{$value})) > $rule_value) { 1996: _rule_error($logger, $rules, "$rule_description: Parameter $param_label must contain no more than $rule_value keys"); 1997: $invalid_args{$key} = 1; 1998: } 1999: } elsif(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2000: if(!defined($value)) { 2001: next; # Skip if hash is undefined 2002: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2003: if(Scalar::Util::looks_like_number($value)) { 2004: if($value > $rule_value) { 2005: if($rules->{'error_msg'}) { 2006: _error($logger, $rules->{'error_msg'});

Mutants (Total: 1, Killed: 1, Survived: 0)

2007: } elsif(($type eq 'integer') && ($value == 0)) { 2008: _error($logger, "$rule_description: Parameter $param_label ($value) must be a negative number");

Mutants (Total: 1, Killed: 1, Survived: 0)

2009: } elsif(($type eq 'integer') && ($value == -1)) { 2010: _error($logger, "$rule_description: Parameter $param_label ($value) must be a negative, non-zero number"); 2011: } else { 2012: _error($logger, "$rule_description: Parameter $param_label ($value) must be no more than $rule_value"); 2013: } 2014: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

2015: next;

Mutants (Total: 1, Killed: 1, Survived: 0)

2016: } 2017: } else { 2018: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be a number"); 2019: _unreachable($logger); # Defensive: _error always croaks, so this is never reached. 2020: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2021: } else { 2022: _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: if(!defined($value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2026: next; # Skip if string is undefined 2027: } 2028: eval { 2029: my $re = (ref($rule_value) eq 'Regexp') ? $rule_value : qr/\Q$rule_value\E/; 2030: if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) {

Mutants (Total: 1, Killed: 0, Survived: 1)
2031: # all{} short-circuits on first failure and allocates no temp array 2032: unless(all { $_ =~ $re } @{$value}) { 2033: _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: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must match pattern '$re'"); 2037: } 2038: 1; 2039: }; 2040: if($@) { 2041: _rule_error($logger, $rules, "$rule_description: Parameter $param_label regex '$rule_value' error: $@"); 2042: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

2043: } 2044: } elsif($rule_name eq 'nomatch') {

Mutants (Total: 1, Killed: 1, Survived: 0)

2045: if(!defined($value)) { 2046: 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: my $re = (ref($rule_value) eq 'Regexp') ? $rule_value : qr/\Q$rule_value\E/; 2051: eval { 2052: if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) { 2053: # any{} short-circuits on first match and allocates no temp array 2054: if(any { $_ =~ $re } @{$value}) { 2055: _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: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must not match pattern '$rule_value'"); 2059: $invalid_args{$key} = 1; 2060: } 2061: 1; 2062: }; 2063: if($@) { 2064: _rule_error($logger, $rules, "$rule_description: Parameter $param_label regex '$rule_value' error: $@"); 2065: $invalid_args{$key} = 1; 2066: } 2067: } elsif($rule_name eq 'bnf') { 2068: if(!defined($value)) { 2069: next; # Skip if value is undefined 2070: } 2071: if(ref($rule_value) ne 'ARRAY') { 2072: _error($logger, "$rule_description: Parameter $param_label 'bnf' rule must be an arrayref of grammar lines");

Mutants (Total: 1, Killed: 1, Survived: 0)

2073: }

Mutants (Total: 7, Killed: 7, Survived: 0)

2074: require Params::Validate::Strict::BNF; 2075: my $matcher = Params::Validate::Strict::BNF::bnf_to_matcher($rule_value); 2076: unless($matcher->($value)) { 2077: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) does not match the BNF grammar");

Mutants (Total: 1, Killed: 1, Survived: 0)

2078: $invalid_args{$key} = 1; 2079: } 2080: } elsif(($rule_name eq 'memberof') || ($rule_name eq 'enum') || ($rule_name eq 'values')) { 2081: if(!defined($value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2082: next; # Skip if string is undefined 2083: } 2084: if(ref($rule_value) eq 'ARRAY') { 2085: unless(_value_in_list($value, $rule_value, $rules->{'type'} // '', $rules->{'case_sensitive'})) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2086: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must be one of ", join(', ', @{$rule_value})); 2087: $invalid_args{$key} = 1; 2088: } 2089: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

2090: _rule_error($logger, $rules, "$rule_description: Parameter $param_label rule ($rule_value) must be an array reference");

Mutants (Total: 3, Killed: 3, Survived: 0)

2091: } 2092: } elsif($rule_name eq 'notmemberof') { 2093: if(!defined($value)) { 2094: next; # Skip if string is undefined 2095: } 2096: if(ref($rule_value) eq 'ARRAY') { 2097: if(_value_in_list($value, $rule_value, $rules->{'type'} // '', $rules->{'case_sensitive'})) { 2098: _rule_error($logger, $rules, "$rule_description: Parameter $param_label ($value) must not be one of ", join(', ', @{$rule_value})); 2099: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

2100: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2101: } else { 2102: _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: if(!defined($value)) { 2106: next; # Skip if object not given 2107: } 2108: if($rules->{'type'} eq 'object') { 2109: if(!$value->isa($rule_value)) { 2110: _error($logger, "$rule_description: Parameter $param_label must be a '$rule_value' object got a " . (ref($value) ? ref($value) : $value) . ' object instead');

Mutants (Total: 1, Killed: 1, Survived: 0)

2111: $invalid_args{$key} = 1; 2112: } 2113: } else { 2114: _error($logger, "$rule_description: Parameter $param_label has meaningless isa value $rule_value"); 2115: } 2116: } elsif($rule_name eq 'can') { 2117: if(!defined($value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2118: next; # Skip if object not given 2119: } 2120: if(($rules->{'type'} eq 'object') || ($rules->{'type'} eq 'invocant')) { 2121: if(ref($rule_value) eq 'ARRAY') { 2122: # List of methods 2123: foreach my $method(@{$rule_value}) { 2124: if(!$value->can($method)) { 2125: _error($logger, "$rule_description: Parameter $param_label must be an object that understands the $method method");

Mutants (Total: 1, Killed: 1, Survived: 0)

2126: $invalid_args{$key} = 1; 2127: } 2128: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2129: } elsif(!ref($rule_value)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2130: if(!$value->can($rule_value)) { 2131: _error($logger, "$rule_description: Parameter $param_label must be an object that understands the $rule_value method"); 2132: $invalid_args{$key} = 1; 2133: } 2134: } else { 2135: _error($logger, "$rule_description: 'can' rule for Parameter $param_label must be either a scalar or an arrayref"); 2136: } 2137: } else { 2138: _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: if(!defined($value)) { 2142: next;

Mutants (Total: 1, Killed: 1, Survived: 0)

2143: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2144: if(ref($rule_value) && ref($rule_value) ne 'ARRAY') { 2145: _error($logger, "$rule_description: 'classcan' rule for Parameter $param_label must be either a scalar or an arrayref"); 2146: } 2147: unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) { 2148: $invalid_args{$key} = 1; 2149: _error($logger, "$rule_description: Parameter $param_label must be a valid class name"); 2150: _unreachable($logger); # Defensive: _error always croaks, so this is never reached. 2151: } 2152: foreach my $method (ref($rule_value) ? @{$rule_value} : ($rule_value)) { 2153: # Always a method call, so an overridden can() is respected

Mutants (Total: 1, Killed: 1, Survived: 0)

2154: unless($value->can($method)) { 2155: _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that understands the $method method"); 2156: $invalid_args{$key} = 1; 2157: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2158: } 2159: } elsif($rule_name eq 'does') { 2160: if(!defined($value)) { 2161: next; # Skip if object not given 2162: } 2163: if($rules->{'type'} eq 'object') {

Mutants (Total: 4, Killed: 4, Survived: 0)

2164: unless(Scalar::Util::blessed($value) && $value->DOES($rule_value)) { 2165: _error($logger, "$rule_description: Parameter $param_label must be an object that does '$rule_value'"); 2166: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

2167: } 2168: } else { 2169: _error($logger, "$rule_description: Parameter $param_label has meaningless does value '$rule_value' for parameter type $rules->{type}"); 2170: }

Mutants (Total: 2, Killed: 2, Survived: 0)

2171: } elsif($rule_name eq 'classisa') { 2172: if(!defined($value)) { 2173: next; 2174: } 2175: unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ && $value->isa($rule_value)) { 2176: _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that isa '$rule_value'"); 2177: $invalid_args{$key} = 1; 2178: } 2179: } elsif($rule_name eq 'subclass') { 2180: if(!defined($value)) { 2181: next;

Mutants (Total: 1, Killed: 1, Survived: 0)

2182: } 2183: unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 2184: && $value ne $rule_value && $value->isa($rule_value)) { 2185: _error($logger, "$rule_description: Parameter $param_label ($value) must be a strict subclass of '$rule_value'"); 2186: $invalid_args{$key} = 1; 2187: } 2188: } elsif($rule_name eq 'classdoes') {

Mutants (Total: 1, Killed: 1, Survived: 0)

2189: if(!defined($value)) { 2190: next; 2191: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2192: unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ && $value->DOES($rule_value)) { 2193: _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that does '$rule_value'"); 2194: $invalid_args{$key} = 1; 2195: } 2196: } elsif($rule_name eq 'driver') { 2197: if(!defined($value)) { 2198: next; 2199: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2200: unless(!ref($value) && $value =~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) { 2201: $invalid_args{$key} = 1; 2202: _error($logger, "$rule_description: Parameter $param_label must be a valid class name"); 2203: _unreachable($logger); # Defensive: _error always croaks, so this is never reached. 2204: } 2205: (my $file = $value) =~ s{::}{/}g; 2206: $file .= '.pm'; 2207: eval { require $file };

Mutants (Total: 1, Killed: 1, Survived: 0)

2208: if($@) { 2209: $invalid_args{$key} = 1; 2210: _error($logger, "$rule_description: Parameter $param_label ($value) could not be loaded: $@"); 2211: _unreachable($logger); # Defensive: _error always croaks, so this is never reached. 2212: } 2213: unless($value->isa($rule_value)) { 2214: _error($logger, "$rule_description: Parameter $param_label ($value) must be a class that isa '$rule_value'"); 2215: $invalid_args{$key} = 1; 2216: } 2217: } elsif($rule_name eq 'element_type') { 2218: if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) { 2219: my $type = $rule_value; 2220: my $custom_type = $custom_types->{$rule_value}; 2221: if($custom_type && $custom_type->{'type'}) { 2222: $type = $custom_type->{'type'}; 2223: } 2224: foreach my $member(@{$value}) { 2225: if($custom_type && $custom_type->{'transform'}) { 2226: # The custom type has a transform embedded within it 2227: if(ref($custom_type->{'transform'}) eq 'CODE') { 2228: $member = &{$custom_type->{'transform'}}($member); 2229: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

2230: _error($logger, "$rule_description: transforms must be a code ref"); 2231: } 2232: } 2233: if(($type eq 'string') || ($type eq 'Str')) { 2234: if(ref($member)) { 2235: _rule_error($logger, $rules, "$param_label can only contain strings"); 2236: $invalid_args{$key} = 1; 2237: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2238: } elsif($type eq 'integer') { 2239: if(ref($member) || ($member =~ /\D/)) { 2240: _rule_error($logger, $rules, "$param_label can only contain integers (found $member)"); 2241: $invalid_args{$key} = 1;

Mutants (Total: 1, Killed: 1, Survived: 0)

2242: } 2243: } elsif(($type eq 'number') || ($rule_value eq 'float')) { 2244: if(ref($member) || ($member !~ /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/)) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2245: _rule_error($logger, $rules, "$param_label can only contain numbers (found $member)"); 2246: $invalid_args{$key} = 1; 2247: } 2248: } elsif($type eq 'object') {

Mutants (Total: 1, Killed: 1, Survived: 0)

2249: if(!Scalar::Util::blessed($member)) { 2250: _rule_error($logger, $rules, "$param_label can only contain objects (found $member)"); 2251: $invalid_args{$key} = 1; 2252: } 2253: } else { 2254: _error($logger, "BUG: Add $type to element_type list"); 2255: } 2256: } 2257: } else { 2258: _error($logger, "$rule_description: Parameter $param_label has meaningless element_type value $rule_value"); 2259: } 2260: } elsif($rule_name eq 'element_isa') {

Mutants (Total: 2, Killed: 2, Survived: 0)

2261: if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) { 2262: foreach my $member (@{$value}) { 2263: unless(Scalar::Util::blessed($member) && $member->isa($rule_value)) { 2264: $invalid_args{$key} = 1; 2265: _rule_error($logger, $rules, "$rule_description: Parameter $param_label can only contain '$rule_value' objects"); 2266: _unreachable($logger); # Defensive: _error always croaks, so this is never reached.

Mutants (Total: 1, Killed: 1, Survived: 0)

2267: } 2268: } 2269: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

2270: _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

Mutants (Total: 2, Killed: 2, Survived: 0)

2276: } elsif($rule_name eq 'nullable') { 2277: # Already handled at the beginning of the loop (same as optional)

Mutants (Total: 2, Killed: 2, Survived: 0)

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: if($rule_value eq 'unix_timestamp') { 2292: if($value < 0 || $value > 2147483647) { 2293: _error($logger, "Invalid Unix timestamp: $value"); 2294: } 2295: } elsif($rule_value eq 'identifier') { 2296: if(defined($value) && $value !~ /\A[A-Za-z_]\w*\z/) { 2297: _error($logger, "Invalid Perl identifier: $value"); 2298: } 2299: } elsif($rule_value eq 'class_name') { 2300: if(defined($value) && $value !~ /\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) { 2301: _error($logger, "Invalid Perl class name: $value"); 2302: } 2303: } elsif($rule_value eq 'filename') { 2304: if(defined($value)) { 2305: # A single path component, at most 255 bytes when encoded as UTF-8 2306: my $bytes = $value; 2307: utf8::encode($bytes); 2308: if(($value eq '') || ($value eq '.') || ($value eq '..') 2309: || ($value =~ m{[/\0]}) || (length($bytes) > 255)) { 2310: _error($logger, "Invalid filename: $value"); 2311: } 2312: } 2313: } else { 2314: _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: if(($rules->{'type'} eq 'arrayref') || ($rules->{'type'} eq 'ArrayRef')) { 2319: if(ref($value) eq 'ARRAY') { 2320: 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: my $is_field_schema = (ref($rule_value) eq 'HASH') && !exists($rule_value->{'type'}); 2328: my %inner = (custom_types => $custom_types); 2329: if($is_field_schema) { 2330: $inner{input} = $member; 2331: $inner{schema} = $rule_value; 2332: } else { 2333: $inner{input} = { $key => $member }; 2334: $inner{schema} = { $key => $rule_value }; 2335: } 2336: if(!validate_strict(\%inner)) { 2337: $invalid_args{$key} = 1; 2338: } 2339: } 2340: } elsif(defined($value)) { # Allow undef for optional values 2341: _error($logger, "$rule_description: nested schema: Parameter '$value' must be an arrayref"); 2342: } 2343: } elsif($rules->{'type'} eq 'hashref') { 2344: if(ref($rule_value) eq 'HASH') {

Mutants (Total: 1, Killed: 1, Survived: 0)

2345: # Apply nested defaults before validation 2346: my $nested_with_defaults = _apply_nested_defaults($value, $rule_value); 2347: if(scalar keys(%{$nested_with_defaults})) {

Mutants (Total: 2, Killed: 2, Survived: 0)

2348: if(my $new_args = validate_strict({ input => $nested_with_defaults, schema => $rule_value, custom_types => $custom_types })) { 2349: $value = $new_args;

Mutants (Total: 2, Killed: 2, Survived: 0)

2350: } else { 2351: $invalid_args{$key} = 1; 2352: } 2353: } 2354: } else { 2355: _error($logger, "$rule_description: nested schema: Parameter '$value' must be an hashref"); 2356: } 2357: } else { 2358: _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: if(ref($rule_value) eq 'CODE') { 2362: if(my $error = &{$rule_value}($args)) { 2363: _error($logger, "$rule_description: $param_label not valid: $error"); 2364: $invalid_args{$key} = 1; 2365: } 2366: } else { 2367: # _error($logger, "$rule_description: Parameter $param_label: 'validate' only supports coderef, not $value"); 2368: _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: unless (defined &$rule_value) { 2373: _error($logger, "$rule_description: callback for $param_label must be a code reference"); 2374: } 2375: my $res = $rule_value->($value, $args, $schema, $key); 2376: unless ($res) { 2377: _rule_error($logger, $rules, "$rule_description: Parameter $param_label failed custom validation"); 2378: $invalid_args{$key} = 1; 2379: }

Mutants (Total: 2, Killed: 2, Survived: 0)

2380: } elsif($rule_name eq 'position') { 2381: 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: _unreachable($logger); 2385: } 2386: if($rule_value =~ /\D/) { 2387: _error($logger, "$rule_description: Parameter $param_label: 'position' must be a positive integer"); 2388: } 2389: } elsif($rule_name eq 'slurp') { 2390: if($rule_value && $are_positional_args != 1) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2391: _error($logger, "$rule_description: Parameter $param_label: 'slurp' is only valid in positional-argument schemas (all parameters need a 'position')");

Mutants (Total: 2, Killed: 2, Survived: 0)

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: _error($logger, "$rule_description: Unknown rule '$rule_name'"); 2398: } 2399: } 2400: } elsif(ref($rules) eq 'ARRAY') {

Mutants (Total: 2, Killed: 2, Survived: 0)

2401: 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: my $rc = 0; 2406: my @types; 2407: foreach my $rule(@{$rules}) { 2408: if(ref($rule) ne 'HASH') { 2409: _error($logger, "$rule_description: Parameter $param_label rules must be a hash reference"); 2410: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2411: if(!defined($rule->{'type'})) { 2412: _error($logger, "$rule_description: Parameter $param_label is missing a type in an alternative"); 2413: } 2414: push @types, $rule->{'type'}; 2415: my $result;

Mutants (Total: 1, Killed: 1, Survived: 0)

2416: eval { 2417: $result = validate_strict({ input => { $key => $value }, schema => { $key => $rule }, logger => undef, custom_types => $custom_types }); 2418: }; 2419: if(!$@) { 2420: # Capture coercion performed by the successful sub-validation

Mutants (Total: 2, Killed: 2, Survived: 0)

2421: # (e.g. integer/number coercion) so the outer scope sees it. 2422: $value = $result->{$key} if(defined($result)); 2423: $rc = 1; 2424: last; 2425: } 2426: } 2427: if(!$rc) { 2428: _error($logger, "$rule_description: Parameter $param_label must be one of " . join(', ', @types)); 2429: $invalid_args{$key} = 1; 2430: } 2431: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

2432: _error($logger, "$rule_description: Parameter $param_label schema is empty arrayref"); 2433: } 2434: } elsif(ref($rules)) { 2435: _error($logger, 'rules must be a hash reference or string'); 2436: } 2437: 2438: $validated_args{$key} = $value; 2439: } 2440: 2441: # Validate parameter relationships ●2442 → 2447 → 2459 2442: 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: foreach my $name ($has_needs ? sort(keys %{$schema}) : ()) { 2448: my $rules = $schema->{$name}; 2449: next unless(ref($rules) eq 'HASH' && defined($rules->{'needs'})); 2450: my $needs = $rules->{'needs'}; 2451: if(ref($needs) && ref($needs) ne 'ARRAY') { 2452: _error($logger, "$schema_description: 'needs' for parameter '$name' must be a string or an arrayref"); 2453: }

Mutants (Total: 3, Killed: 3, Survived: 0)

2454: foreach my $required (ref($needs) ? @{$needs} : ($needs)) { 2455: push @relationships, { type => 'dependency', param => $name, requires => $required }; 2456: } 2457: }

Mutants (Total: 4, Killed: 4, Survived: 0)

2458: ●2459 → 2459 → 2463 2459: if(@relationships) { 2460: _validate_relationships(\%validated_args, \@relationships, $logger, $schema_description); 2461: } 2462: ●2463 → 2463 → 2478 2463: if(my $cross_validation = $params->{'cross_validation'}) { 2464: foreach my $validator_name(keys %{$cross_validation}) { 2465: my $validator = $cross_validation->{$validator_name}; 2466: if((!ref($validator)) || (ref($validator) ne 'CODE')) { 2467: _error($logger, "$schema_description: cross_validation $validator is not a code snippet");

Mutants (Total: 3, Killed: 3, Survived: 0)

2468: _unreachable($logger); # Defensive: _error always croaks, so this is never reached. 2469: } 2470: if(my $error = &{$validator}(\%validated_args, $validator)) { 2471: _error($logger, $error);

Mutants (Total: 2, Killed: 2, Survived: 0)

2472: # We have no idea which parameters are still valid, so let's invalidate them all 2473: return; 2474: } 2475: } 2476: } 2477: ●2478 → 2478 → 2482 2478: foreach my $key(keys %invalid_args) { 2479: delete $validated_args{$key}; 2480: } 2481: ●2482 → 2482 → 2499 2482: if($are_positional_args == 1) { 2483: my @rc; 2484: foreach my $key (keys %{$schema}) { 2485: # Use exists() rather than if(my $value = ...) so that falsy but

Mutants (Total: 1, Killed: 1, Survived: 0)

2486: # valid coerced values (integer 0, empty string, undef from an 2487: # absent optional) are not silently dropped from the return array.

Mutants (Total: 1, Killed: 1, Survived: 0)

2488: if(exists $validated_args{$key}) { 2489: my $value = delete $validated_args{$key};

Mutants (Total: 1, Killed: 1, Survived: 0)

2490: my $position = $schema->{$key}->{'position'}; 2491: if(defined($rc[$position])) { 2492: _error($logger, "$schema_description: $key: position $position appears twice"); 2493: } 2494: $rc[$position] = $value; 2495: } 2496: } 2497: return \@rc; 2498: } 2499: return \%validated_args; 2500: } 2501: 2502: =head2 compile_schema 2503: 2504: my $validator = compile_schema(\%schema);

Mutants (Total: 1, Killed: 1, Survived: 0)

2505: my $result = $validator->(\%input);

Mutants (Total: 1, Killed: 1, Survived: 0)

2506: 2507: # with optional keyword args 2508: my $validator = compile_schema(\%schema, 2509: description => 'User registration', 2510: custom_types => \%types, 2511: unknown_parameter_handler => 'warn', 2512: ); 2513: 2514: Pre-captures a schema (and any optional keyword arguments accepted by 2515: C<validate_strict>) into a reusable validator closure. Calling the returned 2516: coderef is equivalent to: 2517: 2518: validate_strict(schema => \%schema, input => \%input, %opts); 2519: 2520: but the schema is analysed once, when C<compile_schema> is called, rather than 2521: on every call - useful when the same schema is applied repeatedly in a hot 2522: path. The result, the errors raised, the warnings and the logger calls are

Mutants (Total: 1, Killed: 1, Survived: 0)

2523: exactly those of C<validate_strict>; only the speed differs. 2524:

Mutants (Total: 1, Killed: 1, Survived: 0)

2525: Fields that use a built-in type (C<string>, C<integer>, C<number>, C<boolean>, 2526: C<arrayref>, C<hashref>, C<scalar>, C<coderef>, C<object> and their synonyms) 2527: with any of the rules C<min>, C<max>, C<optional>, C<nullable>, C<default>, 2528: C<description>, C<error_msg>, C<matches>, C<memberof> (also C<enum> and

Mutants (Total: 1, Killed: 1, Survived: 0)

2529: C<values>) and C<case_sensitive> are validated by a fast path. Any other

Mutants (Total: 1, Killed: 1, Survived: 0)

2530: field - one that uses C<callback>, C<transform>, union types, C<aliases>, 2531: C<needs>, nested C<schema>, custom types, the class and element rules, and so

Mutants (Total: 1, Killed: 1, Survived: 0)

2532: on - is validated by the general code, as before, so using such a rule never 2533: changes behaviour; it just does not get faster. Positional schemas (those with

Mutants (Total: 3, Killed: 3, Survived: 0)

2534: C<position>) are not precompiled. On a typical five-field schema a compiled 2535: validator runs about three times faster than calling C<validate_strict>

Mutants (Total: 3, Killed: 3, Survived: 0)

2536: directly. 2537:

Mutants (Total: 3, Killed: 3, Survived: 0)

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

Mutants (Total: 3, Killed: 3, Survived: 0)

2540: 2541: =head3 Arguments 2542:

Mutants (Total: 1, Killed: 1, Survived: 0)

2543: =over 4 2544: 2545: =item * C<\%schema> (required) 2546: 2547: The validation schema as a hashref or arrayref, identical to the C<schema> 2548: argument of C<validate_strict>. 2549: 2550: =item * C<%opts> (optional) 2551: 2552: Any keyword arguments accepted by C<validate_strict> other than C<schema> 2553: and C<input>: C<description>, C<custom_types>, 2554: C<unknown_parameter_handler>, C<logger>, C<relationships>, 2555: C<cross_validation>, etc. 2556: 2557: =back 2558: 2559: =head3 Returns

Mutants (Total: 1, Killed: 1, Survived: 0)

2560:

Mutants (Total: 1, Killed: 1, Survived: 0)

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

Mutants (Total: 1, Killed: 1, Survived: 0)

2563: =head3 API SPECIFICATION 2564: 2565: =head4 Input 2566: 2567: { 2568: schema => { type => ['hashref', 'arrayref'] }, 2569: opts => { type => 'hashref', optional => 1 }, # passed as trailing key/value pairs 2570: } 2571: 2572: =head4 Output 2573: 2574: { type => 'coderef' } 2575: 2576: The returned coderef has the signature C<sub ($input) -E<gt> \%validated>, 2577: and croaks in the same way as C<validate_strict>. 2578: 2579: =cut 2580: 2581: sub compile_schema 2582: { ●2583 → 2584 → 2590 2583: my ($schema, %opts) = @_; 2584: unless(ref($schema) eq 'HASH' || ref($schema) eq 'ARRAY') { 2585: 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 → 2590 → 2599 2590: if(grep { exists($opts{$_}) } qw(schema input args _compiled)) { 2591: return sub { 2592: my $input = shift; 2593: return validate_strict(schema => $schema, input => $input, %opts); 2594: }; 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 → 2599 → 2604 2599: if(ref($schema) eq 'ARRAY') { 2600: my $normalised = eval { _schema_from_arrayref($schema, undef) }; 2601: $schema = $normalised if($normalised); 2602: } 2603: 2604: my $compiled = _compile_schema($schema, $opts{'custom_types'});

Mutants (Total: 1, Killed: 0, Survived: 1)
2605: my %params = (schema => $schema, %opts); 2606: $params{'_compiled'} = $compiled if($compiled); 2607: 2608: return sub { 2609: # Setting input in place avoids copying the option hash on every call.

Mutants (Total: 1, Killed: 1, Survived: 0)

2610: # local restores it on exit, so re-entrant and recursive use is safe. 2611: local $params{'input'} = shift;

Mutants (Total: 1, Killed: 1, Survived: 0)

2612: return validate_strict(\%params); 2613: }; 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

Mutants (Total: 2, Killed: 2, Survived: 0)

2628: # a single implementation of the complicated rules and of every error path. 2629: sub _compile_schema 2630: { ●2631 → 2655 → 2675 2631: my ($schema, $custom_types) = @_; 2632: 2633: return unless(ref($schema) eq 'HASH'); 2634: return if(exists($schema->{'members'})); # 'members' may denote a wrapper 2635: 2636: my %type_info = (

Mutants (Total: 2, Killed: 2, Survived: 0)

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: my %scalar_like = map { $_ => 1 } qw(string str integer int number float num double boolean bool scalar); 2648: my %allowed = map { $_ => 1 } qw(type min max optional nullable default description error_msg 2649: matches memberof enum values case_sensitive);

Mutants (Total: 1, Killed: 1, Survived: 0)

2650: 2651: my $has_aliases = 0; 2652: my $has_needs = 0; 2653: my %fields; 2654: 2655: foreach my $key (keys %{$schema}) { 2656: my $rules = $schema->{$key}; 2657: next unless(defined($rules)); 2658: 2659: 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: return if(exists($rules->{'position'}) || exists($rules->{'slurp'})); 2663: $has_aliases = 1 if(ref($rules->{'aliases'}) eq 'ARRAY');

Mutants (Total: 1, Killed: 1, Survived: 0)

2664: $has_needs = 1 if(defined($rules->{'needs'})); 2665: } elsif(ref($rules) eq '') { 2666: $rules = { type => $rules }; # as the generic code does 2667: } else { 2668: next; 2669: } 2670: 2671: my $f = _compile_field($key, $rules, \%type_info, \%scalar_like, \%allowed, $custom_types); 2672: $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: 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. 2688: sub _compile_field 2689: { ●2690 → 2695 → 2705 2690: my ($key, $rules, $type_info, $scalar_like, $allowed, $custom_types) = @_; 2691: 2692: return if(grep { !$allowed->{$_} } keys %{$rules}); 2693: 2694: # Every value must be a plain scalar, apart from the two that may be refs 2695: foreach my $name (keys %{$rules}) { 2696: next if($name eq 'default'); 2697: my $v = $rules->{$name}; 2698: if(ref($v)) { 2699: next if($name eq 'matches' && ref($v) eq 'Regexp'); 2700: next if(($name eq 'memberof' || $name eq 'enum' || $name eq 'values') && ref($v) eq 'ARRAY'); 2701: return; 2702: } 2703: } 2704: ●2705 → 2711 → 2716 2705: my $type = $rules->{'type'}; 2706: return unless(defined($type) && !ref($type)); 2707: my $info = $type_info->{lc($type)} or return; 2708: return if(ref($custom_types) eq 'HASH' && exists($custom_types->{lc($type)})); 2709: 2710: my $label = "'$key'"; 2711: if(exists($rules->{'description'})) { 2712: return unless(defined($rules->{'description'})); 2713: $label = "'$key' ($rules->{description})"; 2714: } 2715: ●2716 → 2729 → 2735 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: default => $rules->{'default'}, 2726: ); 2727: 2728: # optional wins over nullable if both are present, as in validate_strict 2729: if(exists($rules->{'optional'})) { 2730: $f{'opt'} = $rules->{'optional'} ? 1 : 0; 2731: } elsif($rules->{'nullable'}) { 2732: $f{'opt'} = 1; 2733: } 2734: ●2735 → 2735 → 2742 2735: foreach my $bound (qw(min max)) { 2736: next unless(exists($rules->{$bound})); 2737: my $v = $rules->{$bound}; 2738: return unless(defined($v) && $info->[1] && Scalar::Util::looks_like_number($v)); 2739: return if($bound eq 'min' && $info->[1] eq 's' && $v < 0); # meaningless; generic code reports it 2740: $f{$bound} = $v; 2741: } ●2742 → 2744 → 2752 2742: return if(defined($f{'min'}) && defined($f{'max'}) && $f{'min'} > $f{'max'}); 2743: 2744: if(exists($rules->{'matches'})) { 2745: return unless($scalar_like->{lc($type)}); 2746: my $m = $rules->{'matches'}; 2747: return unless(defined($m)); 2748: $f{'re'} = (ref($m) eq 'Regexp') ? $m : qr/\Q$m\E/; 2749: $f{'match_src'} = $m; 2750: } 2751: ●2752 → 2753 → 2762 2752: my @list_names = grep { exists($rules->{$_}) } qw(memberof enum values); 2753: if(@list_names) { 2754: # exactly one, and not combined with min/max (which is an error) 2755: return if(@list_names > 1 || exists($rules->{'min'}) || exists($rules->{'max'})); 2756: return unless(ref($rules->{$list_names[0]}) eq 'ARRAY'); 2757: $f{'list'} = $rules->{$list_names[0]}; 2758: } elsif(exists($rules->{'case_sensitive'})) { 2759: return; # meaningless without a list; leave it to the generic code 2760: } 2761: 2762: 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. 2775: sub _schema_from_arrayref 2776: { ●2777 → 2780 → 2791 2777: my ($arrayref, $logger) = @_; 2778: 2779: my %schema; 2780: foreach my $spec (@{$arrayref}) { 2781: _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: unless exists($spec->{'name'}); 2785: my %rule = %{$spec}; 2786: my $name = delete $rule{'name'}; 2787: _error($logger, "validate_strict: duplicate parameter '$name' in arrayref schema") 2788: if exists($schema{$name}); 2789: $schema{$name} = \%rule; 2790: } 2791: return \%schema; 2792: } 2793: 2794: # Return number of visible characters not number of bytes 2795: # Ensure string is decoded into Perl characters 2796: sub _number_of_characters 2797: { ●2798 → 2802 → 2806 2798: my $value = $_[0]; 2799: 2800: return if(!defined($value)); 2801: 2802: if($value !~ /[^[:ascii:]]/) { 2803: return length($value); 2804: } 2805: # Decode only if it's not already a Perl character string 2806: $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: return scalar(() = $value =~ /\X/g); 2813: } 2814: 2815: sub _apply_nested_defaults { ●2816 → 2819 → 2832 2816: my ($input, $schema) = @_; 2817: my %result = %$input; 2818: 2819: foreach my $key (keys %$schema) { 2820: my $rules = $schema->{$key}; 2821: 2822: if (ref $rules eq 'HASH' && exists $rules->{default} && !exists $result{$key}) { 2823: $result{$key} //= $rules->{default}; 2824: } 2825: 2826: # Recursively handle nested schema 2827: if((ref $rules eq 'HASH') && $rules->{schema} && (ref $result{$key} eq 'HASH')) { 2828: $result{$key} = _apply_nested_defaults($result{$key}, $rules->{schema}); 2829: } 2830: } 2831: 2832: return \%result; 2833: } 2834: 2835: sub _validate_relationships { ●2836 → 2840 → 0 2836: my ($validated_args, $relationships, $logger, $description) = @_; 2837: 2838: return unless ref($relationships) eq 'ARRAY'; 2839: 2840: foreach my $rel (@$relationships) { 2841: my $type = $rel->{type} or next; 2842: 2843: if ($type eq 'mutually_exclusive') { 2844: _validate_mutually_exclusive($validated_args, $rel, $logger, $description); 2845: } elsif ($type eq 'required_group') { 2846: _validate_required_group($validated_args, $rel, $logger, $description); 2847: } elsif ($type eq 'conditional_requirement') { 2848: _validate_conditional_requirement($validated_args, $rel, $logger, $description); 2849: } elsif ($type eq 'dependency') { 2850: _validate_dependency($validated_args, $rel, $logger, $description); 2851: } elsif ($type eq 'value_constraint') { 2852: _validate_value_constraint($validated_args, $rel, $logger, $description); 2853: } elsif ($type eq 'value_conditional') { 2854: _validate_value_conditional($validated_args, $rel, $logger, $description); 2855: } else { 2856: _error($logger, "Unknown relationship type $type"); 2857: } 2858: } 2859: } 2860: 2861: sub _validate_mutually_exclusive { ●2862 → 2869 → 0 2862: my ($args, $rel, $logger, $description) = @_; 2863: 2864: my @params = @{$rel->{params} || []}; 2865: return unless @params >= 2; 2866: 2867: my @present = grep { _param_defined($args, $_) } @params; 2868: 2869: if (@present > 1) { 2870: my $msg = $rel->{description} || 'Cannot specify both ' . join(' and ', @present); 2871: _error($logger, "$description: $msg"); 2872: } 2873: } 2874: 2875: sub _validate_required_group { ●2876 → 2883 → 0 2876: my ($args, $rel, $logger, $description) = @_; 2877: 2878: my @params = @{$rel->{params} || []}; 2879: return unless @params >= 2; 2880: 2881: my @present = grep { _param_defined($args, $_) } @params; 2882: 2883: if (@present == 0) { 2884: my $msg = $rel->{description} || 2885: 'Must specify at least one of: ' . join(', ', @params); 2886: _error($logger, "$description: $msg"); 2887: } 2888: } 2889: 2890: sub _validate_conditional_requirement { ●2891 → 2897 → 0 2891: my ($args, $rel, $logger, $description) = @_; 2892: 2893: my $if_param = $rel->{if} or return; 2894: my $then_param = $rel->{then_required} or return; 2895: 2896: # If the condition parameter is present and defined 2897: if (_param_defined($args, $if_param)) { 2898: # Check if it's truthy (for booleans and general values) 2899: if ($args->{$if_param}) { 2900: # Then the required parameter must also be present 2901: unless (_param_defined($args, $then_param)) { 2902: my $msg = $rel->{description} || "When $if_param is specified, $then_param is required"; 2903: _error($logger, "$description: $msg"); 2904: } 2905: } 2906: } 2907: } 2908: 2909: sub _validate_dependency { ●2910 → 2916 → 0 2910: my ($args, $rel, $logger, $description) = @_; 2911: 2912: my $param = $rel->{param} or return; 2913: my $requires = $rel->{requires} or return; 2914: 2915: # If param is present, requires must also be present 2916: if (_param_defined($args, $param)) { 2917: unless (_param_defined($args, $requires)) { 2918: my $msg = $rel->{description} || "$param requires $requires to be specified"; 2919: _error($logger, "$description: $msg"); 2920: } 2921: } 2922: } 2923: 2924: sub _validate_value_constraint { ●2925 → 2934 → 0 2925: my ($args, $rel, $logger, $description) = @_; 2926: 2927: my $if_param = $rel->{if} or return; 2928: my $then_param = $rel->{then} or return; 2929: my $operator = $rel->{operator} or return; 2930: my $value = $rel->{value}; 2931: return unless defined $value; 2932: 2933: # If the condition parameter is present and truthy 2934: if (_param_defined($args, $if_param) && $args->{$if_param}) { 2935: # Check if the then parameter exists 2936: if (_param_defined($args, $then_param)) { 2937: my $actual = $args->{$then_param}; 2938: my $valid = 0; 2939: 2940: if ($operator eq '==') { 2941: $valid = ($actual == $value); 2942: } elsif ($operator eq '!=') { 2943: $valid = ($actual != $value); 2944: } elsif ($operator eq '<') { 2945: $valid = ($actual < $value); 2946: } elsif ($operator eq '<=') { 2947: $valid = ($actual <= $value); 2948: } elsif ($operator eq '>') { 2949: $valid = ($actual > $value); 2950: } elsif ($operator eq '>=') { 2951: $valid = ($actual >= $value); 2952: } 2953: 2954: unless ($valid) { 2955: my $msg = $rel->{description} || "When $if_param is specified, $then_param must be $operator $value (got $actual)"; 2956: _error($logger, "$description: $msg"); 2957: } 2958: } 2959: } 2960: } 2961: 2962: sub _validate_value_conditional { ●2963 → 2971 → 0 2963: my ($args, $rel, $logger, $description) = @_; 2964: 2965: my $if_param = $rel->{if} or return; 2966: my $equals = $rel->{equals}; 2967: my $then_param = $rel->{then_required} or return; 2968: return unless defined $equals; 2969: 2970: # If the parameter has the specific value 2971: if (_param_defined($args, $if_param)) { 2972: if ($args->{$if_param} eq $equals) { 2973: # Then the required parameter must be present 2974: unless (_param_defined($args, $then_param)) { 2975: my $msg = $rel->{description} || 2976: "When $if_param equals '$equals', $then_param is required"; 2977: _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. 2986: sub _rule_error 2987: { 2988: my ($logger, $rules, @default_parts) = @_; 2989: _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. 2997: my %_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). 3003: sub _value_in_list 3004: { ●3005 → 3016 → 3021 3005: my ($value, $list, $type, $case_sensitive) = @_; 3006: my $is_numeric = ($type eq 'integer') || ($type eq 'number') || ($type eq 'float'); 3007: 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: my $ckey = Scalar::Util::refaddr($list) . ($is_numeric ? 'n' : $is_icase ? 'i' : 's'); 3012: 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: if(defined($entry) && !defined($entry->[0])) { 3017: delete $_pvs_memberof_cache{$ckey}; 3018: $entry = undef; 3019: } 3020: ●3021 → 3021 → 3038 3021: unless(defined $entry) { 3022: my $lookup; 3023: if($is_numeric) { 3024: # Normalise to numeric value so "1" and "1.0" hash identically. 3025: $lookup = { map { ($_ + 0) => 1 } @{$list} }; 3026: } elsif($is_icase) { 3027: $lookup = { map { lc($_) => 1 } @{$list} }; 3028: } else { 3029: $lookup = { map { $_ => 1 } @{$list} }; 3030: } 3031: # Store [weak_ref_to_list, lookup_hash] - weak ref does not prevent GC. 3032: my $weak = $list; 3033: Scalar::Util::weaken($weak); 3034: $_pvs_memberof_cache{$ckey} = [$weak, $lookup]; 3035: $entry = $_pvs_memberof_cache{$ckey}; 3036: } 3037: 3038: my $lookup = $entry->[1]; 3039: return $is_numeric ? exists($lookup->{$value + 0}) 3040: : $is_icase ? exists($lookup->{lc($value)}) 3041: : exists($lookup->{$value}); 3042: } 3043: 3044: # Return true when $args->{$param} is both present (exists) and defined. 3045: sub _param_defined 3046: { 3047: my ($args, $param) = @_; 3048: 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. 3053: sub _unreachable 3054: { ●3055 → 3059 → 3062 3055: my $logger = shift; 3056: my @call_details = caller(0); 3057: my $message = 'BUG: this code should not be reachable. Please report it to the maintainer'; 3058: 3059: if($logger) { 3060: $logger->error(__PACKAGE__, ' line ', $call_details[2], ": $message"); 3061: } 3062: Carp::croak(__PACKAGE__, ' line ', $call_details[2], ": $message"); 3063: } 3064: 3065: # Helper to log error or croak 3066: sub _error 3067: { ●3068 → 3075 → 3078 3068: my $logger = shift; 3069: my $message = join('', @_); 3070: # Strip ASCII control characters to prevent log-injection / CRLF attacks 3071: # when user-supplied values appear in the message. 3072: $message =~ s/[[:cntrl:]]/ /g; 3073: 3074: my @call_details = caller(0); 3075: if($logger) { 3076: $logger->error(__PACKAGE__, ' line ', $call_details[2], ": $message"); 3077: } 3078: Carp::croak(__PACKAGE__, ' line ', $call_details[2], ": $message"); 3079: } 3080: 3081: # Helper to log warning or carp 3082: sub _warn 3083: { ●3084 → 3089 → 0 3084: my $logger = shift; 3085: my $message = join('', @_); 3086: # Strip ASCII control characters to prevent log-injection / CRLF attacks. 3087: $message =~ s/[[:cntrl:]]/ /g; 3088: 3089: if($logger) { 3090: $logger->warn(__PACKAGE__, ": $message"); 3091: } else { 3092: Carp::carp(__PACKAGE__, ": $message"); 3093: } 3094: } 3095: 3096: =head1 AUTHOR 3097: 3098: Nigel Horne, C<< <njh at nigelhorne.com> >> 3099: 3100: =encoding utf-8 3101: 3102: =head1 FORMAL SPECIFICATION 3103: 3104: [PARAM_NAME, VALUE, TYPE_NAME, CONSTRAINT_VALUE] 3105: 3106: ValidationRule ::= SimpleType | ComplexRule | UnionType 3107: 3108: SimpleType ::= string | integer | number | float | boolean | scalar 3109: | scalarref | stringref | arrayref | hashref | coderef 3110: | object | void | regex | handle 3111: | arraylike | hashlike | codelike | invocant 3112: 3113: UnionType ::= seq SimpleType -- at least two members; written as type => ['a', 'b'] 3114: 3115: ComplexRule == [ 3116: type: SimpleType | UnionType; 3117: min: ℕ₁; 3118: max: ℕ₁; 3119: optional: 𝔹; 3120: matches: REGEX; 3121: regex: REGEX; 3122: nomatch: REGEX; 3123: memberof: seq VALUE; 3124: enum: seq VALUE; 3125: values: seq VALUE; 3126: notmemberof: seq VALUE; 3127: callback: FUNCTION; 3128: isa: TYPE_NAME; 3129: does: ROLE_NAME; 3130: can: METHOD_NAME | seq METHOD_NAME; 3131: classisa: TYPE_NAME; 3132: subclass: TYPE_NAME; 3133: classdoes: ROLE_NAME; 3134: classcan: METHOD_NAME | seq METHOD_NAME; 3135: element_isa: TYPE_NAME; 3136: needs: PARAM_NAME | seq PARAM_NAME; 3137: driver: TYPE_NAME; 3138: semantic: 'unix_timestamp' | 'identifier' | 'class_name' | 'filename'; 3139: aliases: seq PARAM_NAME; 3140: slurp: 𝔹; 3141: position: â„•â‚€; 3142: default: VALUE; 3143: transform: FUNCTION; 3144: error_msg: STRING 3145: ] 3146: 3147: Schema == PARAM_NAME ⇸ ValidationRule 3148: 3149: Arguments == PARAM_NAME ⇸ VALUE 3150: 3151: ValidatedResult == PARAM_NAME ⇸ VALUE 3152: 3153: ∀ rule: ComplexRule • 3154: rule.min ≤ rule.max ∧ 3155: ¬((rule.memberof ∨ rule.enum ∨ rule.values) ∧ rule.min) ∧ 3156: ¬((rule.memberof ∨ rule.enum ∨ rule.values) ∧ rule.max) ∧ 3157: ¬(rule.notmemberof ∧ rule.min) ∧ 3158: ¬(rule.notmemberof ∧ rule.max) 3159: 3160: ∀ schema: Schema; args: Arguments • 3161: dom(validate_strict(schema, args)) ⊆ dom(schema) ∪ dom(args) 3162: 3163: validate_strict: Schema × Arguments → ValidatedResult 3164: 3165: ∀ schema: Schema; args: Arguments • 3166: let result == validate_strict(schema, args) • 3167: (∀ name: dom(schema) ∩ dom(args) • 3168: name ∈ dom(result) ⇒ 3169: type_matches(result(name), schema(name))) ∧ 3170: (∀ name: dom(schema) • 3171: ¬optional(schema(name)) ⇒ name ∈ dom(args)) 3172: 3173: type_matches: VALUE × ValidationRule → 𝔹 3174: 3175: =head1 EXAMPLE 3176: 3177: use Params::Get; 3178: use Params::Validate::Strict; 3179: 3180: sub where_am_i 3181: { 3182: my $params = Params::Validate::Strict::validate_strict({ 3183: args => Params::Get::get_params(undef, \@_), 3184: description => 'Print a string of latitude and longitude', 3185: error_msg => 'Latitude is a number between +/- 90, longitude is a number between +/- 180', 3186: members => { 3187: 'latitude' => { 3188: type => 'number', 3189: min => -90, 3190: max => 90 3191: }, 'longitude' => { 3192: type => 'number', 3193: min => -180, 3194: max => 180 3195: } 3196: } 3197: }); 3198: 3199: print 'You are at ', $params->{'latitude'}, ', ', $params->{'longitude'}, "\n"; 3200: } 3201: 3202: where_am_i({ latitude => 3.14, longitude => -155 }); 3203: 3204: =head1 BUGS 3205: 3206: Known limitations: 3207: 3208: =over 4 3209: 3210: =item * C<semantic =E<gt> 'filename'> checks for a single path component only. 3211: It does not reject characters that are illegal only on some platforms, 3212: such as C<:> or C<\> on Windows, and does not check that the file exists. 3213: 3214: =item * C<classisa>, C<subclass>, C<classdoes> and C<classcan> require the class to be loaded already; 3215: use C<driver> to load it first. 3216: 3217: =item * Grammars passed to C<bnf> are cached for the life of the process and never evicted. 3218: 3219: =back 3220: 3221: Please report any other bugs as described in L</SUPPORT>. 3222: 3223: =head1 SECURITY 3224: 3225: =head2 Taint mode 3226: 3227: This module does B<not> untaint its return values. 3228: When running under Perl's taint mode (C<-T>), any value that was derived from 3229: tainted external input (C<$ENV{}>, C<STDIN>, etc.) will remain tainted in the 3230: validated result, even if the module accepted it. 3231: Callers that require untainted values must perform their own regex capture after 3232: validation, for example: 3233: 3234: my $validated = validate_strict(%args); 3235: my ($safe_name) = ($validated->{name} =~ /\A([\w\s]+)\z/); 3236: 3237: =head2 User-supplied regex patterns 3238: 3239: The C<matches> rule accepts pre-compiled C<qr//> objects supplied by the caller. 3240: A pathologically constructed pattern (e.g. C<qr/(a+)+b/>) can cause catastrophic 3241: backtracking and peg a CPU core when matched against a hostile input value. 3242: Use possessive quantifiers (C<++>) or atomic groups (C<< (?>...) >>) in any 3243: C<matches> pattern that will be applied to untrusted data. 3244: 3245: =head2 Error message content 3246: 3247: Error and warning messages produced by this module may include the parameter 3248: value supplied by the caller. 3249: The module strips ASCII control characters (including CR and LF) from all 3250: messages before passing them to the logger or croaking, to prevent log-injection 3251: and HTTP response-splitting attacks. 3252: Callers should nevertheless apply their own output encoding before including any 3253: validated value in an HTTP response, HTML page, or structured log entry. 3254: 3255: =head1 SEE ALSO 3256: 3257: =over 4 3258: 3259: =item * L<Test Dashboard|https://nigelhorne.github.io/Params-Validate-Strict/coverage/> 3260: 3261: =item * L<Data::Processor> 3262: 3263: =item * L<Params::Get> 3264: 3265: =item * L<Params::Smart> 3266: 3267: This is where the ideas for C<aliases>, C<slurp> and C<compile_schema> came from. 3268: 3269: =item * L<Params::Util> 3270: 3271: This is where the ideas for C<regex>, C<handle>, C<arraylike>, C<hashlike>, C<codelike>, C<invocant> came from. 3272: 3273: =item * L<Params::SomeUtil> 3274: 3275: A maintained fork of L<Params::Util> 1.07 with bug fixes. The same type-predicate ideas apply. 3276: 3277: =item * L<Params::Validate> 3278: 3279: =item * L<Return::Set> 3280: 3281: =item * L<App::Test::Generator> 3282: 3283: =back 3284: 3285: =head1 SUPPORT 3286: 3287: This module is provided as-is without any warranty. 3288: 3289: Please report any bugs or feature requests to C<bug-params-validate-strict at rt.cpan.org>, 3290: or through the web interface at 3291: L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Params-Validate-Strict>. 3292: I will be notified, and then you'll 3293: automatically be notified of progress on your bug as I make changes. 3294: 3295: You can find documentation for this module with the perldoc command. 3296: 3297: perldoc Params::Validate::Strict 3298: 3299: You can also look for information at: 3300: 3301: =over 4 3302: 3303: =item * MetaCPAN 3304: 3305: L<https://metacpan.org/dist/Params-Validate-Strict> 3306: 3307: =item * RT: CPAN's request tracker 3308: 3309: L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Params-Validate-Strict> 3310: 3311: =item * CPAN Testers' Matrix 3312: 3313: L<http://matrix.cpantesters.org/?dist=Params-Validate-Strict> 3314: 3315: =item * CPAN Testers Dependencies 3316: 3317: L<http://deps.cpantesters.org/?module=Params::Validate::Strict> 3318: 3319: =back 3320: 3321: =head1 LICENSE AND COPYRIGHT 3322: 3323: Copyright 2025-2026 Nigel Horne. 3324: 3325: This program is released under the following licence: GPL2. 3326: If you use it, 3327: please let me know. 3328: 3329: =cut 3330: 3331: 1; 3332: 3333: __END__