diff --git a/CHANGELOG.md b/CHANGELOG.md index 12b1603..153c03a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. Updates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles. ## [Unreleased][unreleased] +### Fixed +- Multi value validation and transformation if expected type is not array but instead expects array of specific type. For example if expected type is integer and value is array of integers, validation and transformation will pass. ## 3.4.3 ### Fixed diff --git a/src/Validation/InputType.php b/src/Validation/InputType.php index 08f90d2..ff60cce 100644 --- a/src/Validation/InputType.php +++ b/src/Validation/InputType.php @@ -9,5 +9,5 @@ class InputType public const DOUBLE = 'double'; public const FLOAT = 'float'; public const STRING = 'string'; - public const ARRAY = 'array'; + public const ARRAY = 'array'; // Returns array of mixed values. If you want to validate array of specific type use setMulti() with expected values in array } diff --git a/src/Validation/InputValidator.php b/src/Validation/InputValidator.php index c8d49b4..b998ce3 100644 --- a/src/Validation/InputValidator.php +++ b/src/Validation/InputValidator.php @@ -20,6 +20,10 @@ public function validate($value, $expectedType = null): ValidationResultInterfac return new ValidationResult(ValidationResult::STATUS_OK); } + if (is_array($value) && $expectedType !== InputType::ARRAY) { + return $this->validateMulti($value, $expectedType); + } + switch ($expectedType) { case InputType::BOOLEAN: if (!is_bool($value)) { @@ -67,6 +71,11 @@ public function transformType($value, $expectedType = null): mixed if ($value === null || $expectedType === null) { return $value; } + + if (is_array($value) && $expectedType !== InputType::ARRAY) { + return $this->transformMulti($value, $expectedType); + } + switch ($expectedType) { case InputType::BOOLEAN: if ($value === '1' || $value === 1 || $value === true || strtolower((string) $value) === 'true') { @@ -100,4 +109,30 @@ public function transformType($value, $expectedType = null): mixed } return $value; } + + /** + * @param mixed[] $value + */ + private function validateMulti(array $value, string $expectedType): ValidationResultInterface + { + foreach ($value as $item) { + $result = $this->validate($item, $expectedType); + if ($result->isOk() === false) { + return $result; + } + } + return new ValidationResult(ValidationResult::STATUS_OK); + } + + /** + * @param mixed[] $value + * @return mixed[] + */ + private function transformMulti(array $value, string $expectedType): array + { + foreach ($value as $key => $item) { + $value[$key] = $this->transformType($item, $expectedType); + } + return $value; + } }