From ae47b309978f3d3083fdd81297b9e878c0c88123 Mon Sep 17 00:00:00 2001 From: Tom Wright Date: Wed, 25 Oct 2023 22:52:12 +0000 Subject: [PATCH 1/2] Coerce null scalar values if type required Signed-off-by: Tom Wright --- CHANGELOG.md | 2 ++ src/Processor/BoolNative.php | 2 +- src/Processor/FloatNative.php | 2 +- src/Processor/IntNative.php | 2 +- src/ProcessorTrait.php | 10 ++++++++++ 5 files changed, 15 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0043d05..0135200 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,5 @@ +* Coerce null scalar values if type required + ## v0.4.0 (2023-10-18) * Refactored main interface methods * Refactored package file structure diff --git a/src/Processor/BoolNative.php b/src/Processor/BoolNative.php index 8bdc77a..1333212 100644 --- a/src/Processor/BoolNative.php +++ b/src/Processor/BoolNative.php @@ -35,7 +35,7 @@ public function getOutputTypes(): array public function coerce(mixed $value): ?bool { if ($value === null) { - return null; + return $this->isRequired() ? false : null; } if (is_bool($value)) { diff --git a/src/Processor/FloatNative.php b/src/Processor/FloatNative.php index c8b285f..3a28f35 100644 --- a/src/Processor/FloatNative.php +++ b/src/Processor/FloatNative.php @@ -34,7 +34,7 @@ public function getOutputTypes(): array public function coerce(mixed $value): ?float { if ($value === null) { - return null; + return $this->isRequired() ? 0 : null; } return Coercion::toFloat($value); diff --git a/src/Processor/IntNative.php b/src/Processor/IntNative.php index 41b868b..1d3da5a 100644 --- a/src/Processor/IntNative.php +++ b/src/Processor/IntNative.php @@ -34,7 +34,7 @@ public function getOutputTypes(): array public function coerce(mixed $value): ?int { if ($value === null) { - return null; + return $this->isRequired() ? 0 : null; } return Coercion::toInt($value); diff --git a/src/ProcessorTrait.php b/src/ProcessorTrait.php index 3aebb8b..9a79a20 100644 --- a/src/ProcessorTrait.php +++ b/src/ProcessorTrait.php @@ -157,6 +157,16 @@ protected function checkConstraintTypes( } + protected function isRequired(): bool + { + if (!isset($this->constraints['required'])) { + return false; + } + + return (bool)$this->constraints['required']->getParameter(); + } + + public function getDefaultConstraints(): array { return []; From f96fdaac29add127d599779deebcfdd0ebde4fd3 Mon Sep 17 00:00:00 2001 From: Tom Wright Date: Wed, 25 Oct 2023 22:52:38 +0000 Subject: [PATCH 2/2] Updated changelog Signed-off-by: Tom Wright --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0135200..d4d35c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,4 @@ +## v0.4.1 (2023-10-25) * Coerce null scalar values if type required ## v0.4.0 (2023-10-18)