Skip to content

Commit d037580

Browse files
hungthai1401phanan
andauthored
feat: allow directly accessing property (#5)
Co-authored-by: Phan An <me@phanan.net>
1 parent 3b435f8 commit d037580

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,16 @@ $data->toArray(); // ['email' => 'alice@company.tld', 'password' => 'SoSecureWow
203203

204204
$data->compact()->toArray(); // ['email' => 'alice@company.tld', 'password' => 'SoSecureWow']
205205
```
206+
* `DataTransferObject::get($name): mixed` returns the value of `$name` property.
207+
```php
208+
$data = UserCreationData::make([
209+
'email' => 'alice@company.tld',
210+
'password' => 'SoSecureWow',
211+
]);
212+
213+
$data->get('email'); // 'alice@company.tld'
214+
$data->password; // 'SoSecureWow'
215+
```
206216

207217
## Differences from spatie/data-transfer-object
208218

src/DataTransferObject.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,15 @@ public function set($name, $value = null): self
4444
return $this;
4545
}
4646

47+
/**
48+
* @param $name
49+
* @return mixed
50+
*/
51+
public function get($name)
52+
{
53+
return $this->{$name};
54+
}
55+
4756
/** @return static */
4857
public function unset(string ...$names): self
4958
{
@@ -139,4 +148,12 @@ public function __unset($name): void
139148
{
140149
unset($this->data[$name]);
141150
}
151+
152+
/** @return mixed */
153+
public function __get($name)
154+
{
155+
$this->assertPropertyExists($name);
156+
157+
return $this->data[$name];
158+
}
142159
}

tests/Unit/DataTransferObjectTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,4 +203,20 @@ public function testNestedDTO(): void
203203

204204
self::assertEquals(['nested' => ['sample_prop' => 'sample']], $data->compact()->toArray());
205205
}
206+
207+
public function testPropertyAccess(): void
208+
{
209+
$data = SampleData::make(['simple_prop' => 'foo']);
210+
211+
self::assertSame('foo', $data->get('simple_prop'));
212+
self::assertSame('foo', $data->simple_prop);
213+
}
214+
215+
public function testAccessingNonExistentPropertyWillThrow(): void
216+
{
217+
self::expectException(DataTransferObjectException::class);
218+
self::expectExceptionMessage('Public property $nope does not exist in class Tests\Fixtures\SampleData');
219+
220+
echo SampleData::make()->nope;
221+
}
206222
}

0 commit comments

Comments
 (0)