diff --git a/src/DataModel.php b/src/DataModel.php index 9cbb3e9..872741a 100644 --- a/src/DataModel.php +++ b/src/DataModel.php @@ -240,7 +240,6 @@ public static function from(iterable|object|null $context = []): self $self->{$methods[$property_name]}($context[$context_key] ?? null, $context, $Attribute, $ReflectionProperty); continue; } - /** When a property name does not match a key name */ if (!array_key_exists($context_key, $context)) { if (isset($Describe->default)) { @@ -250,6 +249,10 @@ public static function from(iterable|object|null $context = []): self if (isset($Describe->required) && $Describe->required) { throw new PropertyRequiredException("Property: $property_name is required"); } + if (isset($Describe->missing_as_null) && $Describe?->missing_as_null) { + $self->{$property_name} = null; + continue; + } if (isset($ClassDescribe->missing_as_null) && $ClassDescribe?->missing_as_null) { $self->{$property_name} = null; continue; diff --git a/tests/Unit/Metadata/MissingAsNull/User.php b/tests/Unit/Metadata/MissingAsNull/User.php index 4f658d8..171dda2 100644 --- a/tests/Unit/Metadata/MissingAsNull/User.php +++ b/tests/Unit/Metadata/MissingAsNull/User.php @@ -2,12 +2,13 @@ namespace Tests\Unit\Metadata\MissingAsNull; +use Zerotoprod\DataModel\DataModel; use Zerotoprod\DataModel\Describe; #[Describe(['missing_as_null' => true])] class User { - use \Zerotoprod\DataModel\DataModel; + use DataModel; public ?string $name; diff --git a/tests/Unit/Metadata/MissingAsNullProperty/MissingAsNullTest.php b/tests/Unit/Metadata/MissingAsNullProperty/MissingAsNullTest.php new file mode 100644 index 0000000..73d6c99 --- /dev/null +++ b/tests/Unit/Metadata/MissingAsNullProperty/MissingAsNullTest.php @@ -0,0 +1,17 @@ +assertNull($User->name); + $this->assertEquals(2, $User->age); + } +} \ No newline at end of file diff --git a/tests/Unit/Metadata/MissingAsNullProperty/User.php b/tests/Unit/Metadata/MissingAsNullProperty/User.php new file mode 100644 index 0000000..0243707 --- /dev/null +++ b/tests/Unit/Metadata/MissingAsNullProperty/User.php @@ -0,0 +1,17 @@ + true])] +class User +{ + use \Zerotoprod\DataModel\DataModel; + + #[Describe(['missing_as_null' => true])] + public ?string $name; + + #[Describe(['default' => 2])] + public ?int $age; +} \ No newline at end of file