diff --git a/src/Lazy.php b/src/Lazy.php index 66401d67b..7f1e475bd 100644 --- a/src/Lazy.php +++ b/src/Lazy.php @@ -46,4 +46,14 @@ public function isDefaultIncluded(): bool { return $this->defaultIncluded ?? false; } + + public function __get(string $name): mixed + { + return $this->resolve()->$name; + } + + public function __call(string $name, array $arguments): mixed + { + return call_user_func_array([$this->resolve(), $name], $arguments); + } } diff --git a/tests/DataTest.php b/tests/DataTest.php index ec58cd327..2a9a20956 100644 --- a/tests/DataTest.php +++ b/tests/DataTest.php @@ -58,6 +58,7 @@ use Spatie\LaravelData\Tests\Fakes\Transformers\ConfidentialDataTransformer; use Spatie\LaravelData\Tests\Fakes\Transformers\StringToUpperTransformer; use Spatie\LaravelData\Tests\Fakes\UlarData; +use Spatie\LaravelData\Tests\Fakes\UnionData; use Spatie\LaravelData\Transformers\DateTimeInterfaceTransformer; use Spatie\LaravelData\WithData; @@ -2278,3 +2279,21 @@ public function __construct( expect($invaded->_except)->toBeEmpty(); expect($invaded->_wrap)->toBeNull(); }); + +it('can fetch lazy union data', function () { + $data = UnionData::from(1); + + expect($data->id)->toBe(1); + expect($data->simple->string)->toBe('A'); + expect($data->dataCollection->toCollection()->pluck('string')->toArray())->toBe(['B', 'C']); + expect($data->fakeModel->string)->toBe('lazy'); +}); + +it('can fetch non-lazy union data', function () { + $data = UnionData::from('A'); + + expect($data->id)->toBe(1); + expect($data->simple->string)->toBe('A'); + expect($data->dataCollection->toCollection()->pluck('string')->toArray())->toBe(['B', 'C']); + expect($data->fakeModel->string)->toBe('non-lazy'); +}); diff --git a/tests/Fakes/UnionData.php b/tests/Fakes/UnionData.php new file mode 100644 index 000000000..751742af5 --- /dev/null +++ b/tests/Fakes/UnionData.php @@ -0,0 +1,45 @@ + SimpleData::from('A')), + dataCollection: Lazy::create(fn () => SimpleData::collection(['B', 'C'])), + fakeModel: Lazy::create(fn () => FakeModel::factory()->create([ + 'string' => 'lazy', + ])), + ); + } + + public static function fromString(string $name): self + { + return new self( + id: 1, + simple: SimpleData::from($name), + dataCollection: SimpleData::collection(['B', 'C']), + fakeModel: FakeModel::factory()->create([ + 'string' => 'non-lazy', + ]), + ); + } +}