diff --git a/CHANGELOG.md b/CHANGELOG.md index 0043d05..d4d35c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +## v0.4.1 (2023-10-25) +* 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 [];