respect-validation/docs/rules/KeySet.md
Henrique Moody 2aa5e39c54
Improve KeySet rule
After changes in the key-related rules, the KeySet rule became unusable.
Besides, when evaluating an input, it wasn't reporting every single
failure because it would not validate the items in the array if they had
missing or extra keys.

This commit will make several improvements to the rule. It will create
some not(keyExists($key)) rules for the extra keys, which makes the
error reporting much better. A limit of 10 additional keys will show up
when asserting an input with extra keys. I put that limit in place to
prevent the creation of too many rules.
2024-12-02 20:09:47 +01:00

1.9 KiB

KeySet

  • KeySet(KeyRelated $rule, KeyRelated ...$rules)

Validates a keys in a defined structure.

v::keySet(
    v::keyExists('foo'),
    v::keyExists('bar')
)->validate(['foo' => 'whatever', 'bar' => 'something']); // true

It will validate the keys in the array with the rules passed in the constructor.

v::keySet(
    v::key('foo', v::intVal())
)->validate(['foo' => 42]); // true

v::keySet(
    v::key('foo', v::intVal())
)->validate(['foo' => 'string']); // false

Extra keys are not allowed:

v::keySet(
    v::key('foo', v::intVal())
)->validate(['foo' => 42, 'bar' => 'String']); // false

Missing required keys are not allowed:

v::keySet(
    v::key('foo', v::intVal()),
    v::key('bar', v::stringType()),
    v::key('baz', v::boolType())
)->validate(['foo' => 42, 'bar' => 'String']); // false

Missing non-required keys are allowed:

v::keySet(
    v::key('foo', v::intVal()),
    v::key('bar', v::stringType()),
    v::keyOptional('baz', v::boolType())
)->validate(['foo' => 42, 'bar' => 'String']); // true

Alternatively, you can pass a chain of key-related rules to keySet():

v::keySet(
    v::create()
        ->key('foo', v::intVal())
        ->key('bar', v::stringType())
        ->keyOptional('baz', v::boolType())
)->validate(['foo' => 42, 'bar' => 'String']); // true

It is not possible to negate keySet() rules with not().

The keys' order is not considered in the validation.

Categorization

  • Arrays
  • Nesting
  • Structures

Changelog

Version Description
3.0.0 Requires at least one key-related rule
2.3.0 KeySet is NonNegatable, fixed message with extra keys
1.0.0 Created

See also: