respect-validation/docs/rules/Sorted.md
Henrique Moody 1f6c821fb6
Refactor "Sorted" rule
The sorted rule accepts a callback on its constructor that may be used
to filter values from inside the input. However, with the "Call" rule
one can archive almost the same result. Besides that particular
characteristic, its constructor accepts a boolean value to determine
whether the sorting is ascending or descending.

This commit will remove the callback from the constructor and replace
the boolean by a string which can be "ASC" or "DESC."

Along with those changes, this change will make a few more improvements:

- Make the exception message specific about the sorting direction;

- Allow the rule to validate also strings;

- Update documentation.

Co-authored-by: Danilo Correa <danilosilva87@gmail.com>
Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2019-03-10 18:31:03 +01:00

1.1 KiB

Sorted

  • Sorted(string $direction)

Validates whether the input is sorted in a certain order or not.

v::sorted('ASC')->validate([1, 2, 3]); // true
v::sorted('ASC')->validate('ABC'); // true
v::sorted('DESC')->validate([3, 2, 1]); // true
v::sorted('ASC')->validate([]); // true
v::sorted('ASC')->validate([1]); // true

You can also combine Call to create custom validations:

v::call(
        static function (array $input): array {
            return array_column($input, 'key');
        },
        v::sorted('ASC')
    )->validate([
        ['key' => 1],
        ['key' => 5],
        ['key' => 9],
    ]); // true

v::call('strval', v::sorted('DESC'))->validate(4321); // true

v::call('iterator_to_array', v::sorted())->validate(new ArrayIterator([1, 7, 4])); // false

Changelog

Version Description
2.0.0 Add support for strings
2.0.0 Do not use array keys to sort
2.0.0 Use sorting direction instead of boolean value
2.0.0 Do not accept callback in the constructor
1.1.1 Created

See also: