From 9858f663f62d3498e239df88fcd77d9d7a237c37 Mon Sep 17 00:00:00 2001 From: Philipp Dieter Date: Sun, 21 Nov 2021 23:09:16 +0100 Subject: [PATCH] [FEATURE] Backport function to convert form data input by schema --- Classes/Traits/ValidationTrait.php | 58 ++++++++++++++++++++++++++++++ composer.json | 3 +- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/Classes/Traits/ValidationTrait.php b/Classes/Traits/ValidationTrait.php index 6b4a75a..3803181 100644 --- a/Classes/Traits/ValidationTrait.php +++ b/Classes/Traits/ValidationTrait.php @@ -16,6 +16,7 @@ use \Opis\JsonSchema\{ Validator, ValidationResult, ValidationError, Schema }; use Cjel\TemplatesAide\Utility\ArrayUtility; +use Sarhan\Flatten\Flatten; use TYPO3\CMS\Extbase\Utility\LocalizationUtility; /** @@ -39,6 +40,63 @@ trait ValidationTrait */ protected $errorLabels = []; + /** + * validate objects + * + * @param $input + * @param schema + * @return void + */ + protected function convertInputBySchema($input, $schema) + { + $flatten = new Flatten(); + $schemaFlat = $flatten->flattenToArray($schema); + $typesList = []; + foreach ($schemaFlat as $index => $row) { + if (substr($index, -5) == '.type') { + $dataIndex = preg_replace( + '/(\.)(properties\.|items\.)/', + '$1', + $index + ); + $dataIndex = preg_replace( + '/^properties\./', + '', + $dataIndex + ); + $dataIndex = preg_replace( + '/\.type$/', + '', + $dataIndex + ); + $typesList[$dataIndex] = $row; + } + } + foreach ($input as $index => $row) { + $rowType = $typesList[$index]; + if (!$rowType) { + continue; + } + switch ($rowType) { + case 'integer': + if (is_numeric($row)) { + settype($input[$index], $rowType); + } + break; + case 'boolean': + $testResult = filter_var( + $row, + FILTER_VALIDATE_BOOLEAN, + [FILTER_NULL_ON_FAILURE] + ); + if ($testResult === true || $testResult === false) { + $input[$index] = $testResult; + } + } + } + return $input; + } + /** * validate objects * diff --git a/composer.json b/composer.json index 3b3fc76..d02a60f 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,8 @@ } ], "require": { - "typo3/cms-core": "8.7.0 - 9.5.99" + "typo3/cms-core": "8.7.0 - 9.5.99", + "sarhan/php-flatten": "^4.0" }, "autoload": { "psr-4": {