From 3d70e8a0756270a930ae03a7a54c5d90046e7d72 Mon Sep 17 00:00:00 2001 From: Ruben Van Assche Date: Thu, 13 Jun 2024 10:48:32 +0200 Subject: [PATCH] Fix #774 --- src/Normalizers/Normalized/NormalizedModel.php | 10 +++++++++- tests/CreationTest.php | 9 +++++++++ tests/Fakes/Models/DummyModel.php | 4 ++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Normalizers/Normalized/NormalizedModel.php b/src/Normalizers/Normalized/NormalizedModel.php index fbc46cb5b..22fcc082f 100644 --- a/src/Normalizers/Normalized/NormalizedModel.php +++ b/src/Normalizers/Normalized/NormalizedModel.php @@ -21,7 +21,15 @@ public function getProperty(string $name, DataProperty $dataProperty): mixed { $propertyName = $this->model::$snakeAttributes ? Str::snake($name) : $name; - return $this->properties[$propertyName] ?? $this->fetchNewProperty($propertyName, $dataProperty); + $value = array_key_exists($propertyName, $this->properties) + ? $this->properties[$propertyName] + : $this->fetchNewProperty($propertyName, $dataProperty); + + if ($value === null && ! $dataProperty->type->isNullable) { + return UnknownProperty::create(); + } + + return $value; } protected function initialize(Model $model): void diff --git a/tests/CreationTest.php b/tests/CreationTest.php index d4e7d0560..48ab6082a 100644 --- a/tests/CreationTest.php +++ b/tests/CreationTest.php @@ -235,6 +235,7 @@ 'boolean' => true, 'date' => CarbonImmutable::create(2020, 05, 16, 12, 00, 00), 'nullable_date' => null, + 'nullable_optional_date' => null, ]); $dataClass = new class () extends Data { @@ -245,6 +246,10 @@ public Carbon $date; public ?Carbon $nullable_date; + + public Optional|Carbon $optional_date; + + public Optional|null|Carbon $nullable_optional_date; }; $data = $dataClass::from(DummyModel::findOrFail($model->id)); @@ -253,9 +258,13 @@ ->string->toEqual('test') ->boolean->toBeTrue() ->nullable_date->toBeNull() + ->optional_date->toBeInstanceOf(Optional::class) + ->nullable_optional_date->toBeNull() ->and(CarbonImmutable::create(2020, 05, 16, 12, 00, 00)->eq($data->date))->toBeTrue(); }); + + it('can create a data object from a stdClass object', function () { $object = (object) [ 'string' => 'test', diff --git a/tests/Fakes/Models/DummyModel.php b/tests/Fakes/Models/DummyModel.php index 6f353edac..066063ca3 100644 --- a/tests/Fakes/Models/DummyModel.php +++ b/tests/Fakes/Models/DummyModel.php @@ -11,6 +11,8 @@ class DummyModel extends Model protected $casts = [ 'date' => 'datetime', 'nullable_date' => 'datetime', + 'optional_date' => 'datetime', + 'nullable_optional_date' => 'datetime', 'boolean' => 'boolean', ]; @@ -22,6 +24,8 @@ public static function migrate() $blueprint->string('string'); $blueprint->dateTime('date'); $blueprint->dateTime('nullable_date')->nullable(); + $blueprint->dateTime('optional_date')->nullable(); + $blueprint->dateTime('nullable_optional_date')->nullable(); $blueprint->boolean('boolean'); $blueprint->timestamps();